1 # $Id: IRSpy.pm,v 1.37 2006-10-26 13:39:13 sondberg 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 => $xslt->parse_stylesheet($xsl_doc),
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 my $p = $this->{conn}->package();
260 $p->option(action => "specialUpdate");
261 my $xml = $rec->toString();
262 $p->option(record => $xml);
266 $p = $this->{conn}->package();
273 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
278 # The approach: gather declarative information about test hierarchy,
279 # then go into a loop. In the loop, we ensure that each connection is
280 # running a test, and within that test a task, until its list of tests
281 # is exhausted. No individual test ever calls wait(): tests just queue
282 # up tasks and return immediately. When the tasks are run (one at a
283 # time on each connection) they generate events, and it is these that
284 # are harvested by ZOOM::event(). Since each connection knows what
285 # task it is running, it can invoke the appropriate callbacks.
286 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
287 # loop how to continue.
290 # While a connection is running a task, its current_task()
291 # points at the task structure. When it finishes its task,
292 # next_task() is pointed at the next task to execute (if there
293 # is one), and its current_task() is set to zero. When the next
294 # task is executed, the connection's next_task() is set to zero
295 # and its current_task() pointed to the task structure.
296 # current_task() and next_task() are both zero only when there
297 # are no more queued tasks, which is when a new test is
300 # Each connection's current test is stored in its
301 # "current_test_address" option. The next test to execute is
302 # calculated by walking the declarative tree of tests. This
303 # option begins empty; the "next test" after this is of course
310 $tname = "Main" if !defined $tname;
311 $this->{tree} = $this->_gather_tests($tname)
312 or die "No tests defined";
313 #$this->{tree}->print(0);
316 my @conn = @{ $this->{connections} };
319 my @copy_conn = @conn; # avoid alias problems after splice()
320 my $nconn = scalar(@copy_conn);
321 foreach my $i0 (0 .. $#copy_conn) {
322 my $conn = $copy_conn[$i0];
323 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
324 if (!$conn->current_task()) {
325 if (!$conn->next_task()) {
326 # Out of tasks: we need a new test
328 my $address = $conn->option("current_test_address");
330 if (!defined $address) {
333 $this->log("irspy_test",
334 "checking for next test after '$address'");
335 $nextaddr = $this->_next_test($address);
337 if (!defined $nextaddr) {
338 $conn->log("irspy", "has no more tests: removing");
339 splice @conn, $i0, 1;
340 $this->_rewrite_record($conn);
344 my $node = $this->{tree}->select($nextaddr)
345 or die "invalid nextaddr '$nextaddr'";
346 $conn->option(current_test_address => $nextaddr);
347 my $tname = $node->name();
348 $conn->log("irspy_test",
349 "starting test '$nextaddr' = $tname");
350 my $tasks = $conn->tasks();
351 my $oldcount = @$tasks;
352 "ZOOM::IRSpy::Test::$tname"->start($conn);
353 $tasks = $conn->tasks();
354 if (@$tasks > $oldcount) {
355 # Prepare to start the first of the newly added tasks
356 $conn->next_task($tasks->[$oldcount]);
358 $conn->log("irspy_task",
359 "no tasks added by new test $tname");
364 my $task = $conn->next_task();
365 die "no next task queued for $conn" if !defined $task;
366 $conn->log("irspy_task", "preparing task $task");
368 $conn->current_task($task);
372 # Do we need to test $conn->is_idle()? I don't think so!
375 my $i0 = ZOOM::event(\@conn);
376 $this->log("irspy_event",
377 "ZOOM_event(", scalar(@conn), " connections) = $i0");
378 last if $i0 == 0 || $i0 == -3; # no events or no connections
379 my $conn = $conn[$i0-1];
380 my $ev = $conn->last_event();
381 my $evstr = ZOOM::event_str($ev);
382 $conn->log("irspy_event", "event $ev ($evstr)");
384 my $task = $conn->current_task();
385 die "$conn has no current task for event $ev ($evstr)" if !$task;
386 eval { $conn->_check() };
388 ($ev == ZOOM::Event::RECV_DATA ||
389 $ev == ZOOM::Event::RECV_APDU ||
390 $ev == ZOOM::Event::ZEND)) {
391 # An error in, say, a search response, becomes visible to
392 # ZOOM before the Receive Data event is sent and persists
393 # until after the End, which means that successive events
394 # each report the same error. So we just ignore errors on
395 # "unimportant" events. ### But this doesn't work for,
396 # say, a Connection Refused, as the only event that shows
397 # us this error is the End.
398 $conn->log("irspy_event", "ignoring error ",
399 "on event $ev ($evstr): $@");
405 my $sub = $task->{cb}->{exception};
406 die $@ if !defined $sub;
407 $res = &$sub($conn, $task, $task->udata(), $@);
409 my $sub = $task->{cb}->{$ev};
411 $conn->log("irspy_unhandled", "event $ev ($evstr)");
415 $res = &$sub($conn, $task, $task->udata(), $ev);
418 if ($res == ZOOM::IRSpy::Status::OK) {
419 # Nothing to do -- life continues
421 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
422 my $task = $conn->current_task();
423 die "no task for TASK_DONE on $conn" if !$task;
424 die "next task already defined for $conn" if $conn->next_task();
425 $conn->log("irspy_task", "completed task $task");
426 $conn->next_task($task->{next});
427 $conn->current_task(0);
429 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
430 $res == ZOOM::IRSpy::Status::TEST_BAD) {
431 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
432 $conn->log("irspy_task", "test ended during task $task ($x)");
433 $conn->log("irspy_test", "test completed ($x)");
434 $conn->current_task(0);
436 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
437 my $address = $conn->option('current_test_address');
438 ($address, my $n) = $this->_last_sibling_test($address);
439 if (defined $address) {
440 $conn->log("irspy_test", "skipped $n tests");
441 $conn->option(current_test_address => $address);
446 die "unknown callback return-value '$res'";
450 $this->log("irspy", "exiting main loop");
457 my($tname, @ancestors) = @_;
459 die("$0: test-hierarchy loop detected: " .
460 join(" -> ", @ancestors, $tname))
461 if grep { $_ eq $tname } @ancestors;
464 my $slashSeperatedTname = $tname;
465 $slashSeperatedTname =~ s/::/\//g;
466 require "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
468 $this->log("warn", "can't load test '$tname': skipping",
469 $@ =~ /^Can.t locate/ ? () : " ($@)");
473 $this->log("irspy", "adding test '$tname'");
475 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
476 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
477 push @subnodes, $subtest if defined $subtest;
480 return new ZOOM::IRSpy::Node($tname, @subnodes);
484 # These next three should arguably be Node methods
487 my($address, $omit_child) = @_;
491 my $maybe = $address eq "" ? "0" : "$address:0";
492 return $maybe if $this->{tree}->select($maybe);
495 # The top-level node has no successor or parent
496 return undef if $address eq "";
498 # Try next sibling child
499 my @components = split /:/, $address;
500 my $last = pop @components;
501 my $maybe = join(":", @components, $last+1);
502 return $maybe if $this->{tree}->select($maybe);
504 # This node is exhausted: try the parent's successor
505 return $this->_next_test(join(":", @components), 1)
509 sub _last_sibling_test {
514 if !defined $this->_next_sibling_test($address);
518 my $maybe = $this->_next_sibling_test($address);
519 last if !defined $maybe;
521 $this->log("irspy", "skipping $nskipped tests to '$address'");
525 return ($address, $nskipped);
529 sub _next_sibling_test {
533 my @components = split /:/, $address;
534 my $last = pop @components;
535 my $maybe = join(":", @components, $last+1);
536 return $maybe if $this->{tree}->select($maybe);
541 # Utility functions follow, exported for use of web UI
543 # I can't -- just can't, can't, can't -- believe that this function
544 # isn't provided by one of the core XML modules. But the evidence all
545 # says that it's not: among other things, XML::Generator and
546 # Template::Plugin both roll their own. So I will do likewise. D'oh!
550 $text =~ s/&/&/g;
553 $text =~ s/['']/'/g;
554 $text =~ s/[""]/"/g;
559 sub irspy_xpath_context {
560 my($zoom_record) = @_;
562 my $xml = $zoom_record->render();
563 my $parser = new XML::LibXML();
564 my $doc = $parser->parse_string($xml);
565 my $root = $doc->getDocumentElement();
566 my $xc = XML::LibXML::XPathContext->new($root);
567 $xc->registerNs(e => 'http://explain.z3950.org/dtd/2.0/');
577 ZOOM::IRSpy::Maintenance.
579 The ZOOM-Perl module,
580 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
583 http://indexdata.com/zebra/
587 Mike Taylor, E<lt>mike@indexdata.comE<gt>
589 =head1 COPYRIGHT AND LICENSE
591 Copyright (C) 2006 by Index Data ApS.
593 This library is free software; you can redistribute it and/or modify
594 it under the same terms as Perl itself, either Perl version 5.8.7 or,
595 at your option, any later version of Perl 5 you may have available.