Bug 30477: Add new UNIMARC installer translation files
[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::Plugins;
29
30 use base qw( Koha::Object );
31
32 =head1 NAME
33
34 Koha::BackgroundJob - Koha BackgroundJob Object class
35
36 This is a base class for BackgroundJob, some methods must be subclassed.
37
38 Example of usage:
39
40 Producer:
41 my $job_id = Koha::BackgroundJob->enqueue(
42     {
43         job_type => $job_type,
44         job_size => $job_size,
45         job_args => $job_args
46     }
47 );
48
49 Consumer:
50 Koha::BackgrounJobs->find($job_id)->process;
51 See also C<misc/background_jobs_worker.pl> for a full example
52
53 =head1 API
54
55 =head2 Class methods
56
57 =head3 connect
58
59 Connect to the message broker using default guest/guest credential
60
61 =cut
62
63 sub connect {
64     my ( $self );
65     my $hostname = 'localhost';
66     my $port = '61613';
67     my $config = C4::Context->config('message_broker');
68     my $credentials = {
69         login => 'guest',
70         passcode => 'guest',
71     };
72     if ($config){
73         $hostname = $config->{hostname} if $config->{hostname};
74         $port = $config->{port} if $config->{port};
75         $credentials->{login} = $config->{username} if $config->{username};
76         $credentials->{passcode} = $config->{password} if $config->{password};
77         $credentials->{host} = $config->{vhost} if $config->{vhost};
78     }
79     my $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } );
80     $stomp->connect( $credentials );
81     return $stomp;
82 }
83
84 =head3 enqueue
85
86 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.
87
88 C<job_size> is the size of the job
89 C<job_args> is the arguments of the job. It's a structure that will be JSON encoded.
90
91 Return the job_id of the newly created job.
92
93 =cut
94
95 sub enqueue {
96     my ( $self, $params ) = @_;
97
98     my $job_type = $self->job_type;
99     my $job_size = $params->{job_size};
100     my $job_args = $params->{job_args};
101     my $job_queue = $params->{job_queue} // 'default';
102
103     my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef;
104     my $json_args = encode_json $job_args;
105
106     $self->set(
107         {
108             status         => 'new',
109             type           => $job_type,
110             queue          => $job_queue,
111             size           => $job_size,
112             data           => $json_args,
113             enqueued_on    => dt_from_string,
114             borrowernumber => $borrowernumber,
115         }
116     )->store;
117
118     $job_args->{job_id} = $self->id;
119
120     my $conn;
121     try {
122         $conn = $self->connect;
123     } catch {
124         warn "Cannot connect to broker " . $_;
125     };
126     return unless $conn;
127
128     $json_args = encode_json $job_args;
129     try {
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_queue), body => $json_args } )
136           or Koha::Exceptions::Exception->throw('Job has not been enqueued');
137     } catch {
138         $self->status('failed')->store;
139         if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
140             $_->rethrow;
141         } else {
142             warn sprintf "The job has not been sent to the message broker: (%s)", $_;
143         }
144     };
145
146     return $self->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( $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 encode_utf8 $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 encode_utf8 $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;
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::Exception->throw($job_type . ' is not a valid job_type')
246         unless $class;
247
248     eval "require $class";
249     return $class->_new_from_dbic( $self->_result );
250 }
251
252 =head3 type_to_class_mapping
253
254     my $mapping = Koha::BackgrounJob->new->type_to_class_mapping;
255
256 Returns the available types to class mappings.
257
258 =cut
259
260 sub type_to_class_mapping {
261     my ($self) = @_;
262
263     my $plugins_mapping = $self->plugin_types_to_classes;
264
265     return ($plugins_mapping)
266       ? { %{ $self->core_types_to_classes }, %$plugins_mapping }
267       : $self->core_types_to_classes;
268 }
269
270 =head3 core_types_to_classes
271
272     my $mappings = Koha::BackgrounJob->new->core_types_to_classes
273
274 Returns the core background jobs types to class mappings.
275
276 =cut
277
278 sub core_types_to_classes {
279     return {
280         batch_authority_record_deletion     => 'Koha::BackgroundJob::BatchDeleteAuthority',
281         batch_authority_record_modification => 'Koha::BackgroundJob::BatchUpdateAuthority',
282         batch_biblio_record_deletion        => 'Koha::BackgroundJob::BatchDeleteBiblio',
283         batch_biblio_record_modification    => 'Koha::BackgroundJob::BatchUpdateBiblio',
284         batch_item_record_deletion          => 'Koha::BackgroundJob::BatchDeleteItem',
285         batch_item_record_modification      => 'Koha::BackgroundJob::BatchUpdateItem',
286         batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
287     };
288 }
289
290 =head3 plugin_types_to_classes
291
292     my $mappings = Koha::BackgroundJob->new->plugin_types_to_classes
293
294 Returns the plugin-defined background jobs types to class mappings.
295
296 =cut
297
298 sub plugin_types_to_classes {
299     my ($self) = @_;
300
301     unless ( exists $self->{_plugin_mapping} ) {
302         my @plugins = Koha::Plugins->new()->GetPlugins( { method => 'background_tasks', } );
303
304         foreach my $plugin (@plugins) {
305
306             my $tasks    = $plugin->background_tasks;
307             my $metadata = $plugin->get_metadata;
308
309             unless ( $metadata->{namespace} ) {
310                 Koha::Logger->get->warn(
311                         q{A plugin includes the 'background_tasks' method, }
312                       . q{but doesn't provide the required 'namespace' }
313                       . qq{method ($plugin->{class})} );
314                 next;
315             }
316
317             my $namespace = $metadata->{namespace};
318
319             foreach my $type ( keys %{$tasks} ) {
320                 my $class = $tasks->{$type};
321
322                 # skip if conditions not met
323                 next unless $type and $class;
324
325                 my $key = "plugin_$namespace" . "_$type";
326
327                 $self->{_plugin_mapping}->{$key} = $tasks->{$type};
328             }
329         }
330     }
331
332     return $self->{_plugin_mapping};
333 }
334
335 =head3 _type
336
337 =cut
338
339 sub _type {
340     return 'BackgroundJob';
341 }
342
343 1;