1 # $Id: IRSpy.pm,v 1.25 2006-10-11 16:44:04 mike Exp $
9 use Data::Dumper; # For debugging only
10 use ZOOM::IRSpy::Node;
11 use ZOOM::IRSpy::Connection;
12 use ZOOM::IRSpy::Record;
15 our $VERSION = '0.02';
18 # Enumeration for callback functions to return
19 package ZOOM::IRSpy::Status;
20 sub OK { 29 } # No problems, task is still progressing
21 sub TASK_DONE { 18 } # Task is complete, next task should begin
22 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
23 sub TEST_BAD { 31 } # Whole test is complete, and failed
29 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
34 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
35 print $spy->report_status();
39 This module exists to implement the IRspy program, which discovers,
40 analyses and monitors IR servers implementing the Z39.50 and SRU/W
41 protocols. It is a successor to the ZSpy program.
46 ZOOM::Log::mask_str("irspy");
47 ZOOM::Log::mask_str("irspy_test");
48 ZOOM::Log::mask_str("irspy_debug");
49 ZOOM::Log::mask_str("irspy_event");
50 ZOOM::Log::mask_str("irspy_unhandled");
55 my($dbname, $user, $password) = @_;
58 push @options, (user => $user, password => $password)
61 my $conn = new ZOOM::Connection($dbname, 0, @options)
62 or die "$0: can't connection to IRSpy database 'dbname'";
66 allrecords => 1, # unless overridden by targets()
67 query => undef, # filled in later
68 targets => undef, # filled in later
69 connections => undef, # filled in later
70 tests => [], # stack of tests currently being executed
72 $this->log("irspy", "starting up with database '$dbname'");
84 # Explicitly nominate a set of targets to check, overriding the
85 # default which is to re-check everything in the database. Each
86 # target already in the database results in the existing record being
87 # updated; each new target causes a new record to be added.
93 $this->log("irspy", "setting explicit list of targets ",
94 join(", ", map { "'$_'" } @targets));
95 $this->{allrecords} = 0;
97 foreach my $target (@targets) {
98 my($host, $port, $db, $newtarget) = _parse_target_string($target);
99 if ($newtarget ne $target) {
100 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
101 $target = $newtarget; # This is written through the ref
103 push @qlist, (qq[(host="$host" and port="$port" and path="$db")]);
106 $this->{targets} = \@targets;
107 $this->{query} = join(" or ", @qlist);
111 # Also used by ZOOM::IRSpy::Record
112 sub _parse_target_string {
115 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
116 if (!defined $host) {
118 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
119 $target = "$host:$port/$db";
121 die "$0: invalid target string '$target'"
124 return ($host, $port, $db, $target);
128 # There are two cases.
130 # 1. A specific set of targets is nominated on the command line.
131 # - Records must be fetched for those targets that are in the DB
132 # - New, empty records must be made for those that are not.
133 # - Updated records written to the DB may or may not be new.
135 # 2. All records in the database are to be checked.
136 # - Records must be fetched for all targets in the DB
137 # - Updated records written to the DB may not be new.
139 # That's all -- what could be simpler?
145 if ($this->{allrecords}) {
146 # We need to check on every target in the database, which
147 # means we need to do a "find all". According to the BIB-1
148 # semantics document at
149 # http://www.loc.gov/z3950/agency/bib1.html
151 # @attr 2=103 @attr 1=1035 x
152 # should find all records, but it seems that Zebra doesn't
153 # support this. Furthermore, when using the "alvis" filter
154 # (as we do for IRSpy) it doesn't support the use of any BIB-1
155 # access point -- not even 1035 "everywhere" -- so instead we
156 # hack together a search that we know will find all records.
157 $this->{query} = "port=?*";
159 # Prepopulate the target map with nulls so that after we fill
160 # in what we can from the database query, we know which target
161 # IDs we need new records for.
162 foreach my $target (@{ $this->{targets} }) {
163 $target2record{lc($target)} = undef;
167 $this->log("irspy_debug", "query '", $this->{query}, "'");
168 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
169 delete $this->{query}; # No longer needed at all
170 $this->log("irspy_debug", "found ", $rs->size(), " target records");
171 foreach my $i (1 .. $rs->size()) {
172 my $target = _render_record($rs, $i-1, "id");
173 my $zeerex = _render_record($rs, $i-1, "zeerex");
174 #print STDERR "making '$target' record with '$zeerex'\n";
175 $target2record{lc($target)} =
176 new ZOOM::IRSpy::Record($this, $target, $zeerex);
177 push @{ $this->{targets} }, $target
178 if $this->{allrecords};
181 # Make records for targets not previously in the database
182 foreach my $target (keys %target2record) {
183 my $record = $target2record{$target};
184 if (!defined $record) {
185 $this->log("irspy_debug", "made new record for '$target'");
186 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
188 $this->log("irspy_debug", "using existing record for '$target'");
193 foreach my $target (@{ $this->{targets} }) {
194 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
195 $conn->option(host => $target);
196 my $record = delete $target2record{lc($target)};
197 $conn->record($record);
198 push @connections, $conn;
200 die("remaining target2record = { " .
201 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
202 sort keys %target2record) . " }")
205 $this->{connections} = \@connections;
206 delete $this->{targets}; # The information is now in {connections}
211 my($rs, $which, $elementSetName) = @_;
213 # There is a slight race condition here on the element-set name,
214 # but it shouldn't be a problem as this is (currently) only called
215 # from parts of the program that run single-threaded.
216 my $old = $rs->option(elementSetName => $elementSetName);
217 my $rec = $rs->record($which);
218 $rs->option(elementSetName => $old);
220 return $rec->render();
224 sub _rewrite_records {
227 # Write modified records back to database
228 foreach my $conn (@{ $this->{connections} }) {
229 my $rec = $conn->record();
230 my $p = $this->{conn}->package();
231 $p->option(action => "specialUpdate");
232 my $xml = $rec->{zeerex}->toString();
233 $p->option(record => $xml);
237 $p = $this->{conn}->package();
244 print "Updated with xml=<br/>\n<pre>$xml</pre>\n";
250 # The approach: gather declarative information about test hierarchy,
251 # then go into a loop. In the loop, we ensure that each connection is
252 # running a test, and within that test a task, until its list of tests
253 # is exhausted. No individual test ever calls wait(): tests just queue
254 # up tasks and return immediately. When the tasks are run (one at a
255 # time on each connection) they generate events, and it is these that
256 # are harvested by ZOOM::event(). Since each connection knows what
257 # task it is running, it can invoke the appropriate callbacks.
258 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
259 # loop how to continue.
262 # While a connection is running a task, its current_task()
263 # points at the task structure. When it finishes its task,
264 # next_task() is pointed at the next task to execute (if there
265 # is one), and its current_task() is set to zero. When the next
266 # task is executed, the connection's next_task() is set to zero
267 # and its current_task() pointed to the task structure.
268 # current_task() and next_task() are both zero only when there
269 # are no more queued tasks, which is when a new test is
272 # Each connection's current test is stored in its
273 # "current_test_address" option. The next test to execute is
274 # calculated by walking the declarative tree of tests. This
275 # option begins empty; the "next test" after this is of course
282 $tname = "Main" if !defined $tname;
283 $this->{tree} = $this->_gather_tests($tname)
284 or die "No tests defined";
285 #$this->{tree}->print(0);
288 my @conn = @{ $this->{connections} };
291 my @copy_conn = @conn; # avoid alias problems after splice()
292 foreach my $i0 (0 .. $#copy_conn) {
293 my $conn = $copy_conn[$i0];
294 #print "connection $i0 of ", scalar(@copy_conn), " from ", scalar(@conn), " is $conn\n";
295 if (!$conn->current_task()) {
296 if (!$conn->next_task()) {
297 # Out of tasks: we need a new test
299 my $address = $conn->option("current_test_address");
300 my $nextaddr = defined $address ?
301 $this->_next_test($address) : "";
302 if (!defined $nextaddr) {
303 $conn->log("irspy", "has no more tests: removing");
304 splice @conn, $i0, 1;
308 my $node = $this->{tree}->select($nextaddr)
309 or die "invalid nextaddr '$nextaddr'";
310 $conn->option(current_test_address => $nextaddr);
311 my $tname = $node->name();
312 $conn->log("irspy", "starting test '$nextaddr' = $tname");
313 my $tasks = $conn->tasks();
314 my $oldcount = @$tasks;
315 "ZOOM::IRSpy::Test::$tname"->start($conn);
316 $tasks = $conn->tasks();
317 if (@$tasks > $oldcount) {
318 # Prepare to start the first of the newly added tasks
319 $conn->next_task($tasks->[$oldcount]);
321 $conn->log("irspy", "no tasks added by new test $tname");
326 my $task = $conn->next_task();
327 die "no next task queued for $conn" if !defined $task;
328 $conn->log("irspy", "starting task $task");
330 $conn->current_task($task);
334 ### Test $conn->is_idle() here?
337 my $i0 = ZOOM::event(\@conn);
338 $this->log("irspy_event", "ZOOM_event(", scalar(@conn), " connections) = $i0");
339 last if $i0 == 0 || $i0 == -3; # no events or no connections
340 my $conn = $conn[$i0-1];
341 my $ev = $conn->last_event();
342 my $evstr = ZOOM::event_str($ev);
343 $conn->log("irspy_event", "event $ev ($evstr)");
345 my $task = $conn->current_task();
346 die "$conn has no current task for event $ev ($evstr)" if !$task;
347 eval { $conn->_check() };
349 ($ev == ZOOM::Event::RECV_DATA ||
350 $ev == ZOOM::Event::RECV_APDU ||
351 $ev == ZOOM::Event::ZEND)) {
352 # An error in, say, a search response, becomes visible to
353 # ZOOM before the Receive Data event is sent and persists
354 # until after the End, which means that successive events
355 # each report the same error. So we just ignore errors on
356 # "unimportant" events. ### But this doesn't work for,
357 # say, a Connection Refused, as the only event that shows
358 # us this error is the End.
359 $conn->log("irspy_event", "ignoring error ",
360 "on event $ev ($evstr): $@");
366 my $sub = $task->{cb}->{exception};
367 die $@ if !defined $sub;
368 $res = &$sub($conn, $task, $@);
370 my $sub = $task->{cb}->{$ev};
372 $conn->log("irspy_unhandled", "event $ev ($evstr)");
376 $res = &$sub($conn, $task, $ev);
379 if ($res == ZOOM::IRSpy::Status::OK) {
380 # Nothing to do -- life continues
382 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
383 my $task = $conn->current_task();
384 die "no task for TASK_DONE on $conn" if !$task;
385 die "next task already defined for $conn" if $conn->next_task();
386 $conn->log("irspy", "completed task $task");
387 $conn->next_task($task->{next});
388 $conn->current_task(0);
390 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
391 $res == ZOOM::IRSpy::Status::TEST_BAD) {
392 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
393 $conn->log("irspy", "test completed ($x)");
394 $conn->current_task(0);
396 ### Should also skip over remaining sibling tests if TEST_BAD
397 $nskipped += 1; # should count number of skipped siblings
401 $this->log("irspy_event", "no more events: finishing");
403 #$this->_rewrite_records();
410 my($tname, @ancestors) = @_;
412 die("$0: test-hierarchy loop detected: " .
413 join(" -> ", @ancestors, $tname))
414 if grep { $_ eq $tname } @ancestors;
417 my $slashSeperatedTname = $tname;
418 $slashSeperatedTname =~ s/::/\//g;
419 require "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
421 $this->log("warn", "can't load test '$tname': skipping",
422 $@ =~ /^Can.t locate/ ? () : " ($@)");
426 $this->log("irspy", "adding test '$tname'");
428 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
429 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
430 push @subnodes, $subtest if defined $subtest;
433 return new ZOOM::IRSpy::Node($tname, @subnodes);
439 my($address, $omit_child) = @_;
441 $this->log("irspy", "checking for next test after '$address'");
445 my $maybe = $address eq "" ? "0" : "$address:0";
446 return $maybe if $this->{tree}->select($maybe);
449 # The top-level node has no successor or parent
450 return undef if $address eq "";
452 # Try next sibling child
453 my @components = split /:/, $address;
454 my $last = pop @components;
455 my $maybe = join(":", @components, $last+1);
456 return $maybe if $this->{tree}->select($maybe);
458 # This node is exhausted: try the parent's successor
459 return $this->_next_test(join(":", @components), 1)
468 ZOOM::IRSpy::Maintenance.
470 The ZOOM-Perl module,
471 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
474 http://indexdata.com/zebra/
478 Mike Taylor, E<lt>mike@indexdata.comE<gt>
480 =head1 COPYRIGHT AND LICENSE
482 Copyright (C) 2006 by Index Data ApS.
484 This library is free software; you can redistribute it and/or modify
485 it under the same terms as Perl itself, either Perl version 5.8.7 or,
486 at your option, any later version of Perl 5 you may have available.