1 # $Id: IRSpy.pm,v 1.44 2006-10-30 15:04:33 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;
22 use ZOOM::IRSpy::Utils;
25 our $VERSION = '0.02';
26 our $irspy_ns = 'http://indexdata.com/irspy/1.0';
27 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
30 # Enumeration for callback functions to return
31 package ZOOM::IRSpy::Status;
32 sub OK { 29 } # No problems, task is still progressing
33 sub TASK_DONE { 18 } # Task is complete, next task should begin
34 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
35 sub TEST_BAD { 31 } # Whole test is complete, and failed
41 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
46 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
47 print $spy->report_status();
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;
78 my $libxml = new XML::LibXML;
79 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
80 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
84 allrecords => 1, # unless overridden by targets()
85 query => undef, # filled in later
86 targets => undef, # filled in later
87 connections => undef, # filled in later
89 irspy_to_zeerex_style => $irspy_to_zeerex_style,
90 tests => [], # stack of tests currently being executed
92 $this->log("irspy", "starting up with database '$dbname'");
104 # Explicitly nominate a set of targets to check, overriding the
105 # default which is to re-check everything in the database. Each
106 # target already in the database results in the existing record being
107 # updated; each new target causes a new record to be added.
113 $this->log("irspy", "setting explicit list of targets ",
114 join(", ", map { "'$_'" } @targets));
115 $this->{allrecords} = 0;
117 foreach my $target (@targets) {
118 my($host, $port, $db, $newtarget) = _parse_target_string($target);
119 if ($newtarget ne $target) {
120 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
121 $target = $newtarget; # This is written through the ref
123 push @qlist, (qq[(host="$host" and port="$port" and path="$db")]);
126 $this->{targets} = \@targets;
127 $this->{query} = join(" or ", @qlist);
131 # Also used by ZOOM::IRSpy::Record
132 sub _parse_target_string {
135 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
136 if (!defined $host) {
138 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
139 $target = "$host:$port/$db";
141 die "$0: invalid target string '$target'"
144 return ($host, $port, $db, $target);
148 # There are two cases.
150 # 1. A specific set of targets is nominated on the command line.
151 # - Records must be fetched for those targets that are in the DB
152 # - New, empty records must be made for those that are not.
153 # - Updated records written to the DB may or may not be new.
155 # 2. All records in the database are to be checked.
156 # - Records must be fetched for all targets in the DB
157 # - Updated records written to the DB may not be new.
159 # That's all -- what could be simpler?
165 if ($this->{allrecords}) {
166 # We need to check on every target in the database, which
167 # means we need to do a "find all". According to the BIB-1
168 # semantics document at
169 # http://www.loc.gov/z3950/agency/bib1.html
171 # @attr 2=103 @attr 1=1035 x
172 # should find all records, but it seems that Zebra doesn't
173 # support this. Furthermore, when using the "alvis" filter
174 # (as we do for IRSpy) it doesn't support the use of any BIB-1
175 # access point -- not even 1035 "everywhere" -- so instead we
176 # hack together a search that we know will find all records.
177 $this->{query} = "port=?*";
179 # Prepopulate the target map with nulls so that after we fill
180 # in what we can from the database query, we know which target
181 # IDs we need new records for.
182 foreach my $target (@{ $this->{targets} }) {
183 $target2record{lc($target)} = undef;
187 $this->log("irspy_debug", "query '", $this->{query}, "'");
188 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
189 delete $this->{query}; # No longer needed at all
190 $this->log("irspy_debug", "found ", $rs->size(), " target records");
191 foreach my $i (1 .. $rs->size()) {
192 my $target = _render_record($rs, $i-1, "id");
193 my $zeerex = _render_record($rs, $i-1, "zeerex");
194 #print STDERR "making '$target' record with '$zeerex'\n";
195 $target2record{lc($target)} =
196 new ZOOM::IRSpy::Record($this, $target, $zeerex);
197 push @{ $this->{targets} }, $target
198 if $this->{allrecords};
201 # Make records for targets not previously in the database
202 foreach my $target (keys %target2record) {
203 my $record = $target2record{$target};
204 if (!defined $record) {
205 $this->log("irspy_debug", "made new record for '$target'");
206 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
208 $this->log("irspy_debug", "using existing record for '$target'");
213 foreach my $target (@{ $this->{targets} }) {
214 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
215 $conn->option(host => $target);
216 my $record = delete $target2record{lc($target)};
217 $conn->record($record);
218 push @connections, $conn;
220 die("remaining target2record = { " .
221 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
222 sort keys %target2record) . " }")
225 $this->{connections} = \@connections;
226 delete $this->{targets}; # The information is now in {connections}
231 my($rs, $which, $elementSetName) = @_;
233 # There is a slight race condition here on the element-set name,
234 # but it shouldn't be a problem as this is (currently) only called
235 # from parts of the program that run single-threaded.
236 my $old = $rs->option(elementSetName => $elementSetName);
237 my $rec = $rs->record($which);
238 $rs->option(elementSetName => $old);
240 return $rec->render();
244 sub _irspy_to_zeerex {
245 my ($this, $conn) = @_;
246 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
248 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
250 return $result->documentElement();
254 sub _rewrite_record {
258 $conn->log("irspy", "rewriting XML record");
259 my $rec = $this->_irspy_to_zeerex($conn);
260 _really_rewrite_record($this->{conn}, $rec);
264 sub _really_rewrite_record {
265 my($conn, $rec) = @_;
267 my $p = $conn->package();
268 $p->option(action => "specialUpdate");
269 my $xml = $rec->toString();
270 $p->option(record => $xml);
274 $p = $conn->package();
281 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
286 # The approach: gather declarative information about test hierarchy,
287 # then go into a loop. In the loop, we ensure that each connection is
288 # running a test, and within that test a task, until its list of tests
289 # is exhausted. No individual test ever calls wait(): tests just queue
290 # up tasks and return immediately. When the tasks are run (one at a
291 # time on each connection) they generate events, and it is these that
292 # are harvested by ZOOM::event(). Since each connection knows what
293 # task it is running, it can invoke the appropriate callbacks.
294 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
295 # loop how to continue.
298 # While a connection is running a task, its current_task()
299 # points at the task structure. When it finishes its task,
300 # next_task() is pointed at the next task to execute (if there
301 # is one), and its current_task() is set to zero. When the next
302 # task is executed, the connection's next_task() is set to zero
303 # and its current_task() pointed to the task structure.
304 # current_task() and next_task() are both zero only when there
305 # are no more queued tasks, which is when a new test is
308 # Each connection's current test is stored in its
309 # "current_test_address" option. The next test to execute is
310 # calculated by walking the declarative tree of tests. This
311 # option begins empty; the "next test" after this is of course
318 $tname = "Main" if !defined $tname;
319 $this->{tree} = $this->_gather_tests($tname)
320 or die "No tests defined for '$tname'";
321 #$this->{tree}->print(0);
324 my @conn = @{ $this->{connections} };
327 my @copy_conn = @conn; # avoid alias problems after splice()
328 my $nconn = scalar(@copy_conn);
329 foreach my $i0 (0 .. $#copy_conn) {
330 my $conn = $copy_conn[$i0];
331 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
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 $this->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 splice @conn, $i0, 1;
348 $this->_rewrite_record($conn);
352 my $node = $this->{tree}->select($nextaddr)
353 or die "invalid nextaddr '$nextaddr'";
354 $conn->option(current_test_address => $nextaddr);
355 my $tname = $node->name();
356 $conn->log("irspy_test",
357 "starting test '$nextaddr' = $tname");
358 my $tasks = $conn->tasks();
359 my $oldcount = @$tasks;
360 "ZOOM::IRSpy::Test::$tname"->start($conn);
361 $tasks = $conn->tasks();
362 if (@$tasks > $oldcount) {
363 # Prepare to start the first of the newly added tasks
364 $conn->next_task($tasks->[$oldcount]);
366 $conn->log("irspy_task",
367 "no tasks added by new test $tname");
372 my $task = $conn->next_task();
373 die "no next task queued for $conn" if !defined $task;
374 $conn->log("irspy_task", "preparing task $task");
376 $conn->current_task($task);
380 # Do we need to test $conn->is_idle()? I don't think so!
383 my $i0 = ZOOM::event(\@conn);
384 $this->log("irspy_event",
385 "ZOOM_event(", scalar(@conn), " connections) = $i0");
386 last if $i0 == 0 || $i0 == -3; # no events or no connections
387 my $conn = $conn[$i0-1];
388 my $ev = $conn->last_event();
389 my $evstr = ZOOM::event_str($ev);
390 $conn->log("irspy_event", "event $ev ($evstr)");
392 my $task = $conn->current_task();
393 die "$conn has no current task for event $ev ($evstr)" if !$task;
394 eval { $conn->_check() };
396 ($ev == ZOOM::Event::RECV_DATA ||
397 $ev == ZOOM::Event::RECV_APDU ||
398 $ev == ZOOM::Event::ZEND)) {
399 # An error in, say, a search response, becomes visible to
400 # ZOOM before the Receive Data event is sent and persists
401 # until after the End, which means that successive events
402 # each report the same error. So we just ignore errors on
403 # "unimportant" events. ### But this doesn't work for,
404 # say, a Connection Refused, as the only event that shows
405 # us this error is the End.
406 $conn->log("irspy_event", "ignoring error ",
407 "on event $ev ($evstr): $@");
413 my $sub = $task->{cb}->{exception};
414 die $@ if !defined $sub;
415 $res = &$sub($conn, $task, $task->udata(), $@);
417 my $sub = $task->{cb}->{$ev};
419 $conn->log("irspy_unhandled", "event $ev ($evstr)");
423 $res = &$sub($conn, $task, $task->udata(), $ev);
426 if ($res == ZOOM::IRSpy::Status::OK) {
427 # Nothing to do -- life continues
429 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
430 my $task = $conn->current_task();
431 die "no task for TASK_DONE on $conn" if !$task;
432 die "next task already defined for $conn" if $conn->next_task();
433 $conn->log("irspy_task", "completed task $task");
434 $conn->next_task($task->{next});
435 $conn->current_task(0);
437 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
438 $res == ZOOM::IRSpy::Status::TEST_BAD) {
439 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
440 $conn->log("irspy_task", "test ended during task $task ($x)");
441 $conn->log("irspy_test", "test completed ($x)");
442 $conn->current_task(0);
444 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
445 my $address = $conn->option('current_test_address');
446 ($address, my $n) = $this->_last_sibling_test($address);
447 if (defined $address) {
448 $conn->log("irspy_test", "skipped $n tests");
449 $conn->option(current_test_address => $address);
454 die "unknown callback return-value '$res'";
458 $this->log("irspy", "exiting main loop");
465 my($tname, @ancestors) = @_;
467 die("$0: test-hierarchy loop detected: " .
468 join(" -> ", @ancestors, $tname))
469 if grep { $_ eq $tname } @ancestors;
471 my $slashSeperatedTname = $tname;
472 $slashSeperatedTname =~ s/::/\//g;
473 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
477 $this->log("irspy", "successfully required '$fullName'");
479 $this->log("irspy", "couldn't require '$fullName': $@");
480 $this->log("warn", "can't load test '$tname': skipping",
481 $@ =~ /^Can.t locate/ ? () : " ($@)");
485 $this->log("irspy", "adding test '$tname'");
487 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
488 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
489 push @subnodes, $subtest if defined $subtest;
492 return new ZOOM::IRSpy::Node($tname, @subnodes);
496 # These next three should arguably be Node methods
499 my($address, $omit_child) = @_;
503 my $maybe = $address eq "" ? "0" : "$address:0";
504 return $maybe if $this->{tree}->select($maybe);
507 # The top-level node has no successor or parent
508 return undef if $address eq "";
510 # Try next sibling child
511 my @components = split /:/, $address;
512 my $last = pop @components;
513 my $maybe = join(":", @components, $last+1);
514 return $maybe if $this->{tree}->select($maybe);
516 # This node is exhausted: try the parent's successor
517 return $this->_next_test(join(":", @components), 1)
521 sub _last_sibling_test {
526 if !defined $this->_next_sibling_test($address);
530 my $maybe = $this->_next_sibling_test($address);
531 last if !defined $maybe;
533 $this->log("irspy", "skipping $nskipped tests to '$address'");
537 return ($address, $nskipped);
541 sub _next_sibling_test {
545 my @components = split /:/, $address;
546 my $last = pop @components;
547 my $maybe = join(":", @components, $last+1);
548 return $maybe if $this->{tree}->select($maybe);
553 # Utility functions follow, exported for use of web UI
555 # I can't -- just can't, can't, can't -- believe that this function
556 # isn't provided by one of the core XML modules. But the evidence all
557 # says that it's not: among other things, XML::Generator and
558 # Template::Plugin both roll their own. So I will do likewise. D'oh!
562 $text =~ s/&/&/g;
565 $text =~ s/['']/'/g;
566 $text =~ s/[""]/"/g;
571 sub irspy_xpath_context {
572 my($zoom_record) = @_;
574 my $xml = $zoom_record->render();
575 my $parser = new XML::LibXML();
576 my $doc = $parser->parse_string($xml);
577 my $root = $doc->getDocumentElement();
578 my $xc = XML::LibXML::XPathContext->new($root);
579 $xc->registerNs(e => 'http://explain.z3950.org/dtd/2.0/');
580 $xc->registerNs(i => $irspy_ns);
590 ZOOM::IRSpy::Maintenance.
592 The ZOOM-Perl module,
593 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
596 http://indexdata.com/zebra/
600 Mike Taylor, E<lt>mike@indexdata.comE<gt>
602 =head1 COPYRIGHT AND LICENSE
604 Copyright (C) 2006 by Index Data ApS.
606 This library is free software; you can redistribute it and/or modify
607 it under the same terms as Perl itself, either Perl version 5.8.7 or,
608 at your option, any later version of Perl 5 you may have available.