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