1 # $Id: IRSpy.pm,v 1.70 2007-02-26 22:20:08 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 print FH $irspy_doc->toString();
271 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
273 unlink('/tmp/irspy_transformed.xml');
274 open FH, '>/tmp/irspy_transformed.xml';
275 print FH $result->toString();
279 return $result->documentElement();
283 sub _rewrite_record {
287 $conn->log("irspy", "rewriting XML record");
288 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
289 _really_rewrite_record($this->{conn}, $rec);
293 sub _really_rewrite_record {
294 my($conn, $rec) = @_;
296 my $p = $conn->package();
297 $p->option(action => "specialUpdate");
298 my $xml = $rec->toString();
299 $p->option(record => $xml);
303 $p = $conn->package();
310 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
315 # The approach: gather declarative information about test hierarchy,
316 # then go into a loop. In the loop, we ensure that each connection is
317 # running a test, and within that test a task, until its list of tests
318 # is exhausted. No individual test ever calls wait(): tests just queue
319 # up tasks and return immediately. When the tasks are run (one at a
320 # time on each connection) they generate events, and it is these that
321 # are harvested by ZOOM::event(). Since each connection knows what
322 # task it is running, it can invoke the appropriate callbacks.
323 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
324 # loop how to continue.
327 # While a connection is running a task, its current_task()
328 # points at the task structure. When it finishes its task,
329 # next_task() is pointed at the next task to execute (if there
330 # is one), and its current_task() is set to zero. When the next
331 # task is executed, the connection's next_task() is set to zero
332 # and its current_task() pointed to the task structure.
333 # current_task() and next_task() are both zero only when there
334 # are no more queued tasks, which is when a new test is
337 # Each connection's current test is stored in its
338 # "current_test_address" option. The next test to execute is
339 # calculated by walking the declarative tree of tests. This
340 # option begins empty; the "next test" after this is of course
347 $tname = "Main" if !defined $tname;
348 $this->{tree} = $this->_gather_tests($tname)
349 or die "No tests defined for '$tname'";
350 #$this->{tree}->print(0);
353 my @conn = @{ $this->{connections} };
356 ROUND_AND_ROUND_WE_GO:
358 my @copy_conn = @conn; # avoid alias problems after splice()
359 my $nconn = scalar(@copy_conn);
360 foreach my $i0 (0 .. $#copy_conn) {
361 my $conn = $copy_conn[$i0];
362 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
363 if (!$conn->current_task()) {
364 if (!$conn->next_task()) {
365 # Out of tasks: we need a new test
367 my $address = $conn->option("current_test_address");
369 if (!defined $address) {
372 $this->log("irspy_test",
373 "checking for next test after '$address'");
374 $nextaddr = $this->_next_test($address);
376 if (!defined $nextaddr) {
377 $conn->log("irspy", "has no more tests: removing");
378 ### Does this go wrong if two connections are exhausted?
379 splice @conn, $i0, 1;
380 $this->_rewrite_record($conn);
381 $conn->option(rewrote_record => 1);
385 my $node = $this->{tree}->select($nextaddr)
386 or die "invalid nextaddr '$nextaddr'";
387 $conn->option(current_test_address => $nextaddr);
388 my $tname = $node->name();
389 $conn->log("irspy_test",
390 "starting test '$nextaddr' = $tname");
391 my $tasks = $conn->tasks();
392 my $oldcount = @$tasks;
393 "ZOOM::IRSpy::Test::$tname"->start($conn);
394 $tasks = $conn->tasks();
395 if (@$tasks > $oldcount) {
396 # Prepare to start the first of the newly added tasks
397 $conn->next_task($tasks->[$oldcount]);
399 $conn->log("irspy_task",
400 "no tasks added by new test $tname");
405 my $task = $conn->next_task();
406 die "no next task queued for $conn" if !defined $task;
407 $conn->log("irspy_task", "preparing task $task");
409 $conn->current_task($task);
415 my $i0 = ZOOM::event(\@conn);
416 $this->log("irspy_event",
417 "ZOOM_event(", scalar(@conn), " connections) = $i0");
420 0 => "no events remain",
421 -1 => "ZOOM::event() argument not a reference",
422 -2 => "ZOOM::event() reference not an array",
423 -3 => "no connections remain",
424 -4 => "too many connections for ZOOM::event()",
426 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
427 $this->log("irspy", $message);
431 my $conn = $conn[$i0-1];
432 my $ev = $conn->last_event();
433 my $evstr = ZOOM::event_str($ev);
434 $conn->log("irspy_event", "event $ev ($evstr)");
435 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
437 my $task = $conn->current_task();
438 die "$conn has no current task for event $ev ($evstr)" if !$task;
441 eval { $conn->check() };
442 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
443 my $sub = $task->{cb}->{exception};
444 die $@ if !defined $sub;
445 $res = &$sub($conn, $task, $task->udata(), $@);
447 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
449 my $sub = $task->{cb}->{$ev};
451 $conn->log("irspy_unhandled", "event $ev ($evstr)");
455 $res = &$sub($conn, $task, $task->udata(), $ev);
458 if ($res == ZOOM::IRSpy::Status::OK) {
459 # Nothing to do -- life continues
461 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
462 my $task = $conn->current_task();
463 die "no task for TASK_DONE on $conn" if !$task;
464 die "next task already defined for $conn" if $conn->next_task();
465 $conn->log("irspy_task", "completed task $task");
466 $conn->next_task($task->{next});
467 $conn->current_task(0);
469 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
470 $res == ZOOM::IRSpy::Status::TEST_BAD) {
471 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
472 $conn->log("irspy_task", "test ended during task $task ($x)");
473 $conn->log("irspy_test", "test completed ($x)");
474 $conn->current_task(0);
476 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
477 my $address = $conn->option('current_test_address');
478 ($address, my $n) = $this->_last_sibling_test($address);
479 if (defined $address) {
480 $conn->log("irspy_test", "skipped $n tests");
481 $conn->option(current_test_address => $address);
486 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
487 $conn->log("irspy_test", "test skipped during task $task");
488 $conn->current_task(0);
493 die "unknown callback return-value '$res'";
497 $this->log("irspy", "exiting main loop");
498 # Sanity checks: none of the following should ever happen
500 @conn = @{ $this->{connections} };
501 foreach my $conn (@conn) {
502 my $test = $conn->option("current_test_address");
503 my $next = $this->_next_test($test);
506 "$conn (in test '$test') has queued test '$next'");
509 if (my $task = $conn->current_task()) {
510 $this->log("irspy", "$conn still has an active task $task");
513 if (my $task = $conn->next_task()) {
514 $this->log("irspy", "$conn still has a queued task $task");
517 if (!$conn->is_idle()) {
519 "$conn still has ZOOM-C level tasks queued: see below");
522 my $ev = $conn->peek_event();
523 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
524 my $evstr = ZOOM::event_str($ev);
525 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
528 if (!$conn->option("rewrote_record")) {
529 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
534 # This really shouldn't be necessary, and in practice it rarely
535 # helps, but it's belt and braces. (For now, we don't do this
536 # hence the zero in the $nruns check).
539 $this->log("irspy", "back into main loop, ${nruns}th time");
540 goto ROUND_AND_ROUND_WE_GO;
542 $this->log("irspy", "bailing after $nruns main-loop runs");
546 # This shouldn't happen emit anything either:
547 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
548 my $conn = $conn[$i1-1];
549 my $ev = $conn->last_event();
550 my $evstr = ZOOM::event_str($ev);
552 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
553 if $ev != ZOOM::Event::ZEND;
562 my($tname, @ancestors) = @_;
564 die("$0: test-hierarchy loop detected: " .
565 join(" -> ", @ancestors, $tname))
566 if grep { $_ eq $tname } @ancestors;
568 my $slashSeperatedTname = $tname;
569 $slashSeperatedTname =~ s/::/\//g;
570 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
574 $this->log("irspy", "successfully required '$fullName'");
576 $this->log("irspy", "couldn't require '$fullName': $@");
577 $this->log("warn", "can't load test '$tname': skipping",
578 $@ =~ /^Can.t locate/ ? () : " ($@)");
582 $this->log("irspy", "adding test '$tname'");
584 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
585 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
586 push @subnodes, $subtest if defined $subtest;
589 return new ZOOM::IRSpy::Node($tname, @subnodes);
593 # These next three should arguably be Node methods
596 my($address, $omit_child) = @_;
600 my $maybe = $address eq "" ? "0" : "$address:0";
601 return $maybe if $this->{tree}->select($maybe);
604 # The top-level node has no successor or parent
605 return undef if $address eq "";
607 # Try next sibling child
608 my @components = split /:/, $address;
609 my $last = pop @components;
610 my $maybe = join(":", @components, $last+1);
611 return $maybe if $this->{tree}->select($maybe);
613 # This node is exhausted: try the parent's successor
614 return $this->_next_test(join(":", @components), 1)
618 sub _last_sibling_test {
623 if !defined $this->_next_sibling_test($address);
627 my $maybe = $this->_next_sibling_test($address);
628 last if !defined $maybe;
631 $this->log("irspy", "skipping $nskipped tests to '$address'");
634 return ($address, $nskipped);
638 sub _next_sibling_test {
642 my @components = split /:/, $address;
643 my $last = pop @components;
644 my $maybe = join(":", @components, $last+1);
645 return $maybe if $this->{tree}->select($maybe);
655 ZOOM::IRSpy::Maintenance.
657 The ZOOM-Perl module,
658 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
661 http://indexdata.com/zebra/
665 Mike Taylor, E<lt>mike@indexdata.comE<gt>
667 =head1 COPYRIGHT AND LICENSE
669 Copyright (C) 2006 by Index Data ApS.
671 This library is free software; you can redistribute it and/or modify
672 it under the same terms as Perl itself, either Perl version 5.8.7 or,
673 at your option, any later version of Perl 5 you may have available.