]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/support-scripts/marc_stream_importer.pl
return # of imported and failed records to the caller
[working/Evergreen.git] / Open-ILS / src / support-scripts / marc_stream_importer.pl
1 #!/usr/bin/perl
2 # Copyright (C) 2008-2010 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 File::Temp;
27 use Getopt::Long qw(:DEFAULT GetOptionsFromArray);
28 use Pod::Usage;
29
30 use OpenSRF::Utils::Logger qw/$logger/;
31 use OpenSRF::AppSession;
32 use OpenSRF::EX qw/:try/;
33 use OpenILS::Utils::Cronscript;
34 require 'oils_header.pl';
35 use vars qw/$apputils/;
36
37 my $vl_ses;
38
39 my $debug = 0;
40
41 my %defaults = (
42     'buffsize=i'    => 4096,
43     'merge-profile=i' => 0,
44     'source=i'      => 1,
45 #    'osrf-config=s' => '/openils/conf/opensrf_core.xml',
46     'user=s'        => 'admin',
47     'password=s'    => '',
48     'tempdir=s'     => '',
49     'nolockfile'    => 1,
50     'queue=i'       => 1,
51     'noqueue'       => 0,
52     'wait=i'        => 5,
53     'import-by-queue' => 0
54 );
55
56 $OpenILS::Utils::Cronscript::debug=1 if $debug;
57 $Getopt::Long::debug=1 if $debug > 1;
58 my $o = OpenILS::Utils::Cronscript->new(\%defaults);
59
60 my @script_args = ();
61
62 if (grep {$_ eq '--'} @ARGV) {
63     print "Splitting options into groups\n" if $debug;
64     while (@ARGV) {
65         $_ = shift @ARGV;
66         $_ eq '--' and last;    # stop at the first --
67         push @script_args, $_;
68     }
69 } else {
70     @script_args = @ARGV;
71     @ARGV = ();
72 }
73
74 print "Calling MyGetOptions ",
75     (@script_args ? "with options: " . join(' ', @script_args) : 'without options from command line'),
76     "\n" if $debug;
77
78 my $real_opts = $o->MyGetOptions(\@script_args);
79 $o->bootstrap;
80 # GetOptionsFromArray(\@script_args, \%defaults, %defaults); # similar to
81
82 $real_opts->{tempdir} ||= tempdir_setting();    # This doesn't go in defaults because it reads config, must come after bootstrap
83
84 my $bufsize       = $real_opts->{buffsize};
85 my $bib_source    = $real_opts->{source};
86 my $osrf_config   = $real_opts->{'osrf-config'};
87 my $oils_username = $real_opts->{user};
88 my $oils_password = $real_opts->{password};
89 my $help          = $real_opts->{help};
90 my $merge_profile = $real_opts->{'merge-profile'};
91 my $queue_id      = $real_opts->{queue};
92 my $tempdir       = $real_opts->{tempdir};
93 my $import_by_queue  = $real_opts->{'import-by-queue'};
94    $debug        += $real_opts->{debug};
95
96 foreach (keys %$real_opts) {
97     print("real_opt->{$_} = ", $real_opts->{$_}, "\n") if $real_opts->{debug} or $debug;
98 }
99 my $wait_time     = $real_opts->{wait};
100 my $authtoken     = '';
101
102 # DEFAULTS for Net::Server
103 my $filename   = fileparse($0, '.pl');
104 my $conf_file  = (-r "$filename.conf") ? "$filename.conf" : undef;
105 # $conf_file is the Net::Server config for THIS script (not EG), if it exists and is readable
106
107
108 # FEEDBACK
109
110 pod2usage(1) if $help;
111 unless ($oils_password) {
112     print STDERR "\nERROR: password option required for session login\n\n";
113     # pod2usage(1);
114 }
115
116 print Dumper($o) if $debug;
117
118 if ($debug) {
119     foreach my $ref (qw/bufsize bib_source osrf_config oils_username oils_password help conf_file debug/) {
120         no strict 'refs';
121         printf "%16s => %s\n", $ref, (eval("\$$ref") || '');
122     }
123 }
124
125 print warning();
126 print Dumper($real_opts);
127
128 # SUBS
129
130 sub tempdir_setting {
131     my $ret = $apputils->simplereq( qw# opensrf.settings opensrf.settings.xpath.get
132         /opensrf/default/apps/open-ils.vandelay/app_settings/databases/importer # );
133     return $ret->[0] || '/tmp';
134 }
135
136 sub warning {
137     return <<WARNING;
138
139 WARNING:  This script provides no security layer.  Any client that has 
140 access to the server+port can inject MARC records into the system.  
141
142 WARNING
143 }
144
145 sub xml_import {
146     return $apputils->simplereq(
147         'open-ils.cat', 
148         'open-ils.cat.biblio.record.xml.import',
149         @_
150     );
151 }
152
153 sub old_process_batch_data {
154     my $data = shift or $logger->error("process_batch_data called without any data");
155     $data or return;
156
157     my $handle;
158     open $handle, '<', \$data; 
159     my $batch = MARC::Batch->new('USMARC', $handle);
160     $batch->strict_off;
161
162     my $index = 0;
163     my $imported = 0;
164     my $failed = 0;
165
166     while (1) {
167         my $rec;
168         $index++;
169
170         eval { $rec = $batch->next; };
171
172         if ($@) {
173             $logger->error("Failed parsing MARC record $index");
174             $failed++;
175             next;
176         }
177         last unless $rec;   # The only way out
178
179         my $resp = xml_import($authtoken, $rec->as_xml_record, $bib_source);
180
181         # has the session timed out?
182         if (oils_event_equals($resp, 'NO_SESSION')) {
183             new_auth_token();
184             $resp = xml_import($authtoken, $rec->as_xml_record, $bib_source);   # try again w/ new token
185         }
186         oils_event_die($resp);
187         $imported++;
188     }
189
190     return ($imported, $failed);
191 }
192
193 sub process_spool { # filename
194
195     my $marcfile = shift;
196     my @rec_ids;
197
198     if($import_by_queue) {
199
200         # don't collect the record IDs, just spool the queue
201
202         $apputils->simplereq(
203             'open-ils.vandelay', 
204             'open-ils.vandelay.bib.process_spool', 
205             $authtoken, 
206             undef, 
207             $queue_id, 
208             'import', 
209             $marcfile,
210             $bib_source 
211         );
212
213     } else {
214
215         # collect the newly queued record IDs for processing
216
217         my $req = $vl_ses->request(
218             'open-ils.vandelay.bib.process_spool.stream_results',
219             $authtoken, 
220             undef, # cache key not needed
221             $queue_id, 
222             'import', 
223             $marcfile, 
224             $bib_source 
225         );
226     
227         while(my $resp = $req->recv) {
228
229             if($req->failed) {
230                 $logger->error("Error spooling MARC data: $resp");
231
232             } elsif($resp->content) {
233                 push(@rec_ids, $resp->content);
234             }
235         }
236     }
237
238     return \@rec_ids;
239 }
240
241 sub bib_queue_import {
242     my $rec_ids = shift;
243     my $extra = {auto_overlay_exact => 1};
244     $extra->{merge_profile} = $merge_profile if $merge_profile;
245
246     my $req;
247     my @cleanup_recs;
248
249     if($import_by_queue) {
250         # import by queue
251
252         $req = $vl_ses->request(
253             'open-ils.vandelay.bib_queue.import', 
254             $authtoken, 
255             $queue_id, 
256             $extra 
257         );
258
259     } else {
260         # import explicit record IDs
261
262         $req = $vl_ses->request(
263             'open-ils.vandelay.bib_record.list.import', 
264             $authtoken, 
265             $rec_ids, 
266             $extra 
267         );
268     }
269
270     # collect the successfully imported vandelay records
271     my $failed = 0;
272     while(my $resp = $req->recv) {
273          if($req->failed) {
274             $logger->error("Error importing MARC data: $resp");
275
276         } elsif(my $data = $resp->content) {
277
278             if($data->{err_event}) {
279
280                 $logger->error(Dumper($data->{err_event}));
281                 $failed++;
282
283             } else {
284                 push(@cleanup_recs, $data->{imported}) if $data->{imported};
285             }
286         }
287     }
288
289     # clean up the successfully imported vandelay records to prevent queue bloat
290     my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
291     $pcrud->connect;
292     $pcrud->request('open-ils.pcrud.transaction.begin', $authtoken)->recv;
293     my $err;
294
295     foreach (@cleanup_recs) {
296
297         try { 
298
299             $pcrud->request('open-ils.pcrud.delete.vqbr', $authtoken, $_)->recv;
300
301         } catch Error with {
302             $err = shift;
303             $logger->error("Error deleteing queued bib record $_: $err");
304         };
305     }
306
307     $pcrud->request('open-ils.pcrud.transaction.commit', $authtoken)->recv unless $err;
308     $pcrud->disconnect;
309
310     $logger->info("imported queued vandelay records: @cleanup_recs");
311     return (scalar(@cleanup_recs), $failed);
312 }
313
314 sub process_batch_data {
315     my $data = shift or $logger->error("process_batch_data called without any data");
316     $data or return;
317
318     $vl_ses = OpenSRF::AppSession->create('open-ils.vandelay');
319
320     my ($handle, $tempfile) = File::Temp->tempfile("$0_XXXX", DIR => $tempdir) or die "Cannot write tempfile in $tempdir";
321     print $handle $data;
322     close $handle;
323        
324     $logger->info("Calling process_spool on tempfile $tempfile (queue: $queue_id; source: $bib_source)");
325     my $rec_ids = process_spool($tempfile);
326
327     if (oils_event_equals($rec_ids, 'NO_SESSION')) {  # has the session timed out?
328         new_auth_token();
329         $rec_ids = process_spool($tempfile);                # try again w/ new token
330     }
331
332     my ($imported, $failed) = bib_queue_import($rec_ids);
333
334     if (oils_event_equals($imported, 'NO_SESSION')) {  # has the session timed out?
335         new_auth_token();
336         ($imported, $failed) = bib_queue_import();                # try again w/ new token
337     }
338
339     oils_event_die($imported);
340
341     return ($imported, $failed);
342 }
343
344 sub process_request {   # The core Net::Server method
345     my $self = shift;
346     my $client = $self->{server}->{client};
347
348     $logger->info("stream parser received contact from $client");
349
350     my $data;
351     eval {
352         local $SIG{ALRM} = sub { die "alarm\n" };
353         alarm $wait_time; # prevent accidental tie ups of backend processes
354         local $/ = "\x1D"; # MARC record separator
355         $data = <STDIN>;
356         alarm 0;
357     };
358
359     if($@) {
360         $logger->error("reading from STDIN failed or timed out: $@");
361         return;
362     } 
363
364     $logger->info("stream parser read " . length($data) . " bytes");
365
366     my ($imported, $failed) = (0, 0);
367
368     if ($real_opts->{noqueue}) {
369         ($imported, $failed) = old_process_batch_data($data);
370     } else {
371         ($imported, $failed) = process_batch_data($data);
372     }
373
374     my $profile = (!$merge_profile) ? '' :
375         $apputils->simplereq(
376             'open-ils.pcrud', 
377             'open-ils.pcrud.retrieve.vmp', 
378             $authtoken, 
379             $merge_profile)->name;
380
381     my $msg = '';
382     $msg .= "Successfully imported $imported records using merge profile '$profile'\n" if $imported;
383     $msg .= "Faield to import $failed records\n" if $failed;
384     print $client $msg;
385 }
386
387
388 # the authtoken will timeout after the configured inactivity period.
389 # When that happens, get a new one.
390 sub new_auth_token {
391     $authtoken = oils_login($oils_username, $oils_password, 'staff') 
392         or die "Unable to login to Evergreen as user $oils_username";
393     return $authtoken;
394 }
395
396 ##### MAIN ######
397
398 osrf_connect($osrf_config);
399 new_auth_token();
400 print "Calling Net::Server run ", (@ARGV ? "with command-line options: " . join(' ', @ARGV) : ''), "\n";
401 __PACKAGE__->run(conf_file => $conf_file);
402
403 __END__
404
405 =head1 NAME
406
407 marc_stream_importer.pl - Import MARC records via bare socket connection.
408
409 =head1 SYNOPSIS
410
411 ./marc_stream_importer.pl [common opts ...] [script opts ...] -- [Net::Server opts ...] &
412
413 This script uses the EG common options from B<Cronscript>.  See --help output for those.
414
415 Run C<perldoc marc_stream_importer.pl> for full documentation.
416
417 Note the extra C<--> to separate options for the script wrapper from options for the
418 underlying L<Net::Server> options.  
419
420 Note: this script has to be run in the same directory as B<oils_header.pl>.
421
422 Typical execution will include a trailing C<&> to run in the background.
423
424 =head1 DESCRIPTION
425
426 This script is a L<Net::Server::PreFork> instance for shoving records into Evergreen from a remote system.
427
428 =head1 OPTIONS
429
430 The only required option is --password
431
432  --password         =<eg_password>
433  --user             =<eg_username>  default: admin
434  --source           =<bib_source>   default: 1         Integer
435  --merge-profile    =<i>            default: 0
436  --tempdir          =</temp/dir/>   default: from L<opensrf.conf> <open-ils.vandelay/app_settings/databases/importer>
437  --source           =<i>            default: 1
438  --import-by-queue  =<i>            default: 0
439
440
441 =head2 Old style: --noqueue and associated options
442
443 To bypass vandelay queue processing and push directly into the database (as the old style)
444
445  --noqueue         default: OFF
446  --buffsize =<i>   default: 4096    Buffer size.  Only used by --noqueue
447  --wait     =<i>   default: 5       Seconds to read socket before processing.  Only used by --noqueue
448
449 =head2 Net::Server Options
450
451 By default, the script will use the Net::Server configuration file B<marc_stream_importer.conf>.  You can 
452 override this by passing a filepath with the --conf_file option.
453
454 Other Net::Server options include: --port=<port> --min_servers=<X> --max_servers=<Y> and --log_file=[path/to/file]
455
456 See L<Net::Server> for a complete list.
457
458 =head2 Configuration
459
460 =head3 OCLC Connexion
461
462 To use this script with OCLC Connexion, configure the client as follows:
463
464 Under Tools -> Options -> Export (tab)
465    Create -> Choose Connection -> OK -> Leave translation at "None" 
466        -> Create -> Create -> choose TCP/IP (internet) 
467        -> Enter hostname and Port, leave 'Use Telnet Protocol' checked 
468        -> Create/OK your way out of the dialogs
469    Record Characteristics (button) -> Choose 'UTF-8 Unicode' for the Character Set
470    
471
472 OCLC and Connexion are trademark/service marks of OCLC Online Computer Library Center, Inc.
473
474 =head1 CAVEATS
475
476 WARNING: This script provides no inherent security layer.  Any client that has 
477 access to the server+port can inject MARC records into the system.  
478 Use the available options (like allow/deny) in the Net::Server config file 
479 or via the command line to restrict access as necessary.
480
481 =head1 EXAMPLES
482
483 ./marc_stream_importer.pl  \
484     admin open-ils connexion --port 5555 --min_servers 2 \
485     --max_servers=20 --log_file=/openils/var/log/marc_net_importer.log &
486
487 =head1 SEE ALSO
488
489 L<Net::Server::PreFork>, L<marc_stream_importer.conf>
490
491 =head1 AUTHORS
492
493     Bill Erickson <erickson@esilibrary.com>
494     Joe Atzberger <jatzberger@esilibrary.com>
495
496 =cut