0ba7ba46edec166d3aec9de40ce92eb3a31d7cba
[koha.git] / Koha / BackgroundJob.pm
1 package Koha::BackgroundJob;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # 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 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use Encode qw();
20 use JSON;
21 use Carp qw( croak );
22 use Net::Stomp;
23 use Try::Tiny qw( catch try );
24
25 use C4::Context;
26 use Koha::DateUtils qw( dt_from_string );
27 use Koha::Exceptions;
28 use Koha::Exceptions::BackgroundJob;
29
30 use base qw( Koha::Object );
31
32 =head1 NAME
33
34 Koha::BackgroundJob - Koha BackgroundJob Object class
35
36 This is a base class for BackgroundJob, some methods must be subclassed.
37
38 Example of usage:
39
40 Producer:
41 my $job_id = Koha::BackgroundJob->enqueue(
42     {
43         job_type => $job_type,
44         job_size => $job_size,
45         job_args => $job_args
46     }
47 );
48
49 Consumer:
50 Koha::BackgroundJobs->find($job_id)->process;
51 See also C<misc/background_jobs_worker.pl> for a full example
52
53 =head1 API
54
55 =head2 Class methods
56
57 =head3 connect
58
59 Connect to the message broker using default guest/guest credential
60
61 =cut
62
63 sub connect {
64     my ( $self );
65     my $hostname = 'localhost';
66     my $port = '61613';
67     my $config = C4::Context->config('message_broker');
68     my $credentials = {
69         login => 'guest',
70         passcode => 'guest',
71     };
72     if ($config){
73         $hostname = $config->{hostname} if $config->{hostname};
74         $port = $config->{port} if $config->{port};
75         $credentials->{login} = $config->{username} if $config->{username};
76         $credentials->{passcode} = $config->{password} if $config->{password};
77         $credentials->{host} = $config->{vhost} if $config->{vhost};
78     }
79     my $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } );
80     $stomp->connect( $credentials );
81     return $stomp;
82 }
83
84 =head3 enqueue
85
86 Enqueue a new job. It will insert a new row in the DB table and notify the broker that a new job has been enqueued.
87
88 C<job_size> is the size of the job
89 C<job_args> is the arguments of the job. It's a structure that will be JSON encoded.
90
91 Return the job_id of the newly created job.
92
93 =cut
94
95 sub enqueue {
96     my ( $self, $params ) = @_;
97
98     my $job_type    = $self->job_type;
99     my $job_size    = $params->{job_size};
100     my $job_args    = $params->{job_args};
101     my $job_context = $params->{job_context} // C4::Context->userenv;
102     my $job_queue   = $params->{job_queue}  // 'default';
103     my $json = $self->json;
104
105     my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef;
106     $job_context->{interface} = C4::Context->interface;
107     my $json_context = $json->encode($job_context);
108     my $json_args = $json->encode($job_args);
109
110     $self->set(
111         {
112             status         => 'new',
113             type           => $job_type,
114             queue          => $job_queue,
115             size           => $job_size,
116             data           => $json_args,
117             context        => $json_context,
118             enqueued_on    => dt_from_string,
119             borrowernumber => $borrowernumber,
120         }
121     )->store;
122
123     $job_args->{job_id} = $self->id;
124
125     my $conn;
126     try {
127         $conn = $self->connect;
128     } catch {
129         warn "Cannot connect to broker " . $_;
130     };
131     return unless $conn;
132
133     $json_args = $json->encode($job_args);
134     try {
135         # This namespace is wrong, it must be a vhost instead.
136         # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
137         # Also, here we just want the Koha instance's name, but it's not in the config...
138         # Picking a random id (memcached_namespace) from the config
139         my $namespace = C4::Context->config('memcached_namespace');
140         my $encoded_args = Encode::encode_utf8( $json_args ); # FIXME We should better leave this to Net::Stomp?
141         $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_queue), body => $encoded_args } )
142           or Koha::Exceptions::Exception->throw('Job has not been enqueued');
143     } catch {
144         $self->status('failed')->store;
145         if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
146             $_->rethrow;
147         } else {
148             warn sprintf "The job has not been sent to the message broker: (%s)", $_;
149         }
150     };
151
152     return $self->id;
153 }
154
155 =head3 process
156
157 Process the job!
158
159 =cut
160
161 sub process {
162     my ( $self, $args ) = @_;
163
164     return {} if ref($self) ne 'Koha::BackgroundJob';
165
166     my $derived_class = $self->_derived_class;
167
168     $args ||= {};
169
170     if ( $self->context ) {
171         my $context = $self->json->decode($self->context);
172         C4::Context->_new_userenv(-1);
173         C4::Context->interface( $context->{interface} );
174         C4::Context->set_userenv(
175             $context->{number},       $context->{id},
176             $context->{cardnumber},   $context->{firstname},
177             $context->{surname},      $context->{branch},
178             $context->{branchname},   $context->{flags},
179             $context->{emailaddress}, undef,
180             $context->{desk_id},      $context->{desk_name},
181             $context->{register_id},  $context->{register_name}
182         );
183     }
184     else {
185         Koha::Logger->get->warn("A background job didn't have context defined (" . $self->id . ")");
186     }
187
188     return $derived_class->process( $args );
189 }
190
191 =head3 start
192
193     $self->start;
194
195 Marks the job as started.
196
197 =cut
198
199 sub start {
200     my ($self) = @_;
201
202     Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
203         current_status  => $self->status,
204         expected_status => 'new'
205     ) unless $self->status eq 'new';
206
207     return $self->set(
208         {
209             started_on => \'NOW()',
210             progress   => 0,
211             status     => 'started',
212         }
213     )->store;
214 }
215
216 =head3 step
217
218     $self->step;
219
220 Makes the job record a step has taken place.
221
222 =cut
223
224 sub step {
225     my ($self) = @_;
226
227     Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
228         current_status  => $self->status,
229         expected_status => 'started'
230     ) unless $self->status eq 'started';
231
232     # reached the end of the tasks already
233     Koha::Exceptions::BackgroundJob::StepOutOfBounds->throw()
234         unless $self->progress < $self->size;
235
236     return $self->progress( $self->progress + 1 )->store;
237 }
238
239 =head3 finish
240
241     $self->finish;
242
243 Makes the job record as finished. If the job status is I<cancelled>, it is kept.
244
245 =cut
246
247 sub finish {
248     my ( $self, $data ) = @_;
249
250     $self->status('finished') unless $self->status eq 'cancelled' or $self->status eq 'failed';
251
252     return $self->set(
253         {
254             ended_on => \'NOW()',
255             data     => $self->json->encode($data),
256         }
257     )->store;
258 }
259
260 =head3 json
261
262    my $JSON_object = $self->json;
263
264 Returns a JSON object with utf8 disabled. Encoding to UTF-8 should be
265 done later.
266
267 =cut
268
269 sub json {
270     my ( $self ) = @_;
271     $self->{_json} //= JSON->new->utf8(0); # TODO Should we allow_nonref ?
272     return $self->{_json};
273 }
274
275 =head3 decoded_data
276
277     my $job_data = $self->decoded_data;
278
279 Returns the decoded JSON contents from $self->data.
280
281 =cut
282
283 sub decoded_data {
284     my ($self) = @_;
285
286     return $self->data ? $self->json->decode( $self->data ) : undef;
287 }
288
289 =head3 set_encoded_data
290
291     $self->set_encoded_data( $data );
292
293 Serializes I<$data> as a JSON string and sets the I<data> attribute with it.
294
295 =cut
296
297 sub set_encoded_data {
298     my ( $self, $data ) = @_;
299
300     return $self->data( $data ? $self->json->encode($data) : undef );
301 }
302
303 =head3 job_type
304
305 Return the job type of the job. Must be a string.
306
307 =cut
308
309 sub job_type { croak "This method must be subclassed" }
310
311 =head3 messages
312
313 Messages let during the processing of the job.
314
315 =cut
316
317 sub messages {
318     my ( $self ) = @_;
319
320     my @messages;
321     my $data_dump = $self->json->decode($self->data);
322     if ( exists $data_dump->{messages} ) {
323         @messages = @{ $data_dump->{messages} };
324     }
325
326     return \@messages;
327 }
328
329 =head3 report
330
331 Report of the job.
332
333 =cut
334
335 sub report {
336     my ( $self ) = @_;
337
338     my $data_dump = $self->json->decode($self->data);
339     return $data_dump->{report} || {};
340 }
341
342 =head3 additional_report
343
344 Build additional variables for the job detail view.
345
346 =cut
347
348 sub additional_report {
349     my ( $self ) = @_;
350
351     return {} if ref($self) ne 'Koha::BackgroundJob';
352
353     my $derived_class = $self->_derived_class;
354
355     return $derived_class->additional_report;
356 }
357
358 =head3 cancel
359
360 Cancel a job.
361
362 =cut
363
364 sub cancel {
365     my ( $self ) = @_;
366     $self->status('cancelled')->store;
367 }
368
369 =head2 Internal methods
370
371 =head3 _derived_class
372
373 =cut
374
375 sub _derived_class {
376     my ( $self ) = @_;
377     my $job_type = $self->type;
378
379     my $class = $self->type_to_class_mapping->{$job_type};
380
381     Koha::Exception->throw($job_type . ' is not a valid job_type')
382         unless $class;
383
384     eval "require $class";
385     return $class->_new_from_dbic( $self->_result );
386 }
387
388 =head3 type_to_class_mapping
389
390     my $mapping = Koha::BackgroundJob->new->type_to_class_mapping;
391
392 Returns the available types to class mappings.
393
394 =cut
395
396 sub type_to_class_mapping {
397     my ($self) = @_;
398
399     my $plugins_mapping = ( C4::Context->config("enable_plugins") ) ? $self->plugin_types_to_classes : {};
400
401     return ($plugins_mapping)
402       ? { %{ $self->core_types_to_classes }, %$plugins_mapping }
403       : $self->core_types_to_classes;
404 }
405
406 =head3 core_types_to_classes
407
408     my $mappings = Koha::BackgroundJob->new->core_types_to_classes
409
410 Returns the core background jobs types to class mappings.
411
412 =cut
413
414 sub core_types_to_classes {
415     return {
416         batch_authority_record_deletion     => 'Koha::BackgroundJob::BatchDeleteAuthority',
417         batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
418         batch_biblio_record_deletion        => 'Koha::BackgroundJob::BatchDeleteBiblio',
419         batch_biblio_record_modification    => 'Koha::BackgroundJob::BatchUpdateBiblio',
420         batch_item_record_deletion          => 'Koha::BackgroundJob::BatchDeleteItem',
421         batch_item_record_modification      => 'Koha::BackgroundJob::BatchUpdateItem',
422         batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
423         create_eholdings_from_biblios       => 'Koha::BackgroundJob::CreateEHoldingsFromBiblios',
424         update_elastic_index                => 'Koha::BackgroundJob::UpdateElasticIndex',
425         update_holds_queue_for_biblios      => 'Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue',
426         stage_marc_for_import               => 'Koha::BackgroundJob::StageMARCForImport',
427         marc_import_commit_batch            => 'Koha::BackgroundJob::MARCImportCommitBatch',
428         marc_import_revert_batch            => 'Koha::BackgroundJob::MARCImportRevertBatch',
429     };
430 }
431
432 =head3 plugin_types_to_classes
433
434     my $mappings = Koha::BackgroundJob->new->plugin_types_to_classes
435
436 Returns the plugin-defined background jobs types to class mappings.
437
438 =cut
439
440 sub plugin_types_to_classes {
441     my ($self) = @_;
442
443     unless ( exists $self->{_plugin_mapping} ) {
444         require Koha::Plugins;
445         my @plugins = Koha::Plugins->new()->GetPlugins( { method => 'background_tasks', } );
446
447         foreach my $plugin (@plugins) {
448
449             my $tasks    = $plugin->background_tasks;
450             my $metadata = $plugin->get_metadata;
451
452             unless ( $metadata->{namespace} ) {
453                 Koha::Logger->get->warn(
454                         q{A plugin includes the 'background_tasks' method, }
455                       . q{but doesn't provide the required 'namespace' }
456                       . qq{method ($plugin->{class})} );
457                 next;
458             }
459
460             my $namespace = $metadata->{namespace};
461
462             foreach my $type ( keys %{$tasks} ) {
463                 my $class = $tasks->{$type};
464
465                 # skip if conditions not met
466                 next unless $type and $class;
467
468                 my $key = "plugin_$namespace" . "_$type";
469
470                 $self->{_plugin_mapping}->{$key} = $tasks->{$type};
471             }
472         }
473     }
474
475     return $self->{_plugin_mapping};
476 }
477
478 =head3 to_api
479
480     my $json = $job->to_api;
481
482 Overloaded method that returns a JSON representation of the Koha::BackgroundJob object,
483 suitable for API output.
484
485 =cut
486
487 sub to_api {
488     my ( $self, $params ) = @_;
489
490     my $json = $self->SUPER::to_api( $params );
491
492     $json->{context} = $self->json->decode($self->context)
493       if defined $self->context;
494     $json->{data} = $self->decoded_data;
495
496     return $json;
497 }
498
499 =head3 to_api_mapping
500
501 This method returns the mapping for representing a Koha::BackgroundJob object
502 on the API.
503
504 =cut
505
506 sub to_api_mapping {
507     return {
508         id             => 'job_id',
509         borrowernumber => 'patron_id',
510         ended_on       => 'ended_date',
511         enqueued_on    => 'enqueued_date',
512         started_on     => 'started_date',
513     };
514 }
515
516 =head3 _type
517
518 =cut
519
520 sub _type {
521     return 'BackgroundJob';
522 }
523
524 1;