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