1 # $Id: IRSpy.pm,v 1.36 2006-10-25 15:42:47 mike Exp $
10 our @EXPORT_OK = qw(xml_encode irspy_xpath_context);
12 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;
21 our $VERSION = '0.02';
22 our $irspy_ns = 'http://indexdata.com/irspy/1.0';
25 # Enumeration for callback functions to return
26 package ZOOM::IRSpy::Status;
27 sub OK { 29 } # No problems, task is still progressing
28 sub TASK_DONE { 18 } # Task is complete, next task should begin
29 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
30 sub TEST_BAD { 31 } # Whole test is complete, and failed
36 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
41 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
42 print $spy->report_status();
46 This module exists to implement the IRspy program, which discovers,
47 analyses and monitors IR servers implementing the Z39.50 and SRU/W
48 protocols. It is a successor to the ZSpy program.
53 ZOOM::Log::mask_str("irspy");
54 ZOOM::Log::mask_str("irspy_debug");
55 ZOOM::Log::mask_str("irspy_event");
56 ZOOM::Log::mask_str("irspy_unhandled");
57 ZOOM::Log::mask_str("irspy_test");
58 ZOOM::Log::mask_str("irspy_task");
63 my($dbname, $user, $password) = @_;
66 push @options, (user => $user, password => $password)
69 my $conn = new ZOOM::Connection($dbname, 0, @options)
70 or die "$0: can't connection to IRSpy database 'dbname'";
74 allrecords => 1, # unless overridden by targets()
75 query => undef, # filled in later
76 targets => undef, # filled in later
77 connections => undef, # filled in later
78 tests => [], # stack of tests currently being executed
80 $this->log("irspy", "starting up with database '$dbname'");
92 # Explicitly nominate a set of targets to check, overriding the
93 # default which is to re-check everything in the database. Each
94 # target already in the database results in the existing record being
95 # updated; each new target causes a new record to be added.
101 $this->log("irspy", "setting explicit list of targets ",
102 join(", ", map { "'$_'" } @targets));
103 $this->{allrecords} = 0;
105 foreach my $target (@targets) {
106 my($host, $port, $db, $newtarget) = _parse_target_string($target);
107 if ($newtarget ne $target) {
108 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
109 $target = $newtarget; # This is written through the ref
111 push @qlist, (qq[(host="$host" and port="$port" and path="$db")]);
114 $this->{targets} = \@targets;
115 $this->{query} = join(" or ", @qlist);
119 # Also used by ZOOM::IRSpy::Record
120 sub _parse_target_string {
123 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
124 if (!defined $host) {
126 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
127 $target = "$host:$port/$db";
129 die "$0: invalid target string '$target'"
132 return ($host, $port, $db, $target);
136 # There are two cases.
138 # 1. A specific set of targets is nominated on the command line.
139 # - Records must be fetched for those targets that are in the DB
140 # - New, empty records must be made for those that are not.
141 # - Updated records written to the DB may or may not be new.
143 # 2. All records in the database are to be checked.
144 # - Records must be fetched for all targets in the DB
145 # - Updated records written to the DB may not be new.
147 # That's all -- what could be simpler?
153 if ($this->{allrecords}) {
154 # We need to check on every target in the database, which
155 # means we need to do a "find all". According to the BIB-1
156 # semantics document at
157 # http://www.loc.gov/z3950/agency/bib1.html
159 # @attr 2=103 @attr 1=1035 x
160 # should find all records, but it seems that Zebra doesn't
161 # support this. Furthermore, when using the "alvis" filter
162 # (as we do for IRSpy) it doesn't support the use of any BIB-1
163 # access point -- not even 1035 "everywhere" -- so instead we
164 # hack together a search that we know will find all records.
165 $this->{query} = "port=?*";
167 # Prepopulate the target map with nulls so that after we fill
168 # in what we can from the database query, we know which target
169 # IDs we need new records for.
170 foreach my $target (@{ $this->{targets} }) {
171 $target2record{lc($target)} = undef;
175 $this->log("irspy_debug", "query '", $this->{query}, "'");
176 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
177 delete $this->{query}; # No longer needed at all
178 $this->log("irspy_debug", "found ", $rs->size(), " target records");
179 foreach my $i (1 .. $rs->size()) {
180 my $target = _render_record($rs, $i-1, "id");
181 my $zeerex = _render_record($rs, $i-1, "zeerex");
182 #print STDERR "making '$target' record with '$zeerex'\n";
183 $target2record{lc($target)} =
184 new ZOOM::IRSpy::Record($this, $target, $zeerex);
185 push @{ $this->{targets} }, $target
186 if $this->{allrecords};
189 # Make records for targets not previously in the database
190 foreach my $target (keys %target2record) {
191 my $record = $target2record{$target};
192 if (!defined $record) {
193 $this->log("irspy_debug", "made new record for '$target'");
194 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
196 $this->log("irspy_debug", "using existing record for '$target'");
201 foreach my $target (@{ $this->{targets} }) {
202 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
203 $conn->option(host => $target);
204 my $record = delete $target2record{lc($target)};
205 $conn->record($record);
206 push @connections, $conn;
208 die("remaining target2record = { " .
209 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
210 sort keys %target2record) . " }")
213 $this->{connections} = \@connections;
214 delete $this->{targets}; # The information is now in {connections}
219 my($rs, $which, $elementSetName) = @_;
221 # There is a slight race condition here on the element-set name,
222 # but it shouldn't be a problem as this is (currently) only called
223 # from parts of the program that run single-threaded.
224 my $old = $rs->option(elementSetName => $elementSetName);
225 my $rec = $rs->record($which);
226 $rs->option(elementSetName => $old);
228 return $rec->render();
232 sub _rewrite_record {
236 $conn->log("irspy", "rewriting XML record");
237 my $rec = $conn->record();
238 my $p = $this->{conn}->package();
239 $p->option(action => "specialUpdate");
240 my $xml = $rec->{zeerex}->toString();
241 $p->option(record => $xml);
245 $p = $this->{conn}->package();
252 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
257 # The approach: gather declarative information about test hierarchy,
258 # then go into a loop. In the loop, we ensure that each connection is
259 # running a test, and within that test a task, until its list of tests
260 # is exhausted. No individual test ever calls wait(): tests just queue
261 # up tasks and return immediately. When the tasks are run (one at a
262 # time on each connection) they generate events, and it is these that
263 # are harvested by ZOOM::event(). Since each connection knows what
264 # task it is running, it can invoke the appropriate callbacks.
265 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
266 # loop how to continue.
269 # While a connection is running a task, its current_task()
270 # points at the task structure. When it finishes its task,
271 # next_task() is pointed at the next task to execute (if there
272 # is one), and its current_task() is set to zero. When the next
273 # task is executed, the connection's next_task() is set to zero
274 # and its current_task() pointed to the task structure.
275 # current_task() and next_task() are both zero only when there
276 # are no more queued tasks, which is when a new test is
279 # Each connection's current test is stored in its
280 # "current_test_address" option. The next test to execute is
281 # calculated by walking the declarative tree of tests. This
282 # option begins empty; the "next test" after this is of course
289 $tname = "Main" if !defined $tname;
290 $this->{tree} = $this->_gather_tests($tname)
291 or die "No tests defined";
292 #$this->{tree}->print(0);
295 my @conn = @{ $this->{connections} };
298 my @copy_conn = @conn; # avoid alias problems after splice()
299 my $nconn = scalar(@copy_conn);
300 foreach my $i0 (0 .. $#copy_conn) {
301 my $conn = $copy_conn[$i0];
302 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
303 if (!$conn->current_task()) {
304 if (!$conn->next_task()) {
305 # Out of tasks: we need a new test
307 my $address = $conn->option("current_test_address");
309 if (!defined $address) {
312 $this->log("irspy_test",
313 "checking for next test after '$address'");
314 $nextaddr = $this->_next_test($address);
316 if (!defined $nextaddr) {
317 $conn->log("irspy", "has no more tests: removing");
318 splice @conn, $i0, 1;
319 $this->_rewrite_record($conn);
323 my $node = $this->{tree}->select($nextaddr)
324 or die "invalid nextaddr '$nextaddr'";
325 $conn->option(current_test_address => $nextaddr);
326 my $tname = $node->name();
327 $conn->log("irspy_test",
328 "starting test '$nextaddr' = $tname");
329 my $tasks = $conn->tasks();
330 my $oldcount = @$tasks;
331 "ZOOM::IRSpy::Test::$tname"->start($conn);
332 $tasks = $conn->tasks();
333 if (@$tasks > $oldcount) {
334 # Prepare to start the first of the newly added tasks
335 $conn->next_task($tasks->[$oldcount]);
337 $conn->log("irspy_task",
338 "no tasks added by new test $tname");
343 my $task = $conn->next_task();
344 die "no next task queued for $conn" if !defined $task;
345 $conn->log("irspy_task", "preparing task $task");
347 $conn->current_task($task);
351 # Do we need to test $conn->is_idle()? I don't think so!
354 my $i0 = ZOOM::event(\@conn);
355 $this->log("irspy_event",
356 "ZOOM_event(", scalar(@conn), " connections) = $i0");
357 last if $i0 == 0 || $i0 == -3; # no events or no connections
358 my $conn = $conn[$i0-1];
359 my $ev = $conn->last_event();
360 my $evstr = ZOOM::event_str($ev);
361 $conn->log("irspy_event", "event $ev ($evstr)");
363 my $task = $conn->current_task();
364 die "$conn has no current task for event $ev ($evstr)" if !$task;
365 eval { $conn->_check() };
367 ($ev == ZOOM::Event::RECV_DATA ||
368 $ev == ZOOM::Event::RECV_APDU ||
369 $ev == ZOOM::Event::ZEND)) {
370 # An error in, say, a search response, becomes visible to
371 # ZOOM before the Receive Data event is sent and persists
372 # until after the End, which means that successive events
373 # each report the same error. So we just ignore errors on
374 # "unimportant" events. ### But this doesn't work for,
375 # say, a Connection Refused, as the only event that shows
376 # us this error is the End.
377 $conn->log("irspy_event", "ignoring error ",
378 "on event $ev ($evstr): $@");
384 my $sub = $task->{cb}->{exception};
385 die $@ if !defined $sub;
386 $res = &$sub($conn, $task, $task->udata(), $@);
388 my $sub = $task->{cb}->{$ev};
390 $conn->log("irspy_unhandled", "event $ev ($evstr)");
394 $res = &$sub($conn, $task, $task->udata(), $ev);
397 if ($res == ZOOM::IRSpy::Status::OK) {
398 # Nothing to do -- life continues
400 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
401 my $task = $conn->current_task();
402 die "no task for TASK_DONE on $conn" if !$task;
403 die "next task already defined for $conn" if $conn->next_task();
404 $conn->log("irspy_task", "completed task $task");
405 $conn->next_task($task->{next});
406 $conn->current_task(0);
408 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
409 $res == ZOOM::IRSpy::Status::TEST_BAD) {
410 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
411 $conn->log("irspy_task", "test ended during task $task ($x)");
412 $conn->log("irspy_test", "test completed ($x)");
413 $conn->current_task(0);
415 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
416 my $address = $conn->option('current_test_address');
417 ($address, my $n) = $this->_last_sibling_test($address);
418 if (defined $address) {
419 $conn->log("irspy_test", "skipped $n tests");
420 $conn->option(current_test_address => $address);
425 die "unknown callback return-value '$res'";
429 $this->log("irspy", "exiting main loop");
436 my($tname, @ancestors) = @_;
438 die("$0: test-hierarchy loop detected: " .
439 join(" -> ", @ancestors, $tname))
440 if grep { $_ eq $tname } @ancestors;
443 my $slashSeperatedTname = $tname;
444 $slashSeperatedTname =~ s/::/\//g;
445 require "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
447 $this->log("warn", "can't load test '$tname': skipping",
448 $@ =~ /^Can.t locate/ ? () : " ($@)");
452 $this->log("irspy", "adding test '$tname'");
454 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
455 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
456 push @subnodes, $subtest if defined $subtest;
459 return new ZOOM::IRSpy::Node($tname, @subnodes);
463 # These next three should arguably be Node methods
466 my($address, $omit_child) = @_;
470 my $maybe = $address eq "" ? "0" : "$address:0";
471 return $maybe if $this->{tree}->select($maybe);
474 # The top-level node has no successor or parent
475 return undef if $address eq "";
477 # Try next sibling child
478 my @components = split /:/, $address;
479 my $last = pop @components;
480 my $maybe = join(":", @components, $last+1);
481 return $maybe if $this->{tree}->select($maybe);
483 # This node is exhausted: try the parent's successor
484 return $this->_next_test(join(":", @components), 1)
488 sub _last_sibling_test {
493 if !defined $this->_next_sibling_test($address);
497 my $maybe = $this->_next_sibling_test($address);
498 last if !defined $maybe;
500 $this->log("irspy", "skipping $nskipped tests to '$address'");
504 return ($address, $nskipped);
508 sub _next_sibling_test {
512 my @components = split /:/, $address;
513 my $last = pop @components;
514 my $maybe = join(":", @components, $last+1);
515 return $maybe if $this->{tree}->select($maybe);
520 # Utility functions follow, exported for use of web UI
522 # I can't -- just can't, can't, can't -- believe that this function
523 # isn't provided by one of the core XML modules. But the evidence all
524 # says that it's not: among other things, XML::Generator and
525 # Template::Plugin both roll their own. So I will do likewise. D'oh!
529 $text =~ s/&/&/g;
532 $text =~ s/['']/'/g;
533 $text =~ s/[""]/"/g;
538 sub irspy_xpath_context {
539 my($zoom_record) = @_;
541 my $xml = $zoom_record->render();
542 my $parser = new XML::LibXML();
543 my $doc = $parser->parse_string($xml);
544 my $root = $doc->getDocumentElement();
545 my $xc = XML::LibXML::XPathContext->new($root);
546 $xc->registerNs(e => 'http://explain.z3950.org/dtd/2.0/');
556 ZOOM::IRSpy::Maintenance.
558 The ZOOM-Perl module,
559 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
562 http://indexdata.com/zebra/
566 Mike Taylor, E<lt>mike@indexdata.comE<gt>
568 =head1 COPYRIGHT AND LICENSE
570 Copyright (C) 2006 by Index Data ApS.
572 This library is free software; you can redistribute it and/or modify
573 it under the same terms as Perl itself, either Perl version 5.8.7 or,
574 at your option, any later version of Perl 5 you may have available.