1 package Koha::BackgroundJob;
3 # This file is part of Koha.
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.
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.
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>.
22 use Try::Tiny qw( catch try );
25 use Koha::DateUtils qw( dt_from_string );
28 use Koha::Exceptions::BackgroundJob;
30 use base qw( Koha::Object );
34 Koha::BackgroundJob - Koha BackgroundJob Object class
36 This is a base class for BackgroundJob, some methods must be subclassed.
41 my $job_id = Koha::BackgroundJob->enqueue(
43 job_type => $job_type,
44 job_size => $job_size,
50 Koha::BackgrounJobs->find($job_id)->process;
51 See also C<misc/background_jobs_worker.pl> for a full example
59 Connect to the message broker using default guest/guest credential
65 my $hostname = 'localhost';
67 my $config = C4::Context->config('message_broker');
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};
79 my $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } );
80 $stomp->connect( $credentials );
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.
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.
91 Return the job_id of the newly created job.
96 my ( $self, $params ) = @_;
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;
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);
117 context => $json_context,
118 enqueued_on => dt_from_string,
119 borrowernumber => $borrowernumber,
123 $job_args->{job_id} = $self->id;
127 $conn = $self->connect;
129 warn "Cannot connect to broker " . $_;
133 $json_args = $json->encode($job_args);
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');
143 $self->status('failed')->store;
144 if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
147 warn sprintf "The job has not been sent to the message broker: (%s)", $_;
161 my ( $self, $args ) = @_;
163 return {} if ref($self) ne 'Koha::BackgroundJob';
165 my $derived_class = $self->_derived_class;
169 if ( $self->context ) {
170 my $context = $self->json->decode($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}
184 Koha::Logger->get->warn("A background job didn't have context defined (" . $self->id . ")");
187 return $derived_class->process( $args );
194 Marks the job as started.
201 Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
202 current_status => $self->status,
203 expected_status => 'new'
204 ) unless $self->status eq 'new';
208 started_on => \'NOW()',
219 Makes the job record a step has taken place.
226 Koha::Exceptions::BackgroundJob::InconsistentStatus->throw(
227 current_status => $self->status,
228 expected_status => 'started'
229 ) unless $self->status eq 'started';
231 # reached the end of the tasks already
232 Koha::Exceptions::BackgroundJob::StepOutOfBounds->throw()
233 unless $self->progress < $self->size;
235 return $self->progress( $self->progress + 1 )->store;
242 Makes the job record as finished. If the job status is I<cancelled>, it is kept.
247 my ( $self, $data ) = @_;
249 $self->status('finished') unless $self->status eq 'cancelled';
253 ended_on => \'NOW()',
254 data => $self->json->encode($data),
261 my $JSON_object = $self->json;
263 Returns a JSON object with utf8 disabled. Encoding to UTF-8 should be
270 $self->{_json} //= JSON->new->utf8(0); # TODO Should we allow_nonref ?
271 return $self->{_json};
276 my $job_data = $self->decoded_data;
278 Returns the decoded JSON contents from $self->data.
285 return $self->data ? $self->json->decode( $self->data ) : undef;
288 =head3 set_encoded_data
290 $self->set_encoded_data( $data );
292 Serializes I<$data> as a JSON string and sets the I<data> attribute with it.
296 sub set_encoded_data {
297 my ( $self, $data ) = @_;
299 return $self->data( $data ? $self->json->encode($data) : undef );
304 Return the job type of the job. Must be a string.
308 sub job_type { croak "This method must be subclassed" }
312 Messages let during the processing of the job.
320 my $data_dump = $self->json->decode($self->data);
321 if ( exists $data_dump->{messages} ) {
322 @messages = @{ $data_dump->{messages} };
337 my $data_dump = $self->json->decode($self->data);
338 return $data_dump->{report} || {};
341 =head3 additional_report
343 Build additional variables for the job detail view.
347 sub additional_report {
350 return {} if ref($self) ne 'Koha::BackgroundJob';
352 my $derived_class = $self->_derived_class;
354 return $derived_class->additional_report;
365 $self->status('cancelled')->store;
368 =head2 Internal methods
370 =head3 _derived_class
376 my $job_type = $self->type;
378 my $class = $self->type_to_class_mapping->{$job_type};
380 Koha::Exception->throw($job_type . ' is not a valid job_type')
383 eval "require $class";
384 return $class->_new_from_dbic( $self->_result );
387 =head3 type_to_class_mapping
389 my $mapping = Koha::BackgrounJob->new->type_to_class_mapping;
391 Returns the available types to class mappings.
395 sub type_to_class_mapping {
398 my $plugins_mapping = ( C4::Context->config("enable_plugins") ) ? $self->plugin_types_to_classes : {};
400 return ($plugins_mapping)
401 ? { %{ $self->core_types_to_classes }, %$plugins_mapping }
402 : $self->core_types_to_classes;
405 =head3 core_types_to_classes
407 my $mappings = Koha::BackgrounJob->new->core_types_to_classes
409 Returns the core background jobs types to class mappings.
413 sub core_types_to_classes {
415 batch_authority_record_deletion => 'Koha::BackgroundJob::BatchDeleteAuthority',
416 batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
417 batch_biblio_record_deletion => 'Koha::BackgroundJob::BatchDeleteBiblio',
418 batch_biblio_record_modification => 'Koha::BackgroundJob::BatchUpdateBiblio',
419 batch_item_record_deletion => 'Koha::BackgroundJob::BatchDeleteItem',
420 batch_item_record_modification => 'Koha::BackgroundJob::BatchUpdateItem',
421 batch_hold_cancel => 'Koha::BackgroundJob::BatchCancelHold',
422 update_elastic_index => 'Koha::BackgroundJob::UpdateElasticIndex',
423 update_holds_queue_for_biblios => 'Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue',
427 =head3 plugin_types_to_classes
429 my $mappings = Koha::BackgroundJob->new->plugin_types_to_classes
431 Returns the plugin-defined background jobs types to class mappings.
435 sub plugin_types_to_classes {
438 unless ( exists $self->{_plugin_mapping} ) {
439 my @plugins = Koha::Plugins->new()->GetPlugins( { method => 'background_tasks', } );
441 foreach my $plugin (@plugins) {
443 my $tasks = $plugin->background_tasks;
444 my $metadata = $plugin->get_metadata;
446 unless ( $metadata->{namespace} ) {
447 Koha::Logger->get->warn(
448 q{A plugin includes the 'background_tasks' method, }
449 . q{but doesn't provide the required 'namespace' }
450 . qq{method ($plugin->{class})} );
454 my $namespace = $metadata->{namespace};
456 foreach my $type ( keys %{$tasks} ) {
457 my $class = $tasks->{$type};
459 # skip if conditions not met
460 next unless $type and $class;
462 my $key = "plugin_$namespace" . "_$type";
464 $self->{_plugin_mapping}->{$key} = $tasks->{$type};
469 return $self->{_plugin_mapping};
477 return 'BackgroundJob';