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