Bug 29374: Don't crash if search engine returns a deleted record
[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( encode_json decode_json );
20 use Carp qw( croak );
21 use Net::Stomp;
22 use Try::Tiny;
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
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
102     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
103     my $json_args = encode_json $job_args;
104
105     $self->set(
106         {
107             status         => 'new',
108             type           => $job_type,
109             size           => $job_size,
110             data           => $json_args,
111             enqueued_on    => dt_from_string,
112             borrowernumber => $borrowernumber,
113         }
114     )->store;
115
116     $job_args->{job_id} = $self->id;
117
118     my $conn;
119     try {
120         $conn = $self->connect;
121     } catch {
122         warn "Cannot connect to broker " . $_;
123     };
124     return unless $conn;
125
126     $json_args = encode_json $job_args;
127     try {
128         # This namespace is wrong, it must be a vhost instead.
129         # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
130         # Also, here we just want the Koha instance's name, but it's not in the config...
131         # Picking a random id (memcached_namespace) from the config
132         my $namespace = C4::Context->config('memcached_namespace');
133         $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_type), body => $json_args } )
134           or Koha::Exceptions::Exception->throw('Job has not been enqueued');
135     } catch {
136         $self->status('failed')->store;
137         if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
138             $_->rethrow;
139         } else {
140             warn sprintf "The job has not been sent to the message broker: (%s)", $_;
141         }
142     };
143
144     return $self->id;
145 }
146
147 =head3 process
148
149 Process the job!
150
151 =cut
152
153 sub process {
154     my ( $self, $args ) = @_;
155
156     my $job_type = $self->type;
157     return $job_type eq 'batch_biblio_record_modification'
158       ? Koha::BackgroundJob::BatchUpdateBiblio->process($args)
159       : $job_type eq 'batch_authority_record_modification'
160       ? Koha::BackgroundJob::BatchUpdateAuthority->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;