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