d5672e810ea19446283a50d8f48e5198bebeb6ed
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1 # $Id: IRSpy.pm,v 1.17 2006-09-22 15:02:24 mike Exp $
2
3 package ZOOM::IRSpy;
4
5 use 5.008;
6 use strict;
7 use warnings;
8 use ZOOM::IRSpy::Record;
9 use ZOOM::Pod;
10
11 our @ISA = qw();
12 our $VERSION = '0.02';
13
14 =head1 NAME
15
16 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
17
18 =head1 SYNOPSIS
19
20  use ZOOM::IRSpy;
21  $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
22  print $spy->report_status();
23
24 =head1 DESCRIPTION
25
26 This module exists to implement the IRspy program, which discovers,
27 analyses and monitors IR servers implementing the Z39.50 and SRU/W
28 protocols.  It is a successor to the ZSpy program.
29
30 =cut
31
32 BEGIN {
33     ZOOM::Log::mask_str("irspy");
34     ZOOM::Log::mask_str("irspy_test");
35     ZOOM::Log::mask_str("irspy_debug");
36 }
37
38 sub new {
39     my $class = shift();
40     my($dbname, $user, $password) = @_;
41
42     my @options;
43     push @options, (user => $user, password => $password)
44         if defined $user;
45
46     my $conn = new ZOOM::Connection($dbname, 0, @options)
47         or die "$0: can't connection to IRSpy database 'dbname'";
48
49     my $this = bless {
50         conn => $conn,
51         allrecords => 1,        # unless overridden by targets()
52         query => undef,         # filled in later
53         targets => undef,       # filled in later
54         target2record => undef, # filled in later
55         pod => undef,           # filled in later
56         tests => [],            # stack of tests currently being executed
57     }, $class;
58     $this->log("irspy", "starting up with database '$dbname'");
59
60     return $this;
61 }
62
63
64 sub log {
65     my $this = shift();
66     ZOOM::Log::log(@_);
67 }
68
69
70 # Explicitly nominate a set of targets to check, overriding the
71 # default which is to re-check everything in the database.  Each
72 # target already in the database results in the existing record being
73 # updated; each new target causes a new record to be added.
74 #
75 sub targets {
76     my $this = shift();
77     my(@targets) = @_;
78
79     $this->log("irspy", "setting explicit list of targets ",
80                join(", ", map { "'$_'" } @targets));
81     $this->{allrecords} = 0;
82     my @qlist;
83     foreach my $target (@targets) {
84         my($host, $port, $db, $newtarget) = _parse_target_string($target);
85         if ($newtarget ne $target) {
86             $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
87             $target = $newtarget; # This written through the ref
88         }
89         push @qlist,
90             (qq[(host = "$host" and port = "$port" and path="$db")]);
91     }
92
93     $this->{targets} = \@targets;
94     $this->{query} = join(" or ", @qlist);
95 }
96
97
98 # Also used by ZOOM::IRSpy::Record
99 sub _parse_target_string {
100     my($target) = @_;
101
102     my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
103     if (!defined $host) {
104         $port = 210;
105         ($host, $db) = ($target =~ /(.*?)\/(.*)/);
106         $target = "$host:$port/$db";
107     }
108     die "$0: invalid target string '$target'"
109         if !defined $host;
110
111     return ($host, $port, $db, $target);
112 }
113
114
115 # There are two cases.
116 #
117 # 1. A specific set of targets is nominated on the command line.
118 #       - Records must be fetched for those targets that are in the DB
119 #       - New, empty records must be made for those that are not.
120 #       - Updated records written to the DB may or may not be new.
121 #
122 # 2. All records in the database are to be checked.
123 #       - Records must be fetched for all targets in the DB
124 #       - Updated records written to the DB may not be new.
125 #
126 # That's all -- what could be simpler?
127 #
128 sub initialise {
129     my $this = shift();
130
131     my %target2record;
132     if ($this->{allrecords}) {
133         # We need to check on every target in the database, which
134         # means we need to do a "find all".  According to the BIB-1
135         # semantics document at
136         #       http://www.loc.gov/z3950/agency/bib1.html
137         # the query
138         #       @attr 2=103 @attr 1=1035 x
139         # should find all records, but it seems that Zebra doesn't
140         # support this.  Furthermore, when using the "alvis" filter
141         # (as we do for IRSpy) it doesn't support the use of any BIB-1
142         # access point -- not even 1035 "everywhere" -- so instead we
143         # hack together a search that we know will find all records.
144         $this->{query} = "port=?*";
145     } else {
146         # Prepopulate the target map with nulls so that after we fill
147         # in what we can from the database query, we know which target
148         # IDs we need new records for.
149         foreach my $target (@{ $this->{targets} }) {
150             $target2record{lc($target)} = undef;
151         }
152     }
153
154     my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
155     #print "size='", $rs->size(), "'\n";
156     foreach my $i (1 .. $rs->size()) {
157         my $target = _render_record($rs, $i-1, "id");
158         my $zeerex = _render_record($rs, $i-1, "zeerex");
159         #print STDERR "making '$target' record with '$zeerex'\n";
160         $target2record{lc($target)} =
161             new ZOOM::IRSpy::Record($target, $zeerex);
162         push @{ $this->{targets} }, $target
163             if $this->{allrecords};
164     }
165
166     foreach my $target (keys %target2record) {
167         my $record = $target2record{$target};
168         if (!defined $record) {
169             $this->log("irspy_debug", "made new record for '$target'");
170             #print STDERR "making '$target' record without zeerex\n";
171             $target2record{$target} = new ZOOM::IRSpy::Record($target);
172         } else {
173             $this->log("irspy_debug", "using existing record for '$target'");
174         }
175     }
176
177     $this->{target2record} = \%target2record;
178     $this->{pod} = new ZOOM::Pod(@{ $this->{targets} });
179     delete $this->{targets};    # The information is now in the Pod.
180     delete $this->{query};      # Not needed at all
181 }
182
183
184 sub _render_record {
185     my($rs, $which, $elementSetName) = @_;
186
187     # There is a slight race condition here on the element-set name,
188     # but it shouldn't be a problem as this is (currently) only called
189     # from parts of the program that run single-threaded.
190     my $old = $rs->option(elementSetName => $elementSetName);
191     my $rec = $rs->record($which);
192     $rs->option(elementSetName => $old);
193
194     return $rec->render();
195 }
196
197
198 # Returns:
199 #       0 all tests successfully run
200 #       1 some tests skipped
201 #
202 sub check {
203     my $this = shift();
204
205     my $res = $this->_run_test("Main");
206     foreach my $target (sort keys %{ $this->{target2record} }) {
207         my $rec = $this->{target2record}->{$target};
208         # Write record back to database
209         my $p = $this->{conn}->package();
210         $p->option(action => "specialUpdate");
211         my $xml = $rec->{zeerex}->toString();
212         $p->option(record => $xml);
213         $p->send("update");
214         $p->destroy();
215
216         $p = $this->{conn}->package();
217         $p->send("commit");
218         $p->destroy();
219         if (0) {
220             $xml =~ s/&/&amp/g;
221             $xml =~ s/</&lt;/g;
222             $xml =~ s/>/&gt;/g;
223             print "Updated with xml=<br/>\n<pre>$xml</pre>\n";
224         }
225     }
226
227     return $res;
228 }
229
230
231 sub _run_test {
232     my $this = shift();
233     my($tname) = @_;
234
235     die("$0: test-hierarchy loop detected: " .
236         join(" -> ", @{ $this->{tests} }, $tname))
237         if grep { $_ eq $tname } @{ $this->{tests} };
238
239     eval {
240         my $slashSeperatedTname = $tname;
241         $slashSeperatedTname =~ s/::/\//g;
242         require "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
243     }; if ($@) {
244         $this->log("warn", "can't load test '$tname': skipping",
245                    $@ =~ /^Can.t locate/ ? () : " ($@)");
246         return 1;
247     }
248
249     $this->log("irspy", "running test '$tname'");
250     push @{ $this->{tests} }, $tname;
251     my $test = "ZOOM::IRSpy::Test::$tname"->new($this);
252     my $res =$test->run();
253     pop @{ $this->{tests} };
254     return $res;
255 }
256
257
258 # Access methods for the use of Test modules
259 sub pod {
260     my $this = shift();
261     return $this->{pod};
262 }
263
264 sub record {
265     my $this = shift();
266     my($target) = @_;
267
268     if (ref($target) && $target->isa("ZOOM::Connection")) {
269         # Can be called with a Connection instead of a target-name
270         my $conn = $target;
271         $target = $conn->option("host");
272     }
273
274     return $this->{target2record}->{lc($target)};
275 }
276
277
278 # Utility method, really nothing to do with IRSpy
279 sub isodate {
280     my $this = shift();
281     my($time) = @_;
282
283     my($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
284     return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
285                    $year+1900, $mon+1, $mday, $hour, $min, $sec);
286 }
287
288
289 =head1 SEE ALSO
290
291 ZOOM::IRSpy::Record
292
293 The ZOOM-Perl module,
294 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
295
296 The Zebra Database,
297 http://indexdata.com/zebra/
298
299 =head1 AUTHOR
300
301 Mike Taylor, E<lt>mike@indexdata.comE<gt>
302
303 =head1 COPYRIGHT AND LICENSE
304
305 Copyright (C) 2006 by Index Data ApS.
306
307 This library is free software; you can redistribute it and/or modify
308 it under the same terms as Perl itself, either Perl version 5.8.7 or,
309 at your option, any later version of Perl 5 you may have available.
310
311 =cut
312
313 1;