Bug 30360: Add helper methods to Koha::BackgroundJobs
[koha-ffzg.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_queue = $params->{job_queue} // 'default';
103
104     my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef;
105     my $json_args = encode_json $job_args;
106
107     $self->set(
108         {
109             status         => 'new',
110             type           => $job_type,
111             queue          => $job_queue,
112             size           => $job_size,
113             data           => $json_args,
114             enqueued_on    => dt_from_string,
115             borrowernumber => $borrowernumber,
116         }
117     )->store;
118
119     $job_args->{job_id} = $self->id;
120
121     my $conn;
122     try {
123         $conn = $self->connect;
124     } catch {
125         warn "Cannot connect to broker " . $_;
126     };
127     return unless $conn;
128
129     $json_args = encode_json $job_args;
130     try {
131         # This namespace is wrong, it must be a vhost instead.
132         # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
133         # Also, here we just want the Koha instance's name, but it's not in the config...
134         # Picking a random id (memcached_namespace) from the config
135         my $namespace = C4::Context->config('memcached_namespace');
136         $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_queue), body => $json_args } )
137           or Koha::Exceptions::Exception->throw('Job has not been enqueued');
138     } catch {
139         $self->status('failed')->store;
140         if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
141             $_->rethrow;
142         } else {
143             warn sprintf "The job has not been sent to the message broker: (%s)", $_;
144         }
145     };
146
147     return $self->id;
148 }
149
150 =head3 process
151
152 Process the job!
153
154 =cut
155
156 sub process {
157     my ( $self, $args ) = @_;
158
159     return {} if ref($self) ne 'Koha::BackgroundJob';
160
161     my $derived_class = $self->_derived_class;
162
163     $args ||= {};
164
165     return $derived_class->process( $args );
166 }
167
168 =head3 start
169
170     $self->start;
171
172 Marks the job as started.
173
174 =cut
175
176 sub start {
177     my ($self) = @_;
178
179     Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
180         current_status  => $self->status,
181         expected_status => 'new'
182     ) unless $self->status eq 'new';
183
184     return $self->set(
185         {
186             started_on => \'NOW()',
187             progress   => 0,
188             status     => 'started',
189         }
190     )->store;
191 }
192
193 =head3 step
194
195     $self->step;
196
197 Makes the job record a step has taken place.
198
199 =cut
200
201 sub step {
202     my ($self) = @_;
203
204     Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
205         current_status  => $self->status,
206         expected_status => 'started'
207     ) unless $self->status eq 'started';
208
209     # reached the end of the tasks already
210     Koha::Exceptions::BackgroundJob::StepOutOfBounds->throw()
211         unless $self->progress < $self->size;
212
213     return $self->progress( $self->progress + 1 )->store;
214 }
215
216 =head3 finish
217
218     $self->finish;
219
220 Makes the job record as finished. If the job status is I<cancelled>, it is kept.
221
222 =cut
223
224 sub finish {
225     my ( $self, $data ) = @_;
226
227     $self->status('finished') unless $self->status eq 'cancelled';
228
229     return $self->set(
230         {
231             ended_on => \'NOW()',
232             data     => encode_json($data),
233         }
234     )->store;
235 }
236
237 =head3 job_type
238
239 Return the job type of the job. Must be a string.
240
241 =cut
242
243 sub job_type { croak "This method must be subclassed" }
244
245 =head3 messages
246
247 Messages let during the processing of the job.
248
249 =cut
250
251 sub messages {
252     my ( $self ) = @_;
253
254     my @messages;
255     my $data_dump = decode_json encode_utf8 $self->data;
256     if ( exists $data_dump->{messages} ) {
257         @messages = @{ $data_dump->{messages} };
258     }
259
260     return \@messages;
261 }
262
263 =head3 report
264
265 Report of the job.
266
267 =cut
268
269 sub report {
270     my ( $self ) = @_;
271
272     my $data_dump = decode_json encode_utf8 $self->data;
273     return $data_dump->{report} || {};
274 }
275
276 =head3 additional_report
277
278 Build additional variables for the job detail view.
279
280 =cut
281
282 sub additional_report {
283     my ( $self ) = @_;
284
285     return {} if ref($self) ne 'Koha::BackgroundJob';
286
287     my $derived_class = $self->_derived_class;
288
289     return $derived_class->additional_report;
290 }
291
292 =head3 cancel
293
294 Cancel a job.
295
296 =cut
297
298 sub cancel {
299     my ( $self ) = @_;
300     $self->status('cancelled')->store;
301 }
302
303 =head2 Internal methods
304
305 =head3 _derived_class
306
307 =cut
308
309 sub _derived_class {
310     my ( $self ) = @_;
311     my $job_type = $self->type;
312
313     my $class = $self->type_to_class_mapping->{$job_type};
314
315     Koha::Exception->throw($job_type . ' is not a valid job_type')
316         unless $class;
317
318     eval "require $class";
319     return $class->_new_from_dbic( $self->_result );
320 }
321
322 =head3 type_to_class_mapping
323
324     my $mapping = Koha::BackgrounJob->new->type_to_class_mapping;
325
326 Returns the available types to class mappings.
327
328 =cut
329
330 sub type_to_class_mapping {
331     my ($self) = @_;
332
333     my $plugins_mapping = $self->plugin_types_to_classes;
334
335     return ($plugins_mapping)
336       ? { %{ $self->core_types_to_classes }, %$plugins_mapping }
337       : $self->core_types_to_classes;
338 }
339
340 =head3 core_types_to_classes
341
342     my $mappings = Koha::BackgrounJob->new->core_types_to_classes
343
344 Returns the core background jobs types to class mappings.
345
346 =cut
347
348 sub core_types_to_classes {
349     return {
350         batch_authority_record_deletion     => 'Koha::BackgroundJob::BatchDeleteAuthority',
351         batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
352         batch_biblio_record_deletion        => 'Koha::BackgroundJob::BatchDeleteBiblio',
353         batch_biblio_record_modification    => 'Koha::BackgroundJob::BatchUpdateBiblio',
354         batch_item_record_deletion          => 'Koha::BackgroundJob::BatchDeleteItem',
355         batch_item_record_modification      => 'Koha::BackgroundJob::BatchUpdateItem',
356         batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
357         update_elastic_index                => 'Koha::BackgroundJob::UpdateElasticIndex',
358     };
359 }
360
361 =head3 plugin_types_to_classes
362
363     my $mappings = Koha::BackgroundJob->new->plugin_types_to_classes
364
365 Returns the plugin-defined background jobs types to class mappings.
366
367 =cut
368
369 sub plugin_types_to_classes {
370     my ($self) = @_;
371
372     unless ( exists $self->{_plugin_mapping} ) {
373         my @plugins = Koha::Plugins->new()->GetPlugins( { method => 'background_tasks', } );
374
375         foreach my $plugin (@plugins) {
376
377             my $tasks    = $plugin->background_tasks;
378             my $metadata = $plugin->get_metadata;
379
380             unless ( $metadata->{namespace} ) {
381                 Koha::Logger->get->warn(
382                         q{A plugin includes the 'background_tasks' method, }
383                       . q{but doesn't provide the required 'namespace' }
384                       . qq{method ($plugin->{class})} );
385                 next;
386             }
387
388             my $namespace = $metadata->{namespace};
389
390             foreach my $type ( keys %{$tasks} ) {
391                 my $class = $tasks->{$type};
392
393                 # skip if conditions not met
394                 next unless $type and $class;
395
396                 my $key = "plugin_$namespace" . "_$type";
397
398                 $self->{_plugin_mapping}->{$key} = $tasks->{$type};
399             }
400         }
401     }
402
403     return $self->{_plugin_mapping};
404 }
405
406 =head3 _type
407
408 =cut
409
410 sub _type {
411     return 'BackgroundJob';
412 }
413
414 1;