]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/support-scripts/marc_stream_importer.pl
Adding new methodolgoy, robust docs, new options
[working/Evergreen.git] / Open-ILS / src / support-scripts / marc_stream_importer.pl
1 #!/usr/bin/perl
2 # Copyright (C) 2008 Equinox Software, Inc.
3 # Author: Bill Erickson <erickson@esilibrary.com>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15
16 use strict; use warnings;
17 use Net::Server::PreFork;
18 use base qw/Net::Server::PreFork/;
19 use MARC::Record;
20 use MARC::Batch;
21 use MARC::File::XML;
22 use MARC::File::USMARC;
23
24 use Data::Dumper;
25 use File::Basename qw/fileparse/;
26 use Getopt::Long qw(:DEFAULT GetOptionsFromArray);
27 use Pod::Usage;
28
29 use OpenSRF::Utils::Logger qw/$logger/;
30 use OpenILS::Utils::Cronscript;
31 require 'oils_header.pl';
32 use vars qw/$apputils/;
33
34 my $debug = 0;
35
36 my %defaults = (
37     'buffsize=i'    => 4096,
38     'merge=i'       => 0,
39     'source=i'      => 1,
40 #    'osrf-config=s' => '/openils/conf/opensrf_core.xml',
41     'user=s'        => 'admin',
42     'password=s'    => '',
43     'tempdir=s'     => '',
44     'nolockfile'    => 1,
45     'queue'         => 1,
46     'noqueue'       => 0,
47     'wait=i'        => 5,
48 );
49
50 $OpenILS::Utils::Cronscript::debug=1 if $debug;
51 $Getopt::Long::debug=1 if $debug > 1;
52 my $o = OpenILS::Utils::Cronscript->new(\%defaults);
53
54 my @script_args = ();
55
56 if (grep {$_ eq '--'} @ARGV) {
57     print "Splitting options into groups\n" if $debug;
58     while (@ARGV) {
59         $_ = shift @ARGV;
60         $_ eq '--' and last;    # stop at the first --
61         push @script_args, $_;
62     }
63 } else {
64     @script_args = @ARGV;
65 }
66
67 print "Calling MyGetOptions ",
68     (@script_args ? "with options: " . join(' ', @script_args) : 'without options from command line'),
69     "\n" if $debug;
70
71 my $real_opts = $o->MyGetOptions(\@script_args);
72 $o->bootstrap;
73 # GetOptionsFromArray(\@script_args, \%defaults, %defaults); # similar to
74
75 my $bufsize       = $real_opts->{buffsize};
76 my $bib_source    = $real_opts->{source};
77 my $osrf_config   = $real_opts->{'osrf-config'};
78 my $oils_username = $real_opts->{user};
79 my $oils_password = $real_opts->{password};
80 my $help          = $real_opts->{help};
81 my $merge_profile = $real_opts->{merge_profile};
82 my $queue_id      = $real_opts->{queue};
83 my $tempdir       = $real_opts->{tempdir} || tempdir();
84    $debug        += $real_opts->{debug};
85
86 foreach (keys %$real_opts) {
87     print("real_opt->{$_} = ", $real_opts->{$_}, "\n") if $real_opts->{debug} or $debug;
88 }
89 my $wait_time     = $real_opts->{wait};
90 my $authtoken     = '';
91
92 # DEFAULTS for Net::Server
93 my $filename   = fileparse($0, '.pl');
94 my $conf_file  = (-r "$filename.conf") ? "$filename.conf" : undef;
95 # $conf_file is the Net::Server config for THIS script (not EG), if it exists and is readable
96
97
98 # FEEDBACK
99
100 pod2usage(1) if $help;
101 unless ($oils_password) {
102     print STDERR "\nERROR: password option required for session login\n\n";
103     # pod2usage(1);
104 }
105
106 print Dumper($o) if $debug;
107
108 if ($debug) {
109     foreach my $ref (qw/bufsize bib_source osrf_config oils_username oils_password help conf_file debug/) {
110         no strict 'refs';
111         printf "%16s => %s\n", $ref, (eval("\$$ref") || '');
112     }
113 }
114
115 print warning();
116 print Dumper($real_opts);
117
118 # SUBS
119
120 sub tempdir {
121     return $apputils->simplereq( qw# opensrf.settings opensrf.settings.xpath.get
122         /opensrf/default/apps/open-ils.vandelay/app_settings/databases/importer # ) || '/tmp/foobar/';
123 }
124
125 sub warning {
126     return <<WARNING;
127
128 WARNING:  This script provides no security layer.  Any client that has 
129 access to the server+port can inject MARC records into the system.  
130
131 WARNING
132 }
133
134 sub xml_import {
135     return $apputils->simplereq(
136         'open-ils.cat', 
137         'open-ils.cat.biblio.record.xml.import',
138         @_
139     );
140 }
141
142 sub old_process_batch_data {
143     my $data = shift or $logger->error("process_batch_data called without any data");
144     $data or return;
145
146     my $handle;
147     open $handle, '<', \$data; 
148     my $batch = MARC::Batch->new('USMARC', $handle);
149     $batch->strict_off;
150
151     my $index = 0;
152     while (1) {
153         my $rec;
154         $index++;
155
156         eval { $rec = $batch->next; };
157
158         if ($@) {
159             $logger->error("Failed parsing MARC record $index");
160             next;
161         }
162         last unless $rec;   # The only way out
163
164         my $resp = xml_import($authtoken, $rec->as_xml_record, $bib_source);
165
166         # has the session timed out?
167         if (oils_event_equals($resp, 'NO_SESSION')) {
168             new_auth_token();
169             $resp = xml_import($authtoken, $rec->as_xml_record, $bib_source);   # try again w/ new token
170         }
171         oils_event_die($resp);
172     }
173     return $index;
174 }
175
176 sub process_spool {     # (authtoken, queue_id, filename, bib_source)
177     $apputils->simplereq('open-ils.vandelay', 'open-ils.vandelay.bib.process_spool', $authtoken, undef,
178                          $queue_id, 'import', $filename, $bib_source );
179 }
180 sub bib_queue_import {
181     my $extra = {auto_overlay_exact => 1};
182     $extra->{merge_profile} = $merge_profile if $merge_profile;
183     $apputils->simplereq('open-ils.vandelay', 'open-ils.vandelay.bib_queue.import', $authtoken,
184                          $queue_id, $extra );
185 }
186
187 sub process_batch_data {
188     my $data = shift or $logger->error("process_batch_data called without any data");
189     $data or return;
190
191     my $resp = process_spool();
192
193     if (oils_event_equals($resp, 'NO_SESSION')) {  # has the session timed out?
194         new_auth_token();
195         $resp = process_spool();                # try again w/ new token
196     }
197
198     $resp = bib_queue_import();
199
200     if (oils_event_equals($resp, 'NO_SESSION')) {  # has the session timed out?
201         new_auth_token();
202         $resp = bib_queue_import();                # try again w/ new token
203     }
204     oils_event_die($resp);
205 }
206
207 sub process_request {   # The core Net::Server method
208     my $self = shift;
209     my $socket = $self->{server}->{client};
210     my $data = '';
211     my $buf;
212
213     # Reading <STDIN> blocks until the client is closed.  Instead of waiting 
214     # for that, give each inbound record $wait_time seconds to fully arrive
215     # and pull the data directly from the socket
216     eval {
217         local $SIG{ALRM} = sub { die "alarm\n" }; 
218         do {
219             alarm $wait_time;
220             last unless $socket->sysread($buf, $bufsize);
221             $data .= $buf;
222         } while(1);
223         alarm 0;
224     };
225     if ($real_opts->{noqueue}) {
226         old_process_batch_data($data);
227     } else {
228         process_batch_data($data);
229     }
230 }
231
232
233 # the authtoken will timeout after the configured inactivity period.
234 # When that happens, get a new one.
235 sub new_auth_token {
236     $authtoken = oils_login($oils_username, $oils_password, 'staff') 
237         or die "Unable to login to Evergreen as user $oils_username";
238     return $authtoken;
239 }
240
241 ##### MAIN ######
242
243 osrf_connect($osrf_config);
244 new_auth_token();
245 print "Calling Net::Server run ", (@ARGV ? "with command-line options: " . join(' ', @ARGV) : ''), "\n";
246 __PACKAGE__->run(conf_file => $conf_file);
247
248 __END__
249
250 =head1 NAME
251
252 marc_stream_importer.pl - Import MARC records via bare socket connection.
253
254 =head1 SYNOPSIS
255
256 ./marc_stream_importer.pl [common opts ...] [script opts ...] -- [Net::Server opts ...] &
257
258 This script uses the EG common options from B<Cronscript>.  See --help output for those.
259
260 Run C<perldoc marc_stream_importer.pl> for full documentation.
261
262 Note the extra C<--> to separate options for the script wrapper from options for the
263 underlying L<Net::Server> options.  
264
265 Note: this script has to be run in the same directory as B<oils_header.pl>.
266
267 Typical execution will include a trailing C<&> to run in the background.
268
269 =head1 DESCRIPTION
270
271 This script is a L<Net::Server::PreFork> instance for shoving records into Evergreen from a remote system.
272
273 =head1 OPTIONS
274
275 The only required option is --password
276
277  --password =<eg_password>
278  --user     =<eg_username>   default: admin
279  --source   =<bib_source>    default: 1         Integer
280  --merge    =<i>             default: 0
281  --tempdir  =</temp/dir/>    default: from L<opensrf.conf> <open-ils.vandelay/app_settings/databases/importer>
282  --source   =<i>             default: 1
283
284 =head2 Old style: --noqueue and associated options
285
286 To bypass vandelay queue processing and push directly into the database (as the old style)
287
288  --noqueue         default: OFF
289  --buffsize =<i>   default: 4096    Buffer size.  Only used by --noqueue
290  --wait     =<i>   default: 5       Seconds to read socket before processing.  Only used by --noqueue
291
292 =head2 Net::Server Options
293
294 By default, the script will use the Net::Server configuration file B<marc_stream_importer.conf>.  You can 
295 override this by passing a filepath with the --conf_file option.
296
297 Other Net::Server options include: --port=<port> --min_servers=<X> --max_servers=<Y> and --log_file=[path/to/file]
298
299 See L<Net::Server> for a complete list.
300
301 =head2 Configuration
302
303 =head3 OCLC Connexion
304
305 To use this script with OCLC Connexion, configure the client as follows:
306
307 Under Tools -> Options -> Export (tab)
308    Create -> Choose Connection -> OK -> Leave translation at "None" 
309        -> Create -> Create -> choose TCP/IP (internet) 
310        -> Enter hostname and Port, leave 'Use Telnet Protocol' checked 
311        -> Create/OK your way out of the dialogs
312    Record Characteristics (button) -> Choose 'UTF-8 Unicode' for the Character Set
313    
314
315 OCLC and Connexion are trademark/service marks of OCLC Online Computer Library Center, Inc.
316
317 =head1 CAVEATS
318
319 WARNING: This script provides no inherent security layer.  Any client that has 
320 access to the server+port can inject MARC records into the system.  
321 Use the available options (like allow/deny) in the Net::Server config file 
322 or via the command line to restrict access as necessary.
323
324 =head1 EXAMPLES
325
326 ./marc_stream_importer.pl  \
327     admin open-ils connexion --port 5555 --min_servers 2 \
328     --max_servers=20 --log_file=/openils/var/log/marc_net_importer.log &
329
330 =head1 SEE ALSO
331
332 L<Net::Server::PreFork>, L<marc_stream_importer.conf>
333
334 =head1 AUTHORS
335
336     Bill Erickson <erickson@esilibrary.com>
337     Joe Atzberger <jatzberger@esilibrary.com>
338
339 =cut