Bug 29407: Make the pickup locations dropdown JS reusable
[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
101     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
102     my $json_args = encode_json $job_args;
103     my $job_id;
104     $self->_result->result_source->schema->txn_do(
105         sub {
106             $self->set(
107                 {
108                     status         => 'new',
109                     type           => $job_type,
110                     size           => $job_size,
111                     data           => $json_args,
112                     enqueued_on    => dt_from_string,
113                     borrowernumber => $borrowernumber,
114                 }
115             )->store;
116
117             $job_id = $self->id;
118             $job_args->{job_id} = $job_id;
119             $json_args = encode_json $job_args;
120
121             try {
122                 my $conn = $self->connect;
123                 # This namespace is wrong, it must be a vhost instead.
124                 # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
125                 # Also, here we just want the Koha instance's name, but it's not in the config...
126                 # Picking a random id (memcached_namespace) from the config
127                 my $namespace = C4::Context->config('memcached_namespace');
128                 $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_type), body => $json_args } )
129                   or Koha::Exceptions::Exception->throw('Job has not been enqueued');
130             } catch {
131                 if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
132                     $_->rethrow;
133                 } else {
134                     warn sprintf "The job has not been sent to the message broker: (%s)", $_;
135                 }
136             };
137         }
138     );
139
140     return $job_id;
141 }
142
143 =head3 process
144
145 Process the job!
146
147 =cut
148
149 sub process {
150     my ( $self, $args ) = @_;
151
152     return {} if ref($self) ne 'Koha::BackgroundJob';
153
154     my $derived_class = $self->_derived_class;
155
156     $args ||= {};
157
158     return $derived_class->process({job_id => $self->id, %$args});
159 }
160
161 =head3 job_type
162
163 Return the job type of the job. Must be a string.
164
165 =cut
166
167 sub job_type { croak "This method must be subclassed" }
168
169 =head3 messages
170
171 Messages let during the processing of the job.
172
173 =cut
174
175 sub messages {
176     my ( $self ) = @_;
177
178     my @messages;
179     my $data_dump = decode_json encode_utf8 $self->data;
180     if ( exists $data_dump->{messages} ) {
181         @messages = @{ $data_dump->{messages} };
182     }
183
184     return \@messages;
185 }
186
187 =head3 report
188
189 Report of the job.
190
191 =cut
192
193 sub report {
194     my ( $self ) = @_;
195
196     my $data_dump = decode_json encode_utf8 $self->data;
197     return $data_dump->{report} || {};
198 }
199
200 =head3 additional_report
201
202 Build additional variables for the job detail view.
203
204 =cut
205
206 sub additional_report {
207     my ( $self ) = @_;
208
209     return {} if ref($self) ne 'Koha::BackgroundJob';
210
211     my $derived_class = $self->_derived_class;
212
213     return $derived_class->additional_report({job_id => $self->id});
214 }
215
216 =head3 cancel
217
218 Cancel a job.
219
220 =cut
221
222 sub cancel {
223     my ( $self ) = @_;
224     $self->status('cancelled')->store;
225 }
226
227 =head2 Internal methods
228
229 =head3 _derived_class
230
231 =cut
232
233 sub _derived_class {
234     my ( $self ) = @_;
235     my $job_type = $self->type;
236
237     my $class = $self->type_to_class_mapping->{$job_type};
238
239     Koha::Exceptions::Exception->throw($job_type . ' is not a valid job_type')
240         unless $class;
241
242     eval "require $class";
243     return $class->new;
244 }
245
246 =head3 type_to_class_mapping
247
248 =cut
249
250 sub type_to_class_mapping {
251     return {
252         batch_authority_record_deletion     => 'Koha::BackgroundJob::BatchDeleteAuthority',
253         batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
254         batch_biblio_record_deletion        => 'Koha::BackgroundJob::BatchDeleteBiblio',
255         batch_biblio_record_modification    => 'Koha::BackgroundJob::BatchUpdateBiblio',
256         batch_item_record_deletion          => 'Koha::BackgroundJob::BatchDeleteItem',
257         batch_item_record_modification      => 'Koha::BackgroundJob::BatchUpdateItem',
258         batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
259     };
260 }
261
262 =head3 _type
263
264 =cut
265
266 sub _type {
267     return 'BackgroundJob';
268 }
269
270 1;