1 # $Id: IRSpy.pm,v 1.42 2006-10-27 15:36:04 mike Exp $
10 our @EXPORT_OK = qw(xml_encode irspy_xpath_context);
12 use Data::Dumper; # For debugging only
16 use XML::LibXML::XPathContext;
18 use Net::Z3950::ZOOM 1.13; # For the ZOOM version-check only
19 use ZOOM::IRSpy::Node;
20 use ZOOM::IRSpy::Connection;
21 use ZOOM::IRSpy::Record;
24 our $VERSION = '0.02';
25 our $irspy_ns = 'http://indexdata.com/irspy/1.0';
26 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
29 # Enumeration for callback functions to return
30 package ZOOM::IRSpy::Status;
31 sub OK { 29 } # No problems, task is still progressing
32 sub TASK_DONE { 18 } # Task is complete, next task should begin
33 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
34 sub TEST_BAD { 31 } # Whole test is complete, and failed
40 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
45 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
46 print $spy->report_status();
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) = @_;
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;
77 my $libxml = new XML::LibXML;
78 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
79 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
83 allrecords => 1, # unless overridden by targets()
84 query => undef, # filled in later
85 targets => undef, # filled in later
86 connections => undef, # filled in later
88 irspy_to_zeerex_style => $irspy_to_zeerex_style,
89 tests => [], # stack of tests currently being executed
91 $this->log("irspy", "starting up with database '$dbname'");
103 # Explicitly nominate a set of targets to check, overriding the
104 # default which is to re-check everything in the database. Each
105 # target already in the database results in the existing record being
106 # updated; each new target causes a new record to be added.
112 $this->log("irspy", "setting explicit list of targets ",
113 join(", ", map { "'$_'" } @targets));
114 $this->{allrecords} = 0;
116 foreach my $target (@targets) {
117 my($host, $port, $db, $newtarget) = _parse_target_string($target);
118 if ($newtarget ne $target) {
119 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
120 $target = $newtarget; # This is written through the ref
122 push @qlist, (qq[(host="$host" and port="$port" and path="$db")]);
125 $this->{targets} = \@targets;
126 $this->{query} = join(" or ", @qlist);
130 # Also used by ZOOM::IRSpy::Record
131 sub _parse_target_string {
134 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
135 if (!defined $host) {
137 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
138 $target = "$host:$port/$db";
140 die "$0: invalid target string '$target'"
143 return ($host, $port, $db, $target);
147 # There are two cases.
149 # 1. A specific set of targets is nominated on the command line.
150 # - Records must be fetched for those targets that are in the DB
151 # - New, empty records must be made for those that are not.
152 # - Updated records written to the DB may or may not be new.
154 # 2. All records in the database are to be checked.
155 # - Records must be fetched for all targets in the DB
156 # - Updated records written to the DB may not be new.
158 # That's all -- what could be simpler?
164 if ($this->{allrecords}) {
165 # We need to check on every target in the database, which
166 # means we need to do a "find all". According to the BIB-1
167 # semantics document at
168 # http://www.loc.gov/z3950/agency/bib1.html
170 # @attr 2=103 @attr 1=1035 x
171 # should find all records, but it seems that Zebra doesn't
172 # support this. Furthermore, when using the "alvis" filter
173 # (as we do for IRSpy) it doesn't support the use of any BIB-1
174 # access point -- not even 1035 "everywhere" -- so instead we
175 # hack together a search that we know will find all records.
176 $this->{query} = "port=?*";
178 # Prepopulate the target map with nulls so that after we fill
179 # in what we can from the database query, we know which target
180 # IDs we need new records for.
181 foreach my $target (@{ $this->{targets} }) {
182 $target2record{lc($target)} = undef;
186 $this->log("irspy_debug", "query '", $this->{query}, "'");
187 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
188 delete $this->{query}; # No longer needed at all
189 $this->log("irspy_debug", "found ", $rs->size(), " target records");
190 foreach my $i (1 .. $rs->size()) {
191 my $target = _render_record($rs, $i-1, "id");
192 my $zeerex = _render_record($rs, $i-1, "zeerex");
193 #print STDERR "making '$target' record with '$zeerex'\n";
194 $target2record{lc($target)} =
195 new ZOOM::IRSpy::Record($this, $target, $zeerex);
196 push @{ $this->{targets} }, $target
197 if $this->{allrecords};
200 # Make records for targets not previously in the database
201 foreach my $target (keys %target2record) {
202 my $record = $target2record{$target};
203 if (!defined $record) {
204 $this->log("irspy_debug", "made new record for '$target'");
205 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
207 $this->log("irspy_debug", "using existing record for '$target'");
212 foreach my $target (@{ $this->{targets} }) {
213 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
214 $conn->option(host => $target);
215 my $record = delete $target2record{lc($target)};
216 $conn->record($record);
217 push @connections, $conn;
219 die("remaining target2record = { " .
220 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
221 sort keys %target2record) . " }")
224 $this->{connections} = \@connections;
225 delete $this->{targets}; # The information is now in {connections}
230 my($rs, $which, $elementSetName) = @_;
232 # There is a slight race condition here on the element-set name,
233 # but it shouldn't be a problem as this is (currently) only called
234 # from parts of the program that run single-threaded.
235 my $old = $rs->option(elementSetName => $elementSetName);
236 my $rec = $rs->record($which);
237 $rs->option(elementSetName => $old);
239 return $rec->render();
243 sub _irspy_to_zeerex {
244 my ($this, $conn) = @_;
245 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
247 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
249 return $result->documentElement();
253 sub _rewrite_record {
257 $conn->log("irspy", "rewriting XML record");
258 my $rec = $this->_irspy_to_zeerex($conn);
259 _really_rewrite_record($this->{conn}, $rec);
263 sub _really_rewrite_record {
264 my($conn, $rec) = @_;
266 my $p = $conn->package();
267 $p->option(action => "specialUpdate");
268 my $xml = $rec->toString();
269 $p->option(record => $xml);
273 $p = $conn->package();
280 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
285 # The approach: gather declarative information about test hierarchy,
286 # then go into a loop. In the loop, we ensure that each connection is
287 # running a test, and within that test a task, until its list of tests
288 # is exhausted. No individual test ever calls wait(): tests just queue
289 # up tasks and return immediately. When the tasks are run (one at a
290 # time on each connection) they generate events, and it is these that
291 # are harvested by ZOOM::event(). Since each connection knows what
292 # task it is running, it can invoke the appropriate callbacks.
293 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
294 # loop how to continue.
297 # While a connection is running a task, its current_task()
298 # points at the task structure. When it finishes its task,
299 # next_task() is pointed at the next task to execute (if there
300 # is one), and its current_task() is set to zero. When the next
301 # task is executed, the connection's next_task() is set to zero
302 # and its current_task() pointed to the task structure.
303 # current_task() and next_task() are both zero only when there
304 # are no more queued tasks, which is when a new test is
307 # Each connection's current test is stored in its
308 # "current_test_address" option. The next test to execute is
309 # calculated by walking the declarative tree of tests. This
310 # option begins empty; the "next test" after this is of course
317 $tname = "Main" if !defined $tname;
318 $this->{tree} = $this->_gather_tests($tname)
319 or die "No tests defined for '$tname'";
320 #$this->{tree}->print(0);
323 my @conn = @{ $this->{connections} };
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 if (!$conn->current_task()) {
332 if (!$conn->next_task()) {
333 # Out of tasks: we need a new test
335 my $address = $conn->option("current_test_address");
337 if (!defined $address) {
340 $this->log("irspy_test",
341 "checking for next test after '$address'");
342 $nextaddr = $this->_next_test($address);
344 if (!defined $nextaddr) {
345 $conn->log("irspy", "has no more tests: removing");
346 splice @conn, $i0, 1;
347 $this->_rewrite_record($conn);
351 my $node = $this->{tree}->select($nextaddr)
352 or die "invalid nextaddr '$nextaddr'";
353 $conn->option(current_test_address => $nextaddr);
354 my $tname = $node->name();
355 $conn->log("irspy_test",
356 "starting test '$nextaddr' = $tname");
357 my $tasks = $conn->tasks();
358 my $oldcount = @$tasks;
359 "ZOOM::IRSpy::Test::$tname"->start($conn);
360 $tasks = $conn->tasks();
361 if (@$tasks > $oldcount) {
362 # Prepare to start the first of the newly added tasks
363 $conn->next_task($tasks->[$oldcount]);
365 $conn->log("irspy_task",
366 "no tasks added by new test $tname");
371 my $task = $conn->next_task();
372 die "no next task queued for $conn" if !defined $task;
373 $conn->log("irspy_task", "preparing task $task");
375 $conn->current_task($task);
379 # Do we need to test $conn->is_idle()? I don't think so!
382 my $i0 = ZOOM::event(\@conn);
383 $this->log("irspy_event",
384 "ZOOM_event(", scalar(@conn), " connections) = $i0");
385 last if $i0 == 0 || $i0 == -3; # no events or no connections
386 my $conn = $conn[$i0-1];
387 my $ev = $conn->last_event();
388 my $evstr = ZOOM::event_str($ev);
389 $conn->log("irspy_event", "event $ev ($evstr)");
391 my $task = $conn->current_task();
392 die "$conn has no current task for event $ev ($evstr)" if !$task;
393 eval { $conn->_check() };
395 ($ev == ZOOM::Event::RECV_DATA ||
396 $ev == ZOOM::Event::RECV_APDU ||
397 $ev == ZOOM::Event::ZEND)) {
398 # An error in, say, a search response, becomes visible to
399 # ZOOM before the Receive Data event is sent and persists
400 # until after the End, which means that successive events
401 # each report the same error. So we just ignore errors on
402 # "unimportant" events. ### But this doesn't work for,
403 # say, a Connection Refused, as the only event that shows
404 # us this error is the End.
405 $conn->log("irspy_event", "ignoring error ",
406 "on event $ev ($evstr): $@");
412 my $sub = $task->{cb}->{exception};
413 die $@ if !defined $sub;
414 $res = &$sub($conn, $task, $task->udata(), $@);
416 my $sub = $task->{cb}->{$ev};
418 $conn->log("irspy_unhandled", "event $ev ($evstr)");
422 $res = &$sub($conn, $task, $task->udata(), $ev);
425 if ($res == ZOOM::IRSpy::Status::OK) {
426 # Nothing to do -- life continues
428 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
429 my $task = $conn->current_task();
430 die "no task for TASK_DONE on $conn" if !$task;
431 die "next task already defined for $conn" if $conn->next_task();
432 $conn->log("irspy_task", "completed task $task");
433 $conn->next_task($task->{next});
434 $conn->current_task(0);
436 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
437 $res == ZOOM::IRSpy::Status::TEST_BAD) {
438 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
439 $conn->log("irspy_task", "test ended during task $task ($x)");
440 $conn->log("irspy_test", "test completed ($x)");
441 $conn->current_task(0);
443 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
444 my $address = $conn->option('current_test_address');
445 ($address, my $n) = $this->_last_sibling_test($address);
446 if (defined $address) {
447 $conn->log("irspy_test", "skipped $n tests");
448 $conn->option(current_test_address => $address);
453 die "unknown callback return-value '$res'";
457 $this->log("irspy", "exiting main loop");
464 my($tname, @ancestors) = @_;
466 die("$0: test-hierarchy loop detected: " .
467 join(" -> ", @ancestors, $tname))
468 if grep { $_ eq $tname } @ancestors;
470 my $slashSeperatedTname = $tname;
471 $slashSeperatedTname =~ s/::/\//g;
472 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
475 ### This next line shouldn't be necessary, as we should
476 # already be running in an environment where the test
477 # modules are available -- otherwise, how did _this_ module
478 # get loaded? But it seems that for reasons I don't
479 # understand we do sometimes (not always!) need this when
480 # running under Apache.
481 use lib '/usr/local/src/cvs/irspy/lib';
483 $this->log("irspy", "successfully required '$fullName'");
485 $this->log("irspy", "couldn't require '$fullName': $@");
486 $this->log("warn", "can't load test '$tname': skipping",
487 $@ =~ /^Can.t locate/ ? () : " ($@)");
491 $this->log("irspy", "adding test '$tname'");
493 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
494 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
495 push @subnodes, $subtest if defined $subtest;
498 return new ZOOM::IRSpy::Node($tname, @subnodes);
502 # These next three should arguably be Node methods
505 my($address, $omit_child) = @_;
509 my $maybe = $address eq "" ? "0" : "$address:0";
510 return $maybe if $this->{tree}->select($maybe);
513 # The top-level node has no successor or parent
514 return undef if $address eq "";
516 # Try next sibling child
517 my @components = split /:/, $address;
518 my $last = pop @components;
519 my $maybe = join(":", @components, $last+1);
520 return $maybe if $this->{tree}->select($maybe);
522 # This node is exhausted: try the parent's successor
523 return $this->_next_test(join(":", @components), 1)
527 sub _last_sibling_test {
532 if !defined $this->_next_sibling_test($address);
536 my $maybe = $this->_next_sibling_test($address);
537 last if !defined $maybe;
539 $this->log("irspy", "skipping $nskipped tests to '$address'");
543 return ($address, $nskipped);
547 sub _next_sibling_test {
551 my @components = split /:/, $address;
552 my $last = pop @components;
553 my $maybe = join(":", @components, $last+1);
554 return $maybe if $this->{tree}->select($maybe);
559 # Utility functions follow, exported for use of web UI
561 # I can't -- just can't, can't, can't -- believe that this function
562 # isn't provided by one of the core XML modules. But the evidence all
563 # says that it's not: among other things, XML::Generator and
564 # Template::Plugin both roll their own. So I will do likewise. D'oh!
568 $text =~ s/&/&/g;
571 $text =~ s/['']/'/g;
572 $text =~ s/[""]/"/g;
577 sub irspy_xpath_context {
578 my($zoom_record) = @_;
580 my $xml = $zoom_record->render();
581 my $parser = new XML::LibXML();
582 my $doc = $parser->parse_string($xml);
583 my $root = $doc->getDocumentElement();
584 my $xc = XML::LibXML::XPathContext->new($root);
585 $xc->registerNs(e => 'http://explain.z3950.org/dtd/2.0/');
586 $xc->registerNs(i => $irspy_ns);
596 ZOOM::IRSpy::Maintenance.
598 The ZOOM-Perl module,
599 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
602 http://indexdata.com/zebra/
606 Mike Taylor, E<lt>mike@indexdata.comE<gt>
608 =head1 COPYRIGHT AND LICENSE
610 Copyright (C) 2006 by Index Data ApS.
612 This library is free software; you can redistribute it and/or modify
613 it under the same terms as Perl itself, either Perl version 5.8.7 or,
614 at your option, any later version of Perl 5 you may have available.