1 # $Id: IRSpy.pm,v 1.78 2007-03-19 18:52:20 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);
46 $res = $spy->check("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 tests => undef, # Tree of tests to be executed
97 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
99 $this->log("irspy", "starting up with database '$dbname'");
115 $this->{query} = $query;
119 # Explicitly nominate a set of targets to check, overriding the
120 # default which is to re-check everything in the database. Each
121 # target already in the database results in the existing record being
122 # updated; each new target causes a new record to be added.
128 $this->log("irspy", "setting explicit list of targets ",
129 join(", ", map { "'$_'" } @targets));
131 foreach my $target (@targets) {
132 my($host, $port, $db, $newtarget) = _parse_target_string($target);
133 if ($newtarget ne $target) {
134 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
135 $target = $newtarget; # This is written through the ref
137 push @qlist, cql_target($host, $port, $db);
140 $this->{targets} = \@targets;
141 $this->{query} = join(" or ", @qlist);
145 # Also used by ZOOM::IRSpy::Record
146 sub _parse_target_string {
149 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
150 if (!defined $host) {
152 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
153 $target = "$host:$port/$db";
155 die "$0: invalid target string '$target'"
158 return ($host, $port, $db, $target);
162 # Records must be fetched for all records satisfying $this->{query} If
163 # $this->{targets} is already set (i.e. a specific list of targets to
164 # check was specified by a call to targets()), then new, empty records
165 # will be made for any targets that are not already in the database.
171 my $targets = $this->{targets};
172 if (defined $targets) {
173 @targets = @$targets;
174 delete $this->{targets};
176 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
177 $this->log("irspy", "'", $this->{query}, "' found ",
178 $rs->size(), " target records");
179 delete $this->{query};
181 foreach my $i (1 .. $rs->size()) {
182 push @targets, render_record($rs, $i-1, "id");
186 my $n = $this->{activeSetSize};
187 $n = @targets if $n == 0 || $n > @targets;
190 foreach my $i (1..$n) {
191 push @connections, create ZOOM::IRSpy::Connection($this,
196 $this->{connections} = \@connections;
197 $this->{queue} = \@targets;
201 sub _irspy_to_zeerex {
203 my($conn, $save_xml) = @_;
204 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
207 unlink('/tmp/irspy_orig.xml');
208 open FH, '>/tmp/irspy_orig.xml'
209 or die "can't write irspy_orig.xml: $!";
210 print FH $irspy_doc->toString();
214 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
216 unlink('/tmp/irspy_transformed.xml');
217 open FH, '>/tmp/irspy_transformed.xml'
218 or die "can't write irspy_transformed.xml: $!";
219 print FH $result->toString();
223 return $result->documentElement();
227 sub _rewrite_record {
231 $conn->log("irspy", "rewriting XML record");
232 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
234 # Since IRSpy can run for a long time between writes back to the
235 # database, it's quite possible for the server to have closed the
236 # connection as idle. So re-establish it if necessary.
237 $this->{conn}->connect($conn->option("host"));
239 _really_rewrite_record($this->{conn}, $rec);
240 $conn->log("irspy", "rewrote XML record");
244 sub _really_rewrite_record {
245 my($conn, $rec, $oldid) = @_;
247 my $p = $conn->package();
248 $p->option(action => "specialUpdate");
249 my $xml = $rec->toString();
250 $p->option(record => $xml);
254 # This is the expression in the ID-making stylesheet
255 # ../../zebra/zeerex2id.xsl
256 my $xc = irspy_xpath_context($rec);
257 my $id = $xc->find("concat(e:serverInfo/e:host, ':',
258 e:serverInfo/e:port, '/',
259 e:serverInfo/e:database)");
260 if (0 && $id ne $oldid) {
262 warn "IDs differ (old='$oldid' new='$id')";
263 my $p = $conn->package();
264 $p->option(action => "recordDelete");
265 $p->option(recordIdOpaque => $oldid);
270 $p = $conn->package();
277 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
282 # The approach: gather declarative information about test hierarchy,
283 # then go into a loop. In the loop, we ensure that each connection is
284 # running a test, and within that test a task, until its list of tests
285 # is exhausted. No individual test ever calls wait(): tests just queue
286 # up tasks and return immediately. When the tasks are run (one at a
287 # time on each connection) they generate events, and it is these that
288 # are harvested by ZOOM::event(). Since each connection knows what
289 # task it is running, it can invoke the appropriate callbacks.
290 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
291 # loop how to continue.
294 # While a connection is running a task, its current_task()
295 # points at the task structure. When it finishes its task,
296 # next_task() is pointed at the next task to execute (if there
297 # is one), and its current_task() is set to zero. When the next
298 # task is executed, the connection's next_task() is set to zero
299 # and its current_task() pointed to the task structure.
300 # current_task() and next_task() are both zero only when there
301 # are no more queued tasks, which is when a new test is
304 # Each connection's current test is stored in its
305 # "current_test_address" option. The next test to execute is
306 # calculated by walking the declarative tree of tests. This
307 # option begins empty; the "next test" after this is of course
314 $tname = "Main" if !defined $tname;
315 $this->{tree} = $this->_gather_tests($tname)
316 or die "No tests defined for '$tname'";
317 $this->{tree}->resolve();
318 #$this->{tree}->print(0);
321 my @conn = @{ $this->{connections} };
324 ROUND_AND_ROUND_WE_GO:
326 my @copy_conn = @conn; # avoid alias problems after splice()
327 my $nconn = scalar(@copy_conn);
328 foreach my $i0 (0 .. $#copy_conn) {
329 my $conn = $copy_conn[$i0];
330 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
331 next if !defined $conn;
332 if (!$conn->current_task()) {
333 if (!$conn->next_task()) {
334 # Out of tasks: we need a new test
336 my $address = $conn->option("current_test_address");
338 if (!defined $address) {
341 $conn->log("irspy_test",
342 "checking for next test after '$address'");
343 $nextaddr = $this->_next_test($address);
345 if (!defined $nextaddr) {
346 $conn->log("irspy", "has no more tests: removing");
347 $this->_rewrite_record($conn);
348 $conn->option(rewrote_record => 1);
349 if (@{ $this->{queue} } == 0) {
350 # Do not destroy: we need this for later sanity checks
351 splice @conn, $i0, 1;
355 ZOOM::IRSpy::Connection($this,
356 shift @{ $this->{queue} }, async => 1);
357 $conn[$i0]->option(current_test_address => "");
358 $conn[$i0]->log("irspy", "entering active pool - ",
359 scalar(@{ $this->{queue} }),
360 " targets remain in queue");
365 my $node = $this->{tree}->select($nextaddr)
366 or die "invalid nextaddr '$nextaddr'";
367 $conn->option(current_test_address => $nextaddr);
368 my $tname = $node->name();
369 $conn->log("irspy_test",
370 "starting test '$nextaddr' = $tname");
371 my $tasks = $conn->tasks();
372 my $oldcount = @$tasks;
373 "ZOOM::IRSpy::Test::$tname"->start($conn);
374 $tasks = $conn->tasks();
375 if (@$tasks > $oldcount) {
376 # Prepare to start the first of the newly added tasks
377 $conn->next_task($tasks->[$oldcount]);
379 $conn->log("irspy_task",
380 "no tasks added by new test $tname");
385 my $task = $conn->next_task();
386 die "no next task queued for $conn" if !defined $task;
387 $conn->log("irspy_task", "preparing task $task");
389 $conn->current_task($task);
395 my $i0 = ZOOM::event(\@conn);
396 $this->log("irspy_event",
397 "ZOOM_event(", scalar(@conn), " connections) = $i0");
400 0 => "no events remain",
401 -1 => "ZOOM::event() argument not a reference",
402 -2 => "ZOOM::event() reference not an array",
403 -3 => "no connections remain",
404 -4 => "too many connections for ZOOM::event()",
406 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
407 $this->log("irspy", $message);
411 my $conn = $conn[$i0-1];
412 my $ev = $conn->last_event();
413 my $evstr = ZOOM::event_str($ev);
414 $conn->log("irspy_event", "event $ev ($evstr)");
415 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
417 my $task = $conn->current_task();
418 die "$conn has no current task for event $ev ($evstr)" if !$task;
421 eval { $conn->check() };
422 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
423 my $sub = $task->{cb}->{exception};
424 die $@ if !defined $sub;
425 $res = &$sub($conn, $task, $task->udata(), $@);
427 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
429 my $sub = $task->{cb}->{$ev};
431 $conn->log("irspy_unhandled", "event $ev ($evstr)");
435 $res = &$sub($conn, $task, $task->udata(), $ev);
438 if ($res == ZOOM::IRSpy::Status::OK) {
439 # Nothing to do -- life continues
441 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
442 my $task = $conn->current_task();
443 die "no task for TASK_DONE on $conn" if !$task;
444 die "next task already defined for $conn" if $conn->next_task();
445 $conn->log("irspy_task", "completed task $task");
446 $conn->next_task($task->{next});
447 $conn->current_task(0);
449 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
450 $res == ZOOM::IRSpy::Status::TEST_BAD) {
451 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
452 $conn->log("irspy_task", "test ended during task $task ($x)");
453 $conn->log("irspy_test", "test completed ($x)");
454 $conn->current_task(0);
456 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
457 my $address = $conn->option('current_test_address');
458 $conn->log("irspy", "top-level test failed!")
460 my $node = $this->{tree}->select($address);
462 while (defined $node->next() &&
463 length($node->next()->address()) >= length($address)) {
464 $conn->log("irspy_debug", "skipping from '",
465 $node->address(), "' to '",
466 $node->next()->address(), "'");
467 $node = $node->next();
471 $conn->option(current_test_address => $node->address());
472 $conn->log("irspy_test", "skipped $skipcount tests");
473 $nskipped += $skipcount;
476 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
477 $conn->log("irspy_test", "test skipped during task $task");
478 $conn->current_task(0);
483 die "unknown callback return-value '$res'";
487 $this->log("irspy", "exiting main loop");
489 # Sanity checks: none of the following should ever happen
491 $this->log("irspy", "performing end-of-run sanity-checks");
492 foreach my $conn (@conn) {
493 my $test = $conn->option("current_test_address");
494 my $next = $this->_next_test($test);
497 "$conn (in test '$test') has queued test '$next'");
500 if (my $task = $conn->current_task()) {
501 $this->log("irspy", "$conn still has an active task $task");
504 if (my $task = $conn->next_task()) {
505 $this->log("irspy", "$conn still has a queued task $task");
508 if (!$conn->is_idle()) {
510 "$conn still has ZOOM-C level tasks queued: see below");
513 my $ev = $conn->peek_event();
514 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
515 my $evstr = ZOOM::event_str($ev);
516 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
519 if (!$conn->option("rewrote_record")) {
520 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
525 # This really shouldn't be necessary, and in practice it rarely
526 # helps, but it's belt and braces. (For now, we don't do this
527 # hence the zero in the $nruns check).
530 $this->log("irspy", "back into main loop, ${nruns}th time");
531 goto ROUND_AND_ROUND_WE_GO;
533 $this->log("irspy", "bailing after $nruns main-loop runs");
537 # This shouldn't happen emit anything either:
538 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
539 my $conn = $conn[$i1-1];
540 my $ev = $conn->last_event();
541 my $evstr = ZOOM::event_str($ev);
543 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
544 if $ev != ZOOM::Event::ZEND;
551 # Exactly equivalent to ZOOM::event() except that it is tolerant to
552 # undefined values in the array being passed in.
554 sub __UNUSED_tolerant_ZOOM_event {
558 foreach my $i (0 .. @$connref-1) {
559 my $conn = $connref->[$i];
566 my $res = ZOOM::event(\@conn);
567 return $res if $res <= 0;
568 my $res2 = $map[$res-1] + 1;
569 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
576 my($tname, @ancestors) = @_;
578 die("$0: test-hierarchy loop detected: " .
579 join(" -> ", @ancestors, $tname))
580 if grep { $_ eq $tname } @ancestors;
582 my $slashSeperatedTname = $tname;
583 $slashSeperatedTname =~ s/::/\//g;
584 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
588 $this->log("irspy", "successfully required '$fullName'");
590 $this->log("irspy", "couldn't require '$fullName': $@");
591 $this->log("warn", "can't load test '$tname': skipping",
592 $@ =~ /^Can.t locate/ ? () : " ($@)");
596 $this->log("irspy", "adding test '$tname'");
598 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
599 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
600 push @subnodes, $subtest if defined $subtest;
603 return new ZOOM::IRSpy::Node($tname, @subnodes);
607 # These next three should arguably be Node methods
610 my($address, $omit_child) = @_;
614 my $maybe = $address eq "" ? "0" : "$address:0";
615 return $maybe if $this->{tree}->select($maybe);
618 # The top-level node has no successor or parent
619 return undef if $address eq "";
621 # Try next sibling child
622 my @components = split /:/, $address;
623 my $last = pop @components;
624 my $maybe = join(":", @components, $last+1);
625 return $maybe if $this->{tree}->select($maybe);
627 # This node is exhausted: try the parent's successor
628 return $this->_next_test(join(":", @components), 1)
632 sub _last_sibling_test {
637 if !defined $this->_next_sibling_test($address);
641 my $maybe = $this->_next_sibling_test($address);
642 last if !defined $maybe;
645 $this->log("irspy", "skipping $nskipped tests to '$address'");
648 return ($address, $nskipped);
652 sub _next_sibling_test {
656 my @components = split /:/, $address;
657 my $last = pop @components;
658 my $maybe = join(":", @components, $last+1);
659 return $maybe if $this->{tree}->select($maybe);
669 ZOOM::IRSpy::Maintenance.
671 The ZOOM-Perl module,
672 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
675 http://indexdata.com/zebra/
679 Mike Taylor, E<lt>mike@indexdata.comE<gt>
681 =head1 COPYRIGHT AND LICENSE
683 Copyright (C) 2006 by Index Data ApS.
685 This library is free software; you can redistribute it and/or modify
686 it under the same terms as Perl itself, either Perl version 5.8.7 or,
687 at your option, any later version of Perl 5 you may have available.