Bug 28034: Make club enrollment tables in to DataTables
[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     my $job_id;
105     $self->_result->result_source->schema->txn_do(
106         sub {
107             $self->set(
108                 {
109                     status         => 'new',
110                     type           => $job_type,
111                     size           => $job_size,
112                     data           => $json_args,
113                     enqueued_on    => dt_from_string,
114                     borrowernumber => $borrowernumber,
115                 }
116             )->store;
117
118             $job_id = $self->id;
119             $job_args->{job_id} = $job_id;
120             $json_args = encode_json $job_args;
121
122             try {
123                 my $conn = $self->connect;
124                 # This namespace is wrong, it must be a vhost instead.
125                 # But to do so it needs to be created on the server => much more work when a new Koha instance is created.
126                 # Also, here we just want the Koha instance's name, but it's not in the config...
127                 # Picking a random id (memcached_namespace) from the config
128                 my $namespace = C4::Context->config('memcached_namespace');
129                 $conn->send_with_receipt( { destination => sprintf("/queue/%s-%s", $namespace, $job_type), body => $json_args } )
130                   or Koha::Exceptions::Exception->throw('Job has not been enqueued');
131             } catch {
132                 if ( ref($_) eq 'Koha::Exceptions::Exception' ) {
133                     $_->rethrow;
134                 } else {
135                     warn sprintf "The job has not been sent to the message broker: (%s)", $_;
136                 }
137             };
138         }
139     );
140
141     return $job_id;
142 }
143
144 =head3 process
145
146 Process the job!
147
148 =cut
149
150 sub process {
151     my ( $self, $args ) = @_;
152
153     my $job_type = $self->type;
154     return $job_type eq 'batch_biblio_record_modification'
155       ? Koha::BackgroundJob::BatchUpdateBiblio->process($args)
156       : $job_type eq 'batch_authority_record_modification'
157       ? Koha::BackgroundJob::BatchUpdateAuthority->process($args)
158       : Koha::Exceptions::Exception->throw('->process called without valid job_type');
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 $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 $self->data;
197     return $data_dump->{report};
198 }
199
200 =head3 cancel
201
202 Cancel a job.
203
204 =cut
205
206 sub cancel {
207     my ( $self ) = @_;
208     $self->status('cancelled')->store;
209 }
210
211 sub _type {
212     return 'BackgroundJob';
213 }
214
215 1;