-
Notifications
You must be signed in to change notification settings - Fork 54
/
solrsync
executable file
·489 lines (373 loc) · 11.6 KB
/
solrsync
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env perl
use Koha;
use C4::Context;
use C4::Items qw(GetMarcWithItems);
use C4::AuthoritiesMarc qw(GetAuthority);
use WebService::Solr;
use Koha::Solr::IndexStrategy::MARC;
use Koha::Solr::Document::MARC;
use Koha::Changelog::DBLog;
use File::Slurp;
use DateTime;
use DateTime::TimeZone;
use Try::Tiny;
use Getopt::Long qw(GetOptions);
use Pod::Usage;
use Log::Dispatch;
use Log::Dispatch::Screen;
use Carp;
use Parallel::ForkManager;
use Time::HiRes qw(gettimeofday);
use List::MoreUtils qw(natatime);
use POSIX qw();
my %dispatch = (
biblio => {
name => 'biblio',
acquire_all_ids => sub {
return C4::Context->dbh->selectcol_arrayref(
'SELECT biblionumber FROM biblio');
},
acquire_one => \&GetMarcWithItems,
rules_file => C4::Context->config('solr')->{biblio_rules},
prefix => 'bib',
rtype => 'biblio',
tspref => 'SolrBibUpdateTS',
},
auth => {
name => 'auth',
acquire_all_ids => sub {
return C4::Context->dbh->selectcol_arrayref(
'SELECT authid FROM auth_header');
},
acquire_one => \&GetAuthority,
rules_file => C4::Context->config('solr')->{auth_rules},
prefix => 'auth',
rtype => 'auth',
tspref => 'SolrAuthUpdateTS',
},
);
my @verbosities = qw(warn info);
my @queues;
my %opts = (
all => undef,
ids => undef,
timestamp => undef,
to_stdout => undef,
workers => 1,
batch_size => 100,
continuous => 0,
sleeptime => 30,
verbosity => 0,
help => undef,
);
GetOptions(
'bibs!' => sub { push @queues, 'biblio' },
'auths!' => sub { push @queues, 'auth' },
'a|all!' => \$opts{all},
'ids:s' => \$opts{ids},
's|since:s' => \$opts{timestamp},
'w|workers:i' => \$opts{workers},
'b|batch-size:i' => \$opts{batch_size},
'c|continuous!' => \$opts{continuous},
't|sleeptime:i' => \$opts{sleeptime},
'o|stdout!' => \$opts{to_stdout},
'v|verbose' => sub { $opts{verbosity}++ },
'h|help' => \$opts{help},
) or pod2usage(1);
pod2usage(0) if $opts{help};
croak '"continuous" mode is incompatible with "all" or "ids"'
if ( $opts{continuous} && ($opts{all} || $opts{ids}) );
croak 'only one of either "all" or "ids" may be specified'
if ( $opts{all} && $opts{ids} );
my $log = Log::Dispatch->new();
$log->add( Log::Dispatch::Screen->new(
min_level=>$verbosities[$opts{verbosity}] // 'debug',
newline=>1, stderr=>1));
my $ltz = DateTime::TimeZone->new(name => 'local');
while (1) {
$log->info('Starting new queue run at '. DateTime->now(time_zone => $ltz));
for ( @queues ) {
my $rtype = $dispatch{$_};
$log->info("Dispatching $rtype->{name}");
$rtype->{opts} = \%opts;
run_queue( $rtype );
$log->info("Finished $rtype->{name}");
}
last unless $opts{continuous};
$log->info('Sleeping until next run');
sleep $opts{sleeptime};
}
exit;
sub run_queue {
my $rtype = shift;
$SIG{HUP} = $SIG{TERM} = $SIG{INT} = $SIG{QUIT} = sub {
$log->warn('Caught signal. Exiting.');
my $todos = [ {stamp => C4::Context->preference( $rtype->{tspref} )} ];
update_timestamp( $rtype, $todos );
exit 1;
};
my $todos = get_todos($rtype);
update_timestamp($rtype, $todos);
$log->info('Processing '.@$todos.' changelog entries');
my $forker = Parallel::ForkManager->new($rtype->{opts}{workers});
my $todoitr = natatime(@$todos / $rtype->{opts}{workers}, @$todos);
while (my @todo_part = $todoitr->()) {
next if $forker->start;
$SIG{HUP} = $SIG{TERM} = $SIG{INT} = $SIG{QUIT} = undef;
process_list($rtype, \@todo_part);
$forker->finish;
}
$forker->wait_all_children;
$SIG{HUP} = $SIG{TERM} = $SIG{INT} = $SIG{QUIT} = undef;
return;
}
sub get_todos {
my ($rtype) = @_;
my $opts = $rtype->{opts};
if ( $opts->{all} || $opts->{ids} ) {
my @ids;
if ( $opts->{all} ) {
$log->info('Collecting all ids');
@ids = @{$rtype->{acquire_all_ids}->()};
}
else {
$log->info('Collecting select ids');
for ( split /,/, $opts->{ids} ) {
push @ids, /(\d+)-(\d+)/ ? $1..$2 : $_;
}
}
my $tstamp = DateTime->now(time_zone => $ltz)->ymd
. ' ' . DateTime->now(time_zone => $ltz)->hms;
return [
map { {id=>$_, rtype=>$rtype->{name},
action=>'update', stamp=>$tstamp }
} @ids
];
}
else {
my $tstamp = $opts->{timestamp} // get_timestamp($rtype);
$log->info("Collecting ids updated since $tstamp");
return Koha::Changelog::DBLog
->new( rtype => $rtype->{name} )
->get_todos( $tstamp );
}
}
sub s2hms {
my $s = shift;
my $hms;
if ($s > 5400) {
$hms = sprintf '%.02fh', $s / 3600;
}
elsif ($s > 120) {
$hms = sprintf '%.02fm', $s / 60;
}
else {
$hms = sprintf '%.02fs', $s;
}
return $hms;
}
sub process_list {
our ($rtype, $todos) = @_;
return unless @$todos;
our $solr = WebService::Solr->new( C4::Context->config('solr')->{url},
{ autocommit => 0 } );
my %deletes = map { $_->{id} => 1} grep { $_->{action} ~~ 'delete' } @$todos;
my %updates = map { $_->{id} => 1} grep { $_->{action} ~~ 'update' } @$todos;
# Remove deleted items from updates list
%updates = map { $_ => 1 } grep { ! exists $deletes{$_} } keys %updates;
if ( my @delete_ids = map { $rtype->{prefix}.'_'.$_} keys %deletes ) {
$log->info('Deleting '. @delete_ids .' docs');
$solr->delete( {id => \@delete_ids} );
$log->info('Delete complete');
}
our $r = Koha::Solr::IndexStrategy::MARC->new(
rules_text => scalar read_file($rtype->{rules_file}) );
our ($update_count, $render_errors, $update_errors) = (0, 0, 0);
our ($start_time, undef) = gettimeofday();
our $queue_size = scalar keys %updates;
$log->info("Have $queue_size updates in queue");
sub doc_with_catch {
my $id = shift;
$log->debug("Expressing $id");
my $record = $rtype->{acquire_one}->($id);
return unless $record;
my $doc = try {
$update_count++;
Koha::Solr::Document::MARC->new(
record => $record, strategy => $r );
}
catch {
$log->warn("Error rendering $id into Solr doc: $_");
$render_errors++;
$update_count--;
undef;
};
return $doc;
};
sub add_with_catch {
my $update_docs = shift;
return unless @$update_docs;
if ($rtype->{opts}{to_stdout}) {
say join('', @$update_docs);
return;
}
my ($now, undef) = gettimeofday();
my $total_elapsed_seconds = ($now - $start_time) || 1;
my $dps_all = int($update_count / $total_elapsed_seconds);
my $docs_remaining = $queue_size - $update_count;
my $est_seconds_remaining = int($docs_remaining / $dps_all);
my $elapsed = s2hms($total_elapsed_seconds);
my $remaining = s2hms($est_seconds_remaining);
my $msg = sprintf q{completed %d/%d, %d d/s, %s elapsed, %s remaining},
$update_count, $queue_size, $dps_all, $elapsed, $remaining;
$log->info($msg);
try {
$solr->add( $update_docs );
}
catch {
if (@$update_docs == 1) {
$log->warn('Unable to upload doc: ' . substr($_, 0, 255));
$update_errors++;
return;
}
$log->warn("Batch upload error. Splitting batch.");
my @ud2 = splice $update_docs, @$update_docs/2;
add_with_catch( $update_docs );
add_with_catch( \@ud2 );
undef;
};
$log->debug('Batch complete');
};
my $update_docs = [];
for ( sort {$a <=> $b} keys %updates ) {
my $doc = doc_with_catch($_);
next unless $doc;
push $update_docs, $doc;
if (@$update_docs >= $rtype->{opts}{batch_size}) {
add_with_catch( $update_docs );
$update_docs = [];
}
}
add_with_catch( $update_docs );
$log->info(
"Updated $update_count records with $render_errors render errors ".
"and $update_errors update errors.");
return;
}
sub get_timestamp {
my $rtype = shift;
return C4::Context->preference($rtype->{tspref})
// '1970-01-01 00:00:00';
}
sub update_timestamp {
my ($rtype, $todos) = @_;
return unless @$todos;
return if $rtype->{opts}{all}
|| $rtype->{opts}{ids}
|| $rtype->{opts}{to_stdout};
$todos = [ sort { $a->{stamp} cmp $b->{stamp} } @$todos ];
my $youngest_entry = pop @$todos;
my $youngest_ts = $youngest_entry->{stamp};
$log->info('Updated timestamp is '.($youngest_ts ? $youngest_ts : '(undef)'));
return unless $youngest_ts;
C4::Context->preference_set($rtype->{tspref}, $youngest_ts);
return;
}
__END__
=head1 NAME
solrsync - Synchronize Koha bibliographic data to Solr index
=head1 SYNOPSIS
solrsync [options]
Options:
--help | -h
--verbose | -v
--[no-]bibs
--[no-]auths
--all | -a
--since=T | -s T
--workers=N | -w N
--batch-size=N | -b N
--[no-]continuous | -c
--sleeptime=S | -t S
--ids=N,N,N-M
--stdout | -o
=head1 TYPICAL USE CASES
Sync all bibs:
=over
C<solrsync --bibs --all>
=back
Sync all auths and bibs verbosely using four worker threads:
=over
C<solrsync --auths --bibs --all --workers=4 -v>
=back
Sync only bibs updated since last sync:
=over
C<solrsync --bibs>
=back
Sync only bibs changed since date:
=over
C<solrsync --bibs -s 2012-10-03T10:00:00>
=back
Sync only auth with authid between 1234 and 2345:
=over
C<solrsync --auths --ids=1234-2345>
=back
Sync all newly modified bibs and auths every 30 seconds:
=over
C<solrync --bibs --auths --continuous --sleeptime=30>
=back
=head1 OPTIONS
=over
=item B<--verbose>
Increase verbosity. Mulitple invocations are cumulative.
=back
=over
=item B<--bibs>
Process bibliographic records. Default is --no-bibs.
=back
=over
=item B<--auths>
Process authority records. Default is --no-auths.
=back
=over
=item B<--all>
Process all bib and/or auth records in database. Default is --no-all.
=back
=over
=item B<--since=T>
Process all bib and/or auth records written to changelog since time T.
T is an ISO formatted datetime stamp. Default is the value stored in the
appropriate syspref, either SolrBibUpdateTS for bibs or SolrAuthUpdateTS
for auths.
=back
=over
=item B<--workers=N>
Deploy N workers to process the queue contents in parallel. Defaults to 1.
=back
=over
=item B<--batch-size=N>
Queue up N expressed docs before uploading them to the Solr server. Defaults
to 100.
=back
=over
=item B<--continuous>
Run as a persistent process running in a loop. Default is to run a single
time then exit.
=back
=over
=item B<--sleeptime=S>
Sleep for S seconds between queue runs. Only effective when running in
continuous mode. Default is 20.
=back
=over
=item B<--ids=N,N,N-M>
Process only the biblionumbers or authids given in the value of this option.
IDs must be comma separated. A sequence can be given with dashes. For example,
C<--ids=11,17,93-95,22> would enqueue 11, 17, 93, 94, 95, and 22.
=back
=over
=item B<--stdout>
For debugging purposes, mostly. Writes the expressed document to stdout
instead of sending it to the Solr server.
=back
=cut