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