Bug 28445: Use the task queue for the batch delete and update items tool
[srvgit] / 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 Carp qw( croak );
21 use Net::Stomp;
22 use Try::Tiny qw( catch try );
23
24 use C4::Context;
25 use Koha::DateUtils qw( dt_from_string );
26 use Koha::Exceptions;
27 use Koha::BackgroundJob::BatchUpdateBiblio;
28 use Koha::BackgroundJob::BatchUpdateAuthority;
29 use Koha::BackgroundJob::BatchUpdateItem;
30 use Koha::BackgroundJob::BatchDeleteBiblio;
31 use Koha::BackgroundJob::BatchDeleteAuthority;
32 use Koha::BackgroundJob::BatchDeleteItem;
33 use Koha::BackgroundJob::BatchCancelHold;
34
35 use base qw( Koha::Object );
36
37 =head1 NAME
38
39 Koha::BackgroundJob - Koha BackgroundJob Object class
40
41 This is a base class for BackgroundJob, some methods must be subclassed.
42
43 Example of usage:
44
45 Producer:
46 my $job_id = Koha::BackgroundJob->enqueue(
47     {
48         job_type => $job_type,
49         job_size => $job_size,
50         job_args => $job_args
51     }
52 );
53
54 Consumer:
55 Koha::BackgrounJobs->find($job_id)->process;
56 See also C<misc/background_jobs_worker.pl> for a full example
57
58 =head1 API
59
60 =head2 Class methods
61
62 =head3 connect
63
64 Connect to the message broker using default guest/guest credential
65
66 =cut
67
68 sub connect {
69     my ( $self );
70     my $hostname = 'localhost';
71     my $port = '61613';
72     my $config = C4::Context->config('message_broker');
73     my $credentials = {
74         login => 'guest',
75         passcode => 'guest',
76     };
77     if ($config){
78         $hostname = $config->{hostname} if $config->{hostname};
79         $port = $config->{port} if $config->{port};
80         $credentials->{login} = $config->{username} if $config->{username};
81         $credentials->{passcode} = $config->{password} if $config->{password};
82         $credentials->{host} = $config->{vhost} if $config->{vhost};
83     }
84     my $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } );
85     $stomp->connect( $credentials );
86     return $stomp;
87 }
88
89 =head3 enqueue
90
91 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.
92
93 C<job_size> is the size of the job
94 C<job_args> is the arguments of the job. It's a structure that will be JSON encoded.
95
96 Return the job_id of the newly created job.
97
98 =cut
99
100 sub enqueue {
101     my ( $self, $params ) = @_;
102
103     my $job_type = $self->job_type;
104     my $job_size = $params->{job_size};
105     my $job_args = $params->{job_args};
106
107     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
108     my $json_args = encode_json $job_args;
109     my $job_id;
110     $self->_result->result_source->schema->txn_do(
111         sub {
112             $self->set(
113                 {
114                     status         => 'new',
115                     type           => $job_type,
116                     size           => $job_size,
117                     data           => $json_args,
118                     enqueued_on    => dt_from_string,
119                     borrowernumber => $borrowernumber,
120                 }
121             )->store;
122
123             $job_id = $self->id;
124             $job_args->{job_id} = $job_id;
125             $json_args = encode_json $job_args;
126
127             try {
128                 my $conn = $self->connect;
129                 # This namespace is wrong, it must be a vhost instead.
130                 # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
131                 # Also, here we just want the Koha instance's name, but it's not in the config...
132                 # Picking a random id (memcached_namespace) from the config
133                 my $namespace = C4::Context->config('memcached_namespace');
134                 $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_type), body => $json_args } )
135                   or Koha::Exceptions::Exception->throw('Job has not been enqueued');
136             } catch {
137                 if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
138                     $_->rethrow;
139                 } else {
140                     warn sprintf "The job has not been sent to the message broker: (%s)", $_;
141                 }
142             };
143         }
144     );
145
146     return $job_id;
147 }
148
149 =head3 process
150
151 Process the job!
152
153 =cut
154
155 sub process {
156     my ( $self, $args ) = @_;
157
158     return {} if ref($self) ne 'Koha::BackgroundJob';
159
160     my $derived_class = $self->_derived_class;
161
162     $args ||= {};
163
164     return $derived_class->process({job_id => $self->id, %$args});
165 }
166
167 =head3 job_type
168
169 Return the job type of the job. Must be a string.
170
171 =cut
172
173 sub job_type { croak "This method must be subclassed" }
174
175 =head3 messages
176
177 Messages let during the processing of the job.
178
179 =cut
180
181 sub messages {
182     my ( $self ) = @_;
183
184     my @messages;
185     my $data_dump = decode_json $self->data;
186     if ( exists $data_dump->{messages} ) {
187         @messages = @{ $data_dump->{messages} };
188     }
189
190     return \@messages;
191 }
192
193 =head3 report
194
195 Report of the job.
196
197 =cut
198
199 sub report {
200     my ( $self ) = @_;
201
202     my $data_dump = decode_json $self->data;
203     return $data_dump->{report} || {};
204 }
205
206 =head3 additional_report
207
208 Build additional variables for the job detail view.
209
210 =cut
211
212 sub additional_report {
213     my ( $self ) = @_;
214
215     return {} if ref($self) ne 'Koha::BackgroundJob';
216
217     my $derived_class = $self->_derived_class;
218
219     return $derived_class->additional_report({job_id => $self->id});
220 }
221
222 =head3 cancel
223
224 Cancel a job.
225
226 =cut
227
228 sub cancel {
229     my ( $self ) = @_;
230     $self->status('cancelled')->store;
231 }
232
233 =head2 Internal methods
234
235 =head3 _derived_class
236
237 =cut
238
239 sub _derived_class {
240     my ( $self ) = @_;
241     my $job_type = $self->type;
242
243     my $class = $self->type_to_class_mapping->{$job_type};
244
245     Koha::Exceptions::Exception->throw($job_type . ' is not a valid job_type')
246         unless $class;
247
248     return $class->new;
249 }
250
251 =head3 type_to_class_mapping
252
253 =cut
254
255 sub type_to_class_mapping {
256     return {
257         batch_authority_record_deletion     => 'Koha::BackgroundJob::BatchDeleteAuthority',
258         batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
259         batch_biblio_record_deletion        => 'Koha::BackgroundJob::BatchDeleteBiblio',
260         batch_biblio_record_modification    => 'Koha::BackgroundJob::BatchUpdateBiblio',
261         batch_item_record_deletion          => 'Koha::BackgroundJob::BatchDeleteItem',
262         batch_item_record_modification      => 'Koha::BackgroundJob::BatchUpdateItem',
263         batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
264     };
265 }
266
267 =head3 _type
268
269 =cut
270
271 sub _type {
272     return 'BackgroundJob';
273 }
274
275 1;