1 # $Id: IRSpy.pm,v 1.72 2007-02-28 17:36:00 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 allrecords => 1, # unless overridden by targets()
89 query => undef, # filled in later
90 targets => undef, # filled in later
91 connections => undef, # filled in later
93 irspy_to_zeerex_style => $irspy_to_zeerex_style,
94 tests => [], # stack of tests currently being executed
96 $this->log("irspy", "starting up with database '$dbname'");
108 # Explicitly nominate a set of targets to check, overriding the
109 # default which is to re-check everything in the database. Each
110 # target already in the database results in the existing record being
111 # updated; each new target causes a new record to be added.
117 $this->log("irspy", "setting explicit list of targets ",
118 join(", ", map { "'$_'" } @targets));
119 $this->{allrecords} = 0;
121 foreach my $target (@targets) {
122 my($host, $port, $db, $newtarget) = _parse_target_string($target);
123 if ($newtarget ne $target) {
124 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
125 $target = $newtarget; # This is written through the ref
127 push @qlist, cql_target($host, $port, $db);
130 $this->{targets} = \@targets;
131 $this->{query} = join(" or ", @qlist);
139 $this->{allrecords} = 0;
140 $this->{query} = $query;
144 # Also used by ZOOM::IRSpy::Record
145 sub _parse_target_string {
148 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
149 if (!defined $host) {
151 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
152 $target = "$host:$port/$db";
154 die "$0: invalid target string '$target'"
157 return ($host, $port, $db, $target);
161 # There are two cases.
163 # 1. A specific set of targets is nominated on the command line.
164 # - Records must be fetched for those targets that are in the DB
165 # - New, empty records must be made for those that are not.
166 # - Updated records written to the DB may or may not be new.
168 # 2. All records in the database are to be checked.
169 # - Records must be fetched for all targets in the DB
170 # - Updated records written to the DB may not be new.
172 # That's all -- what could be simpler?
178 if ($this->{allrecords}) {
179 # We need to check on every target in the database, which
180 # means we need to do a "find all". According to the BIB-1
181 # semantics document at
182 # http://www.loc.gov/z3950/agency/bib1.html
184 # @attr 2=103 @attr 1=1035 x
185 # should find all records, but it seems that Zebra doesn't
186 # support this. Furthermore, when using the "alvis" filter
187 # (as we do for IRSpy) it doesn't support the use of any BIB-1
188 # access point -- not even 1035 "everywhere" -- so instead we
189 # hack together a search that we know will find all records.
190 $this->{query} = "port=?*";
191 } elsif ($this->{targets}) {
192 # Prepopulate the target map with nulls so that after we fill
193 # in what we can from the database query, we know which target
194 # IDs we need new records for.
195 foreach my $target (@{ $this->{targets} }) {
196 $target2record{lc($target)} = undef;
200 $this->log("irspy_debug", "query '", $this->{query}, "'");
201 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
202 $this->log("irspy", "'", $this->{query}, "' found ",
203 $rs->size(), " target records");
204 delete $this->{query}; # No longer needed at all
205 my $gatherTargets = !$this->{targets};
206 foreach my $i (1 .. $rs->size()) {
207 my $target = _render_record($rs, $i-1, "id");
208 my $zeerex = _render_record($rs, $i-1, "zeerex");
209 #print STDERR "making '$target' record with '$zeerex'\n";
210 $target2record{lc($target)} =
211 new ZOOM::IRSpy::Record($this, $target, $zeerex);
212 push @{ $this->{targets} }, $target
216 # Make records for targets not previously in the database
217 foreach my $target (keys %target2record) {
218 my $record = $target2record{$target};
219 if (!defined $record) {
220 $this->log("irspy_debug", "made new record for '$target'");
221 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
223 $this->log("irspy_debug", "using existing record for '$target'");
228 foreach my $target (@{ $this->{targets} }) {
229 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
230 $conn->option(host => $target);
231 my $record = delete $target2record{lc($target)};
232 $conn->record($record);
233 push @connections, $conn;
235 die("remaining target2record = { " .
236 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
237 sort keys %target2record) . " }")
240 $this->{connections} = \@connections;
241 delete $this->{targets}; # The information is now in {connections}
246 my($rs, $which, $elementSetName) = @_;
248 # There is a slight race condition here on the element-set name,
249 # but it shouldn't be a problem as this is (currently) only called
250 # from parts of the program that run single-threaded.
251 my $old = $rs->option(elementSetName => $elementSetName);
252 my $rec = $rs->record($which);
253 $rs->option(elementSetName => $old);
255 return $rec->render();
259 sub _irspy_to_zeerex {
261 my($conn, $save_xml) = @_;
262 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
265 unlink('/tmp/irspy_orig.xml');
266 open FH, '>/tmp/irspy_orig.xml'
267 or die "can't write irspy_orig.xml: $!";
268 print FH $irspy_doc->toString();
272 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
274 unlink('/tmp/irspy_transformed.xml');
275 open FH, '>/tmp/irspy_transformed.xml'
276 or die "can't write irspy_transformed.xml: $!";
277 print FH $result->toString();
281 return $result->documentElement();
285 sub _rewrite_record {
289 $conn->log("irspy", "rewriting XML record");
290 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
291 _really_rewrite_record($this->{conn}, $rec);
295 sub _really_rewrite_record {
296 my($conn, $rec) = @_;
298 my $p = $conn->package();
299 $p->option(action => "specialUpdate");
300 my $xml = $rec->toString();
301 $p->option(record => $xml);
305 $p = $conn->package();
312 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
317 # The approach: gather declarative information about test hierarchy,
318 # then go into a loop. In the loop, we ensure that each connection is
319 # running a test, and within that test a task, until its list of tests
320 # is exhausted. No individual test ever calls wait(): tests just queue
321 # up tasks and return immediately. When the tasks are run (one at a
322 # time on each connection) they generate events, and it is these that
323 # are harvested by ZOOM::event(). Since each connection knows what
324 # task it is running, it can invoke the appropriate callbacks.
325 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
326 # loop how to continue.
329 # While a connection is running a task, its current_task()
330 # points at the task structure. When it finishes its task,
331 # next_task() is pointed at the next task to execute (if there
332 # is one), and its current_task() is set to zero. When the next
333 # task is executed, the connection's next_task() is set to zero
334 # and its current_task() pointed to the task structure.
335 # current_task() and next_task() are both zero only when there
336 # are no more queued tasks, which is when a new test is
339 # Each connection's current test is stored in its
340 # "current_test_address" option. The next test to execute is
341 # calculated by walking the declarative tree of tests. This
342 # option begins empty; the "next test" after this is of course
349 $tname = "Main" if !defined $tname;
350 $this->{tree} = $this->_gather_tests($tname)
351 or die "No tests defined for '$tname'";
352 $this->{tree}->resolve();
353 #$this->{tree}->print(0);
356 my @conn = @{ $this->{connections} };
359 ROUND_AND_ROUND_WE_GO:
361 my @copy_conn = @conn; # avoid alias problems after splice()
362 my $nconn = scalar(@copy_conn);
363 foreach my $i0 (0 .. $#copy_conn) {
364 my $conn = $copy_conn[$i0];
365 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
366 if (!$conn->current_task()) {
367 if (!$conn->next_task()) {
368 # Out of tasks: we need a new test
370 my $address = $conn->option("current_test_address");
372 if (!defined $address) {
375 $this->log("irspy_test",
376 "checking for next test after '$address'");
377 $nextaddr = $this->_next_test($address);
379 if (!defined $nextaddr) {
380 $conn->log("irspy", "has no more tests: removing");
381 ### Does this go wrong if two connections are exhausted?
382 splice @conn, $i0, 1;
383 $this->_rewrite_record($conn);
384 $conn->option(rewrote_record => 1);
388 my $node = $this->{tree}->select($nextaddr)
389 or die "invalid nextaddr '$nextaddr'";
390 $conn->option(current_test_address => $nextaddr);
391 my $tname = $node->name();
392 $conn->log("irspy_test",
393 "starting test '$nextaddr' = $tname");
394 my $tasks = $conn->tasks();
395 my $oldcount = @$tasks;
396 "ZOOM::IRSpy::Test::$tname"->start($conn);
397 $tasks = $conn->tasks();
398 if (@$tasks > $oldcount) {
399 # Prepare to start the first of the newly added tasks
400 $conn->next_task($tasks->[$oldcount]);
402 $conn->log("irspy_task",
403 "no tasks added by new test $tname");
408 my $task = $conn->next_task();
409 die "no next task queued for $conn" if !defined $task;
410 $conn->log("irspy_task", "preparing task $task");
412 $conn->current_task($task);
418 my $i0 = ZOOM::event(\@conn);
419 $this->log("irspy_event",
420 "ZOOM_event(", scalar(@conn), " connections) = $i0");
423 0 => "no events remain",
424 -1 => "ZOOM::event() argument not a reference",
425 -2 => "ZOOM::event() reference not an array",
426 -3 => "no connections remain",
427 -4 => "too many connections for ZOOM::event()",
429 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
430 $this->log("irspy", $message);
434 my $conn = $conn[$i0-1];
435 my $ev = $conn->last_event();
436 my $evstr = ZOOM::event_str($ev);
437 $conn->log("irspy_event", "event $ev ($evstr)");
438 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
440 my $task = $conn->current_task();
441 die "$conn has no current task for event $ev ($evstr)" if !$task;
444 eval { $conn->check() };
445 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
446 my $sub = $task->{cb}->{exception};
447 die $@ if !defined $sub;
448 $res = &$sub($conn, $task, $task->udata(), $@);
450 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
452 my $sub = $task->{cb}->{$ev};
454 $conn->log("irspy_unhandled", "event $ev ($evstr)");
458 $res = &$sub($conn, $task, $task->udata(), $ev);
461 if ($res == ZOOM::IRSpy::Status::OK) {
462 # Nothing to do -- life continues
464 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
465 my $task = $conn->current_task();
466 die "no task for TASK_DONE on $conn" if !$task;
467 die "next task already defined for $conn" if $conn->next_task();
468 $conn->log("irspy_task", "completed task $task");
469 $conn->next_task($task->{next});
470 $conn->current_task(0);
472 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
473 $res == ZOOM::IRSpy::Status::TEST_BAD) {
474 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
475 $conn->log("irspy_task", "test ended during task $task ($x)");
476 $conn->log("irspy_test", "test completed ($x)");
477 $conn->current_task(0);
479 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
480 my $address = $conn->option('current_test_address');
481 $conn->log("irspy", "top-level test failed!")
483 my $node = $this->{tree}->select($address);
485 while (defined $node->next() &&
486 length($node->next()->address()) >= length($address)) {
487 $conn->log("irspy_debug", "skipping from '",
488 $node->address(), "' to '",
489 $node->next()->address(), "'");
490 $node = $node->next();
494 $conn->option(current_test_address => $node->address());
495 $conn->log("irspy_test", "skipped $skipcount tests");
496 $nskipped += $skipcount;
499 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
500 $conn->log("irspy_test", "test skipped during task $task");
501 $conn->current_task(0);
506 die "unknown callback return-value '$res'";
510 $this->log("irspy", "exiting main loop");
511 # Sanity checks: none of the following should ever happen
513 @conn = @{ $this->{connections} };
514 foreach my $conn (@conn) {
515 my $test = $conn->option("current_test_address");
516 my $next = $this->_next_test($test);
519 "$conn (in test '$test') has queued test '$next'");
522 if (my $task = $conn->current_task()) {
523 $this->log("irspy", "$conn still has an active task $task");
526 if (my $task = $conn->next_task()) {
527 $this->log("irspy", "$conn still has a queued task $task");
530 if (!$conn->is_idle()) {
532 "$conn still has ZOOM-C level tasks queued: see below");
535 my $ev = $conn->peek_event();
536 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
537 my $evstr = ZOOM::event_str($ev);
538 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
541 if (!$conn->option("rewrote_record")) {
542 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
547 # This really shouldn't be necessary, and in practice it rarely
548 # helps, but it's belt and braces. (For now, we don't do this
549 # hence the zero in the $nruns check).
552 $this->log("irspy", "back into main loop, ${nruns}th time");
553 goto ROUND_AND_ROUND_WE_GO;
555 $this->log("irspy", "bailing after $nruns main-loop runs");
559 # This shouldn't happen emit anything either:
560 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
561 my $conn = $conn[$i1-1];
562 my $ev = $conn->last_event();
563 my $evstr = ZOOM::event_str($ev);
565 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
566 if $ev != ZOOM::Event::ZEND;
575 my($tname, @ancestors) = @_;
577 die("$0: test-hierarchy loop detected: " .
578 join(" -> ", @ancestors, $tname))
579 if grep { $_ eq $tname } @ancestors;
581 my $slashSeperatedTname = $tname;
582 $slashSeperatedTname =~ s/::/\//g;
583 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
587 $this->log("irspy", "successfully required '$fullName'");
589 $this->log("irspy", "couldn't require '$fullName': $@");
590 $this->log("warn", "can't load test '$tname': skipping",
591 $@ =~ /^Can.t locate/ ? () : " ($@)");
595 $this->log("irspy", "adding test '$tname'");
597 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
598 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
599 push @subnodes, $subtest if defined $subtest;
602 return new ZOOM::IRSpy::Node($tname, @subnodes);
606 # These next three should arguably be Node methods
609 my($address, $omit_child) = @_;
613 my $maybe = $address eq "" ? "0" : "$address:0";
614 return $maybe if $this->{tree}->select($maybe);
617 # The top-level node has no successor or parent
618 return undef if $address eq "";
620 # Try next sibling child
621 my @components = split /:/, $address;
622 my $last = pop @components;
623 my $maybe = join(":", @components, $last+1);
624 return $maybe if $this->{tree}->select($maybe);
626 # This node is exhausted: try the parent's successor
627 return $this->_next_test(join(":", @components), 1)
631 sub _last_sibling_test {
636 if !defined $this->_next_sibling_test($address);
640 my $maybe = $this->_next_sibling_test($address);
641 last if !defined $maybe;
644 $this->log("irspy", "skipping $nskipped tests to '$address'");
647 return ($address, $nskipped);
651 sub _next_sibling_test {
655 my @components = split /:/, $address;
656 my $last = pop @components;
657 my $maybe = join(":", @components, $last+1);
658 return $maybe if $this->{tree}->select($maybe);
668 ZOOM::IRSpy::Maintenance.
670 The ZOOM-Perl module,
671 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
674 http://indexdata.com/zebra/
678 Mike Taylor, E<lt>mike@indexdata.comE<gt>
680 =head1 COPYRIGHT AND LICENSE
682 Copyright (C) 2006 by Index Data ApS.
684 This library is free software; you can redistribute it and/or modify
685 it under the same terms as Perl itself, either Perl version 5.8.7 or,
686 at your option, any later version of Perl 5 you may have available.