Bug 27783: Replace --job-type by --queue
[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
29 use base qw( Koha::Object );
30
31 =head1 NAME
32
33 Koha::BackgroundJob - Koha BackgroundJob Object class
34
35 This is a base class for BackgroundJob, some methods must be subclassed.
36
37 Example of usage:
38
39 Producer:
40 my $job_id = Koha::BackgroundJob->enqueue(
41     {
42         job_type => $job_type,
43         job_size => $job_size,
44         job_args => $job_args
45     }
46 );
47
48 Consumer:
49 Koha::BackgrounJobs->find($job_id)->process;
50 See also C<misc/background_jobs_worker.pl> for a full example
51
52 =head1 API
53
54 =head2 Class methods
55
56 =head3 connect
57
58 Connect to the message broker using default guest/guest credential
59
60 =cut
61
62 sub connect {
63     my ( $self );
64     my $hostname = 'localhost';
65     my $port = '61613';
66     my $config = C4::Context->config('message_broker');
67     my $credentials = {
68         login => 'guest',
69         passcode => 'guest',
70     };
71     if ($config){
72         $hostname = $config->{hostname} if $config->{hostname};
73         $port = $config->{port} if $config->{port};
74         $credentials->{login} = $config->{username} if $config->{username};
75         $credentials->{passcode} = $config->{password} if $config->{password};
76         $credentials->{host} = $config->{vhost} if $config->{vhost};
77     }
78     my $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } );
79     $stomp->connect( $credentials );
80     return $stomp;
81 }
82
83 =head3 enqueue
84
85 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.
86
87 C<job_size> is the size of the job
88 C<job_args> is the arguments of the job. It's a structure that will be JSON encoded.
89
90 Return the job_id of the newly created job.
91
92 =cut
93
94 sub enqueue {
95     my ( $self, $params ) = @_;
96
97     my $job_type = $self->job_type;
98     my $job_size = $params->{job_size};
99     my $job_args = $params->{job_args};
100     my $job_queue = $params->{job_queue} // 'default';
101
102     my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef;
103     my $json_args = encode_json $job_args;
104
105     $self->set(
106         {
107             status         => 'new',
108             type           => $job_type,
109             queue          => $job_queue,
110             size           => $job_size,
111             data           => $json_args,
112             enqueued_on    => dt_from_string,
113             borrowernumber => $borrowernumber,
114         }
115     )->store;
116
117     $job_args->{job_id} = $self->id;
118
119     my $conn;
120     try {
121         $conn = $self->connect;
122     } catch {
123         warn "Cannot connect to broker " . $_;
124     };
125     return unless $conn;
126
127     $json_args = encode_json $job_args;
128     try {
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_queue), body => $json_args } )
135           or Koha::Exceptions::Exception->throw('Job has not been enqueued');
136     } catch {
137         $self->status('failed')->store;
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     return $self->id;
146 }
147
148 =head3 process
149
150 Process the job!
151
152 =cut
153
154 sub process {
155     my ( $self, $args ) = @_;
156
157     return {} if ref($self) ne 'Koha::BackgroundJob';
158
159     my $derived_class = $self->_derived_class;
160
161     $args ||= {};
162
163     return $derived_class->process( $args );
164 }
165
166 =head3 job_type
167
168 Return the job type of the job. Must be a string.
169
170 =cut
171
172 sub job_type { croak "This method must be subclassed" }
173
174 =head3 messages
175
176 Messages let during the processing of the job.
177
178 =cut
179
180 sub messages {
181     my ( $self ) = @_;
182
183     my @messages;
184     my $data_dump = decode_json encode_utf8 $self->data;
185     if ( exists $data_dump->{messages} ) {
186         @messages = @{ $data_dump->{messages} };
187     }
188
189     return \@messages;
190 }
191
192 =head3 report
193
194 Report of the job.
195
196 =cut
197
198 sub report {
199     my ( $self ) = @_;
200
201     my $data_dump = decode_json encode_utf8 $self->data;
202     return $data_dump->{report} || {};
203 }
204
205 =head3 additional_report
206
207 Build additional variables for the job detail view.
208
209 =cut
210
211 sub additional_report {
212     my ( $self ) = @_;
213
214     return {} if ref($self) ne 'Koha::BackgroundJob';
215
216     my $derived_class = $self->_derived_class;
217
218     return $derived_class->additional_report;
219 }
220
221 =head3 cancel
222
223 Cancel a job.
224
225 =cut
226
227 sub cancel {
228     my ( $self ) = @_;
229     $self->status('cancelled')->store;
230 }
231
232 =head2 Internal methods
233
234 =head3 _derived_class
235
236 =cut
237
238 sub _derived_class {
239     my ( $self ) = @_;
240     my $job_type = $self->type;
241
242     my $class = $self->type_to_class_mapping->{$job_type};
243
244     Koha::Exception->throw($job_type . ' is not a valid job_type')
245         unless $class;
246
247     eval "require $class";
248     return $class->_new_from_dbic( $self->_result );
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;