dcfba14659d60508e1293a3a3c28bf7694311e90
[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 JSON qw( decode_json encode_json );
20 use Encode qw( encode_utf8 );
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::Plugins;
29 use Koha::Exceptions::BackgroundJob;
30
31 use base qw( Koha::Object );
32
33 =head1 NAME
34
35 Koha::BackgroundJob - Koha BackgroundJob Object class
36
37 This is a base class for BackgroundJob, some methods must be subclassed.
38
39 Example of usage:
40
41 Producer:
42 my $job_id = Koha::BackgroundJob->enqueue(
43     {
44         job_type => $job_type,
45         job_size => $job_size,
46         job_args => $job_args
47     }
48 );
49
50 Consumer:
51 Koha::BackgrounJobs->find($job_id)->process;
52 See also C<misc/background_jobs_worker.pl> for a full example
53
54 =head1 API
55
56 =head2 Class methods
57
58 =head3 connect
59
60 Connect to the message broker using default guest/guest credential
61
62 =cut
63
64 sub connect {
65     my ( $self );
66     my $hostname = 'localhost';
67     my $port = '61613';
68     my $config = C4::Context->config('message_broker');
69     my $credentials = {
70         login => 'guest',
71         passcode => 'guest',
72     };
73     if ($config){
74         $hostname = $config->{hostname} if $config->{hostname};
75         $port = $config->{port} if $config->{port};
76         $credentials->{login} = $config->{username} if $config->{username};
77         $credentials->{passcode} = $config->{password} if $config->{password};
78         $credentials->{host} = $config->{vhost} if $config->{vhost};
79     }
80     my $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } );
81     $stomp->connect( $credentials );
82     return $stomp;
83 }
84
85 =head3 enqueue
86
87 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.
88
89 C<job_size> is the size of the job
90 C<job_args> is the arguments of the job. It's a structure that will be JSON encoded.
91
92 Return the job_id of the newly created job.
93
94 =cut
95
96 sub enqueue {
97     my ( $self, $params ) = @_;
98
99     my $job_type    = $self->job_type;
100     my $job_size    = $params->{job_size};
101     my $job_args    = $params->{job_args};
102     my $job_context = $params->{job_context} // C4::Context->userenv;
103     my $job_queue   = $params->{job_queue}  // 'default';
104
105     my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef;
106     $job_context->{interface} = C4::Context->interface;
107     my $json_context = encode_json $job_context;
108     my $json_args = encode_json $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 = encode_json $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         $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_queue), body => $json_args } )
141           or Koha::Exceptions::Exception->throw('Job has not been enqueued');
142     } catch {
143         $self->status('failed')->store;
144         if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
145             $_->rethrow;
146         } else {
147             warn sprintf "The job has not been sent to the message broker: (%s)", $_;
148         }
149     };
150
151     return $self->id;
152 }
153
154 =head3 process
155
156 Process the job!
157
158 =cut
159
160 sub process {
161     my ( $self, $args ) = @_;
162
163     return {} if ref($self) ne 'Koha::BackgroundJob';
164
165     my $derived_class = $self->_derived_class;
166
167     $args ||= {};
168
169     if ( $self->context ) {
170         my $context = decode_json($self->context);
171         C4::Context->_new_userenv(-1);
172         C4::Context->interface( $context->{interface} );
173         C4::Context->set_userenv(
174             $context->{number},       $context->{id},
175             $context->{cardnumber},   $context->{firstname},
176             $context->{surname},      $context->{branch},
177             $context->{branchname},   $context->{flags},
178             $context->{emailaddress}, undef,
179             $context->{desk_id},      $context->{desk_name},
180             $context->{register_id},  $context->{register_name}
181         );
182     }
183     else {
184         Koha::Logger->get->warn("A background job didn't have context defined (" . $self->id . ")");
185     }
186
187     return $derived_class->process( $args );
188 }
189
190 =head3 start
191
192     $self->start;
193
194 Marks the job as started.
195
196 =cut
197
198 sub start {
199     my ($self) = @_;
200
201     Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
202         current_status  => $self->status,
203         expected_status => 'new'
204     ) unless $self->status eq 'new';
205
206     return $self->set(
207         {
208             started_on => \'NOW()',
209             progress   => 0,
210             status     => 'started',
211         }
212     )->store;
213 }
214
215 =head3 step
216
217     $self->step;
218
219 Makes the job record a step has taken place.
220
221 =cut
222
223 sub step {
224     my ($self) = @_;
225
226     Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
227         current_status  => $self->status,
228         expected_status => 'started'
229     ) unless $self->status eq 'started';
230
231     # reached the end of the tasks already
232     Koha::Exceptions::BackgroundJob::StepOutOfBounds->throw()
233         unless $self->progress < $self->size;
234
235     return $self->progress( $self->progress + 1 )->store;
236 }
237
238 =head3 finish
239
240     $self->finish;
241
242 Makes the job record as finished. If the job status is I<cancelled>, it is kept.
243
244 =cut
245
246 sub finish {
247     my ( $self, $data ) = @_;
248
249     $self->status('finished') unless $self->status eq 'cancelled';
250
251     return $self->set(
252         {
253             ended_on => \'NOW()',
254             data     => encode_json($data),
255         }
256     )->store;
257 }
258
259 =head3 decoded_data
260
261     my $job_data = $self->decoded_data;
262
263 Returns the decoded JSON contents from $self->data.
264
265 =cut
266
267 sub decoded_data {
268     my ($self) = @_;
269
270     return $self->data ? decode_json( $self->data ) : undef;
271 }
272
273 =head3 set_encoded_data
274
275     $self->set_encoded_data( $data );
276
277 Serializes I<$data> as a JSON string and sets the I<data> attribute with it.
278
279 =cut
280
281 sub set_encoded_data {
282     my ( $self, $data ) = @_;
283
284     return $self->data( $data ? encode_json($data) : undef );
285 }
286
287 =head3 job_type
288
289 Return the job type of the job. Must be a string.
290
291 =cut
292
293 sub job_type { croak "This method must be subclassed" }
294
295 =head3 messages
296
297 Messages let during the processing of the job.
298
299 =cut
300
301 sub messages {
302     my ( $self ) = @_;
303
304     my @messages;
305     my $data_dump = decode_json encode_utf8 $self->data;
306     if ( exists $data_dump->{messages} ) {
307         @messages = @{ $data_dump->{messages} };
308     }
309
310     return \@messages;
311 }
312
313 =head3 report
314
315 Report of the job.
316
317 =cut
318
319 sub report {
320     my ( $self ) = @_;
321
322     my $data_dump = decode_json encode_utf8 $self->data;
323     return $data_dump->{report} || {};
324 }
325
326 =head3 additional_report
327
328 Build additional variables for the job detail view.
329
330 =cut
331
332 sub additional_report {
333     my ( $self ) = @_;
334
335     return {} if ref($self) ne 'Koha::BackgroundJob';
336
337     my $derived_class = $self->_derived_class;
338
339     return $derived_class->additional_report;
340 }
341
342 =head3 cancel
343
344 Cancel a job.
345
346 =cut
347
348 sub cancel {
349     my ( $self ) = @_;
350     $self->status('cancelled')->store;
351 }
352
353 =head2 Internal methods
354
355 =head3 _derived_class
356
357 =cut
358
359 sub _derived_class {
360     my ( $self ) = @_;
361     my $job_type = $self->type;
362
363     my $class = $self->type_to_class_mapping->{$job_type};
364
365     Koha::Exception->throw($job_type . ' is not a valid job_type')
366         unless $class;
367
368     eval "require $class";
369     return $class->_new_from_dbic( $self->_result );
370 }
371
372 =head3 type_to_class_mapping
373
374     my $mapping = Koha::BackgrounJob->new->type_to_class_mapping;
375
376 Returns the available types to class mappings.
377
378 =cut
379
380 sub type_to_class_mapping {
381     my ($self) = @_;
382
383     my $plugins_mapping = ( C4::Context->config("enable_plugins") ) ? $self->plugin_types_to_classes : {};
384
385     return ($plugins_mapping)
386       ? { %{ $self->core_types_to_classes }, %$plugins_mapping }
387       : $self->core_types_to_classes;
388 }
389
390 =head3 core_types_to_classes
391
392     my $mappings = Koha::BackgrounJob->new->core_types_to_classes
393
394 Returns the core background jobs types to class mappings.
395
396 =cut
397
398 sub core_types_to_classes {
399     return {
400         batch_authority_record_deletion     => 'Koha::BackgroundJob::BatchDeleteAuthority',
401         batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
402         batch_biblio_record_deletion        => 'Koha::BackgroundJob::BatchDeleteBiblio',
403         batch_biblio_record_modification    => 'Koha::BackgroundJob::BatchUpdateBiblio',
404         batch_item_record_deletion          => 'Koha::BackgroundJob::BatchDeleteItem',
405         batch_item_record_modification      => 'Koha::BackgroundJob::BatchUpdateItem',
406         batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
407         update_elastic_index                => 'Koha::BackgroundJob::UpdateElasticIndex',
408         update_holds_queue_for_biblios      => 'Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue',
409     };
410 }
411
412 =head3 plugin_types_to_classes
413
414     my $mappings = Koha::BackgroundJob->new->plugin_types_to_classes
415
416 Returns the plugin-defined background jobs types to class mappings.
417
418 =cut
419
420 sub plugin_types_to_classes {
421     my ($self) = @_;
422
423     unless ( exists $self->{_plugin_mapping} ) {
424         my @plugins = Koha::Plugins->new()->GetPlugins( { method => 'background_tasks', } );
425
426         foreach my $plugin (@plugins) {
427
428             my $tasks    = $plugin->background_tasks;
429             my $metadata = $plugin->get_metadata;
430
431             unless ( $metadata->{namespace} ) {
432                 Koha::Logger->get->warn(
433                         q{A plugin includes the 'background_tasks' method, }
434                       . q{but doesn't provide the required 'namespace' }
435                       . qq{method ($plugin->{class})} );
436                 next;
437             }
438
439             my $namespace = $metadata->{namespace};
440
441             foreach my $type ( keys %{$tasks} ) {
442                 my $class = $tasks->{$type};
443
444                 # skip if conditions not met
445                 next unless $type and $class;
446
447                 my $key = "plugin_$namespace" . "_$type";
448
449                 $self->{_plugin_mapping}->{$key} = $tasks->{$type};
450             }
451         }
452     }
453
454     return $self->{_plugin_mapping};
455 }
456
457 =head3 _type
458
459 =cut
460
461 sub _type {
462     return 'BackgroundJob';
463 }
464
465 1;