Added isodate() utility method (was in Test/Ping.pm)
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1 # $Id: IRSpy.pm,v 1.11 2006-07-24 17:00:36 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     }
157
158     foreach my $target (keys %target2record) {
159         my $record = $target2record{$target};
160         if (!defined $record) {
161             $this->log("irspy_debug", "made new record for '$target'");
162             $target2record{$target} = new ZOOM::IRSpy::Record($target);
163         } else {
164             $this->log("irspy_debug", "using existing record for '$target'");
165         }
166     }
167
168     $this->{target2record} = \%target2record;
169     $this->{pod} = new ZOOM::Pod(@{ $this->{targets} });
170     delete $this->{targets};    # The information is now in the Pod.
171     delete $this->{query};      # Not needed at all
172 }
173
174
175 sub _render_record {
176     my($rs, $which, $elementSetName) = @_;
177
178     # There is a slight race condition here on the element-set name,
179     # but it shouldn't be a problem as this is (currently) only called
180     # from parts of the program that run single-threaded.
181     my $old = $rs->option(elementSetName => $elementSetName);
182     my $rec = $rs->record($which);
183     $rs->option(elementSetName => $old);
184
185     return $rec->render();
186 }
187
188
189 # Returns:
190 #       0 all tests successfully run
191 #       1 some tests skipped
192 #
193 sub check {
194     my $this = shift();
195
196     my $res = $this->_run_test("Main");
197     foreach my $target (sort keys %{ $this->{target2record} }) {
198         my $rec = $this->{target2record}->{$target};
199         print STDERR "$target: zeerex='", $rec->{zeerex}, "' = \n",
200             $rec->{zeerex}->toString(), "\n";
201         ### Write record back to database, if modified.
202     }
203     return $res;
204
205 }
206
207
208 sub _run_test {
209     my $this = shift();
210     my($tname) = @_;
211
212     die("$0: test-hierarchy loop detected: " .
213         join(" -> ", @{ $this->{tests} }, $tname))
214         if grep { $_ eq $tname } @{ $this->{tests} };
215
216     eval {
217         my $slashSeperatedTname = $tname;
218         $slashSeperatedTname =~ s/::/\//g;
219         require "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
220     }; if ($@) {
221         $this->log("warn", "can't load test '$tname': skipping",
222                    $@ =~ /^Can.t locate/ ? () : " ($@)");
223         return 1;
224     }
225
226     $this->log("irspy", "running test '$tname'");
227     push @{ $this->{tests} }, $tname;
228     my $test = "ZOOM::IRSpy::Test::$tname"->new($this);
229     my $res =$test->run();
230     pop @{ $this->{tests} };
231     return $res;
232 }
233
234
235 # Access methods for the use of Test modules
236 sub pod {
237     my $this = shift();
238     return $this->{pod};
239 }
240
241 sub record {
242     my $this = shift();
243     my($target) = @_;
244
245     if (ref($target) && $target->isa("ZOOM::Connection")) {
246         # Can be called with a Connection instead of a target-name
247         my $conn = $target;
248         $target = $conn->option("host");
249     }
250
251     return $this->{target2record}->{lc($target)};
252 }
253
254
255 # Utility method, really nothing to do with IRSpy
256 sub isodate {
257     my $this = shift();
258     my($time) = @_;
259
260     my($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
261     return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
262                    $year+1900, $mon+1, $mday, $hour, $min, $sec);
263 }
264
265
266 =head1 SEE ALSO
267
268 ZOOM::IRSpy::Record
269
270 The ZOOM-Perl module,
271 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
272
273 The Zebra Database,
274 http://indexdata.com/zebra/
275
276 =head1 AUTHOR
277
278 Mike Taylor, E<lt>mike@indexdata.comE<gt>
279
280 =head1 COPYRIGHT AND LICENSE
281
282 Copyright (C) 2006 by Index Data ApS.
283
284 This library is free software; you can redistribute it and/or modify
285 it under the same terms as Perl itself, either Perl version 5.8.7 or,
286 at your option, any later version of Perl 5 you may have available.
287
288 =cut
289
290 1;