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>.
19 use JSON qw( decode_json encode_json );
20 use Encode qw( encode_utf8 );
23 use Try::Tiny qw( catch try );
26 use Koha::DateUtils qw( dt_from_string );
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_queue = $params->{job_queue} // 'default';
103 my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef;
104 my $json_args = encode_json $job_args;
113 enqueued_on => dt_from_string,
114 borrowernumber => $borrowernumber,
118 $job_args->{job_id} = $self->id;
122 $conn = $self->connect;
124 warn "Cannot connect to broker " . $_;
128 $json_args = encode_json $job_args;
130 # This namespace is wrong, it must be a vhost instead.
131 # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
132 # Also, here we just want the Koha instance's name, but it's not in the config...
133 # Picking a random id (memcached_namespace) from the config
134 my $namespace = C4::Context->config('memcached_namespace');
135 $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_queue), body => $json_args } )
136 or Koha::Exceptions::Exception->throw('Job has not been enqueued');
138 $self->status('failed')->store;
139 if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
142 warn sprintf "The job has not been sent to the message broker: (%s)", $_;
156 my ( $self, $args ) = @_;
158 return {} if ref($self) ne 'Koha::BackgroundJob';
160 my $derived_class = $self->_derived_class;
164 return $derived_class->process( $args );
169 Return the job type of the job. Must be a string.
173 sub job_type { croak "This method must be subclassed" }
177 Messages let during the processing of the job.
185 my $data_dump = decode_json encode_utf8 $self->data;
186 if ( exists $data_dump->{messages} ) {
187 @messages = @{ $data_dump->{messages} };
202 my $data_dump = decode_json encode_utf8 $self->data;
203 return $data_dump->{report} || {};
206 =head3 additional_report
208 Build additional variables for the job detail view.
212 sub additional_report {
215 return {} if ref($self) ne 'Koha::BackgroundJob';
217 my $derived_class = $self->_derived_class;
219 return $derived_class->additional_report;
230 $self->status('cancelled')->store;
233 =head2 Internal methods
235 =head3 _derived_class
241 my $job_type = $self->type;
243 my $class = $self->type_to_class_mapping->{$job_type};
245 Koha::Exception->throw($job_type . ' is not a valid job_type')
248 eval "require $class";
249 return $class->_new_from_dbic( $self->_result );
252 =head3 type_to_class_mapping
254 my $mapping = Koha::BackgrounJob->new->type_to_class_mapping;
256 Returns the available types to class mappings.
260 sub type_to_class_mapping {
263 my $plugins_mapping = $self->plugin_type_to_class;
265 return ($plugins_mapping)
266 ? { %{ $self->core_type_to_class }, %{ $self->plugin_type_to_class } }
267 : $self->core_type_to_class;
270 =head3 core_type_to_class
272 my $mappings = Koha::BackgrounJob->new->core_type_to_class
274 Returns the core background jobs types to class mappings.
278 sub core_type_to_class {
280 batch_authority_record_deletion => 'Koha::BackgroundJob::BatchDeleteAuthority',
281 batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
282 batch_biblio_record_deletion => 'Koha::BackgroundJob::BatchDeleteBiblio',
283 batch_biblio_record_modification => 'Koha::BackgroundJob::BatchUpdateBiblio',
284 batch_item_record_deletion => 'Koha::BackgroundJob::BatchDeleteItem',
285 batch_item_record_modification => 'Koha::BackgroundJob::BatchUpdateItem',
286 batch_hold_cancel => 'Koha::BackgroundJob::BatchCancelHold',
290 =head3 plugin_type_to_class
292 my $mappings = Koha::BackgroundJob->new->plugin_type_to_class
294 Returns the plugin-refined background jobs types to class mappings.
298 sub plugin_type_to_class {
301 unless ( exists $self->{_plugin_mapping} ) {
302 my @plugins = Koha::Plugins->new()->GetPlugins( { method => 'background_tasks', } );
304 foreach my $plugin (@plugins) {
306 my $tasks = $plugin->background_tasks;
307 my $metadata = $plugin->get_metadata;
309 unless ( $metadata->{namespace} ) {
310 Koha::Logger->get->warn(
311 "The plugin includes the 'background_tasks' method, but doesn't provide the required 'namespace' method ("
317 my $namespace = $metadata->{namespace};
319 foreach my $type ( keys %{$tasks} ) {
320 my $class = $tasks->{$type};
322 # skip if conditions not met
323 next unless $type and $class;
325 my $key = "plugin_$namespace" . "_$type";
327 $self->{_plugin_mapping}->{$key} = $tasks->{$type};
332 return $self->{_plugin_mapping};
340 return 'BackgroundJob';