1 # $Id: IRSpy.pm,v 1.73 2007-03-01 14:00:50 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::Record;
19 use ZOOM::IRSpy::Stats;
20 use ZOOM::IRSpy::Utils qw(cql_target);
23 our $VERSION = '0.02';
24 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
27 # Enumeration for callback functions to return
28 package ZOOM::IRSpy::Status;
29 sub OK { 29 } # No problems, task is still progressing
30 sub TASK_DONE { 18 } # Task is complete, next task should begin
31 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
32 sub TEST_BAD { 31 } # Whole test is complete, and failed
33 sub TEST_SKIPPED { 12 } # Test couldn't be run
39 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
44 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
45 $spy->targets(@targets);
47 $res = $spy->check("Main");
51 This module exists to implement the IRspy program, which discovers,
52 analyses and monitors IR servers implementing the Z39.50 and SRU/W
53 protocols. It is a successor to the ZSpy program.
58 ZOOM::Log::mask_str("irspy");
59 ZOOM::Log::mask_str("irspy_debug");
60 ZOOM::Log::mask_str("irspy_event");
61 ZOOM::Log::mask_str("irspy_unhandled");
62 ZOOM::Log::mask_str("irspy_test");
63 ZOOM::Log::mask_str("irspy_task");
68 my($dbname, $user, $password) = @_;
71 push @options, (user => $user, password => $password)
74 my $conn = new ZOOM::Connection($dbname, 0, @options)
75 or die "$0: can't connection to IRSpy database 'dbname'";
77 my $xslt = new XML::LibXSLT;
79 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
80 \&ZOOM::IRSpy::Utils::xslt_strcmp);
82 my $libxml = new XML::LibXML;
83 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
84 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
88 query => "cql.allRecords=1", # unless overridden
89 targets => undef, # filled in later
90 connections => undef, # filled in later
92 irspy_to_zeerex_style => $irspy_to_zeerex_style,
93 tests => [], # stack of tests currently being executed
95 $this->log("irspy", "starting up with database '$dbname'");
111 $this->{query} = $query;
115 # Explicitly nominate a set of targets to check, overriding the
116 # default which is to re-check everything in the database. Each
117 # target already in the database results in the existing record being
118 # updated; each new target causes a new record to be added.
124 $this->log("irspy", "setting explicit list of targets ",
125 join(", ", map { "'$_'" } @targets));
127 foreach my $target (@targets) {
128 my($host, $port, $db, $newtarget) = _parse_target_string($target);
129 if ($newtarget ne $target) {
130 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
131 $target = $newtarget; # This is written through the ref
133 push @qlist, cql_target($host, $port, $db);
136 $this->{targets} = \@targets;
137 $this->{query} = join(" or ", @qlist);
141 # Also used by ZOOM::IRSpy::Record
142 sub _parse_target_string {
145 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
146 if (!defined $host) {
148 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
149 $target = "$host:$port/$db";
151 die "$0: invalid target string '$target'"
154 return ($host, $port, $db, $target);
158 # Records must be fetched for all records satisfying $this->{query} If
159 # $this->{targets} is already set (i.e. a specific list of targets to
160 # check was specified by a call to targets()), then new, empty records
161 # must be made for any targets that are not already in the database.
167 if ($this->{targets}) {
168 # Prepopulate the target map with nulls so that after we fill
169 # in what we can from the database query, we know which target
170 # IDs we need new records for.
171 foreach my $target (@{ $this->{targets} }) {
172 $target2record{lc($target)} = undef;
175 delete $this->{targets}; # Information now in keys of %target2record
177 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
178 $this->log("irspy", "'", $this->{query}, "' found ",
179 $rs->size(), " target records");
180 delete $this->{query}; # Information now in $rs
182 foreach my $i (1 .. $rs->size()) {
183 my $target = _render_record($rs, $i-1, "id");
184 my $zeerex = _render_record($rs, $i-1, "zeerex");
185 $target2record{lc($target)} =
186 new ZOOM::IRSpy::Record($this, $target, $zeerex);
189 # Make records for targets not previously in the database
190 foreach my $target (keys %target2record) {
191 if (!defined $target2record{$target}) {
192 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
193 $this->log("irspy_debug", "made new record for '$target'");
195 $this->log("irspy_debug", "using existing record for '$target'");
200 my @targets = sort keys %target2record;
201 foreach my $target (@targets) {
202 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
203 $conn->option(host => $target);
204 my $record = delete $target2record{lc($target)};
205 die "record undefined for '$target'" if !defined $record;
206 $conn->record($record);
207 push @connections, $conn;
209 die("remaining target2record = { " .
210 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
211 sort keys %target2record) . " }")
214 $this->{connections} = \@connections;
219 my($rs, $which, $elementSetName) = @_;
221 # There is a slight race condition here on the element-set name,
222 # but it shouldn't be a problem as this is (currently) only called
223 # from parts of the program that run single-threaded.
224 my $old = $rs->option(elementSetName => $elementSetName);
225 my $rec = $rs->record($which);
226 $rs->option(elementSetName => $old);
228 return $rec->render();
232 sub _irspy_to_zeerex {
234 my($conn, $save_xml) = @_;
235 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
238 unlink('/tmp/irspy_orig.xml');
239 open FH, '>/tmp/irspy_orig.xml'
240 or die "can't write irspy_orig.xml: $!";
241 print FH $irspy_doc->toString();
245 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
247 unlink('/tmp/irspy_transformed.xml');
248 open FH, '>/tmp/irspy_transformed.xml'
249 or die "can't write irspy_transformed.xml: $!";
250 print FH $result->toString();
254 return $result->documentElement();
258 sub _rewrite_record {
262 $conn->log("irspy", "rewriting XML record");
263 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
264 _really_rewrite_record($this->{conn}, $rec);
268 sub _really_rewrite_record {
269 my($conn, $rec) = @_;
271 my $p = $conn->package();
272 $p->option(action => "specialUpdate");
273 my $xml = $rec->toString();
274 $p->option(record => $xml);
278 $p = $conn->package();
285 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
290 # The approach: gather declarative information about test hierarchy,
291 # then go into a loop. In the loop, we ensure that each connection is
292 # running a test, and within that test a task, until its list of tests
293 # is exhausted. No individual test ever calls wait(): tests just queue
294 # up tasks and return immediately. When the tasks are run (one at a
295 # time on each connection) they generate events, and it is these that
296 # are harvested by ZOOM::event(). Since each connection knows what
297 # task it is running, it can invoke the appropriate callbacks.
298 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
299 # loop how to continue.
302 # While a connection is running a task, its current_task()
303 # points at the task structure. When it finishes its task,
304 # next_task() is pointed at the next task to execute (if there
305 # is one), and its current_task() is set to zero. When the next
306 # task is executed, the connection's next_task() is set to zero
307 # and its current_task() pointed to the task structure.
308 # current_task() and next_task() are both zero only when there
309 # are no more queued tasks, which is when a new test is
312 # Each connection's current test is stored in its
313 # "current_test_address" option. The next test to execute is
314 # calculated by walking the declarative tree of tests. This
315 # option begins empty; the "next test" after this is of course
322 $tname = "Main" if !defined $tname;
323 $this->{tree} = $this->_gather_tests($tname)
324 or die "No tests defined for '$tname'";
325 $this->{tree}->resolve();
326 #$this->{tree}->print(0);
329 my @conn = @{ $this->{connections} };
332 ROUND_AND_ROUND_WE_GO:
334 my @copy_conn = @conn; # avoid alias problems after splice()
335 my $nconn = scalar(@copy_conn);
336 foreach my $i0 (0 .. $#copy_conn) {
337 my $conn = $copy_conn[$i0];
338 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
339 if (!$conn->current_task()) {
340 if (!$conn->next_task()) {
341 # Out of tasks: we need a new test
343 my $address = $conn->option("current_test_address");
345 if (!defined $address) {
348 $this->log("irspy_test",
349 "checking for next test after '$address'");
350 $nextaddr = $this->_next_test($address);
352 if (!defined $nextaddr) {
353 $conn->log("irspy", "has no more tests: removing");
354 ### Does this go wrong if two connections are exhausted?
355 splice @conn, $i0, 1;
356 $this->_rewrite_record($conn);
357 $conn->option(rewrote_record => 1);
361 my $node = $this->{tree}->select($nextaddr)
362 or die "invalid nextaddr '$nextaddr'";
363 $conn->option(current_test_address => $nextaddr);
364 my $tname = $node->name();
365 $conn->log("irspy_test",
366 "starting test '$nextaddr' = $tname");
367 my $tasks = $conn->tasks();
368 my $oldcount = @$tasks;
369 "ZOOM::IRSpy::Test::$tname"->start($conn);
370 $tasks = $conn->tasks();
371 if (@$tasks > $oldcount) {
372 # Prepare to start the first of the newly added tasks
373 $conn->next_task($tasks->[$oldcount]);
375 $conn->log("irspy_task",
376 "no tasks added by new test $tname");
381 my $task = $conn->next_task();
382 die "no next task queued for $conn" if !defined $task;
383 $conn->log("irspy_task", "preparing task $task");
385 $conn->current_task($task);
391 my $i0 = ZOOM::event(\@conn);
392 $this->log("irspy_event",
393 "ZOOM_event(", scalar(@conn), " connections) = $i0");
396 0 => "no events remain",
397 -1 => "ZOOM::event() argument not a reference",
398 -2 => "ZOOM::event() reference not an array",
399 -3 => "no connections remain",
400 -4 => "too many connections for ZOOM::event()",
402 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
403 $this->log("irspy", $message);
407 my $conn = $conn[$i0-1];
408 my $ev = $conn->last_event();
409 my $evstr = ZOOM::event_str($ev);
410 $conn->log("irspy_event", "event $ev ($evstr)");
411 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
413 my $task = $conn->current_task();
414 die "$conn has no current task for event $ev ($evstr)" if !$task;
417 eval { $conn->check() };
418 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
419 my $sub = $task->{cb}->{exception};
420 die $@ if !defined $sub;
421 $res = &$sub($conn, $task, $task->udata(), $@);
423 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
425 my $sub = $task->{cb}->{$ev};
427 $conn->log("irspy_unhandled", "event $ev ($evstr)");
431 $res = &$sub($conn, $task, $task->udata(), $ev);
434 if ($res == ZOOM::IRSpy::Status::OK) {
435 # Nothing to do -- life continues
437 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
438 my $task = $conn->current_task();
439 die "no task for TASK_DONE on $conn" if !$task;
440 die "next task already defined for $conn" if $conn->next_task();
441 $conn->log("irspy_task", "completed task $task");
442 $conn->next_task($task->{next});
443 $conn->current_task(0);
445 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
446 $res == ZOOM::IRSpy::Status::TEST_BAD) {
447 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
448 $conn->log("irspy_task", "test ended during task $task ($x)");
449 $conn->log("irspy_test", "test completed ($x)");
450 $conn->current_task(0);
452 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
453 my $address = $conn->option('current_test_address');
454 $conn->log("irspy", "top-level test failed!")
456 my $node = $this->{tree}->select($address);
458 while (defined $node->next() &&
459 length($node->next()->address()) >= length($address)) {
460 $conn->log("irspy_debug", "skipping from '",
461 $node->address(), "' to '",
462 $node->next()->address(), "'");
463 $node = $node->next();
467 $conn->option(current_test_address => $node->address());
468 $conn->log("irspy_test", "skipped $skipcount tests");
469 $nskipped += $skipcount;
472 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
473 $conn->log("irspy_test", "test skipped during task $task");
474 $conn->current_task(0);
479 die "unknown callback return-value '$res'";
483 $this->log("irspy", "exiting main loop");
484 # Sanity checks: none of the following should ever happen
486 @conn = @{ $this->{connections} };
487 foreach my $conn (@conn) {
488 my $test = $conn->option("current_test_address");
489 my $next = $this->_next_test($test);
492 "$conn (in test '$test') has queued test '$next'");
495 if (my $task = $conn->current_task()) {
496 $this->log("irspy", "$conn still has an active task $task");
499 if (my $task = $conn->next_task()) {
500 $this->log("irspy", "$conn still has a queued task $task");
503 if (!$conn->is_idle()) {
505 "$conn still has ZOOM-C level tasks queued: see below");
508 my $ev = $conn->peek_event();
509 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
510 my $evstr = ZOOM::event_str($ev);
511 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
514 if (!$conn->option("rewrote_record")) {
515 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
520 # This really shouldn't be necessary, and in practice it rarely
521 # helps, but it's belt and braces. (For now, we don't do this
522 # hence the zero in the $nruns check).
525 $this->log("irspy", "back into main loop, ${nruns}th time");
526 goto ROUND_AND_ROUND_WE_GO;
528 $this->log("irspy", "bailing after $nruns main-loop runs");
532 # This shouldn't happen emit anything either:
533 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
534 my $conn = $conn[$i1-1];
535 my $ev = $conn->last_event();
536 my $evstr = ZOOM::event_str($ev);
538 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
539 if $ev != ZOOM::Event::ZEND;
548 my($tname, @ancestors) = @_;
550 die("$0: test-hierarchy loop detected: " .
551 join(" -> ", @ancestors, $tname))
552 if grep { $_ eq $tname } @ancestors;
554 my $slashSeperatedTname = $tname;
555 $slashSeperatedTname =~ s/::/\//g;
556 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
560 $this->log("irspy", "successfully required '$fullName'");
562 $this->log("irspy", "couldn't require '$fullName': $@");
563 $this->log("warn", "can't load test '$tname': skipping",
564 $@ =~ /^Can.t locate/ ? () : " ($@)");
568 $this->log("irspy", "adding test '$tname'");
570 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
571 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
572 push @subnodes, $subtest if defined $subtest;
575 return new ZOOM::IRSpy::Node($tname, @subnodes);
579 # These next three should arguably be Node methods
582 my($address, $omit_child) = @_;
586 my $maybe = $address eq "" ? "0" : "$address:0";
587 return $maybe if $this->{tree}->select($maybe);
590 # The top-level node has no successor or parent
591 return undef if $address eq "";
593 # Try next sibling child
594 my @components = split /:/, $address;
595 my $last = pop @components;
596 my $maybe = join(":", @components, $last+1);
597 return $maybe if $this->{tree}->select($maybe);
599 # This node is exhausted: try the parent's successor
600 return $this->_next_test(join(":", @components), 1)
604 sub _last_sibling_test {
609 if !defined $this->_next_sibling_test($address);
613 my $maybe = $this->_next_sibling_test($address);
614 last if !defined $maybe;
617 $this->log("irspy", "skipping $nskipped tests to '$address'");
620 return ($address, $nskipped);
624 sub _next_sibling_test {
628 my @components = split /:/, $address;
629 my $last = pop @components;
630 my $maybe = join(":", @components, $last+1);
631 return $maybe if $this->{tree}->select($maybe);
641 ZOOM::IRSpy::Maintenance.
643 The ZOOM-Perl module,
644 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
647 http://indexdata.com/zebra/
651 Mike Taylor, E<lt>mike@indexdata.comE<gt>
653 =head1 COPYRIGHT AND LICENSE
655 Copyright (C) 2006 by Index Data ApS.
657 This library is free software; you can redistribute it and/or modify
658 it under the same terms as Perl itself, either Perl version 5.8.7 or,
659 at your option, any later version of Perl 5 you may have available.