Bug 35819: (QA follow-up) Prevent warning on uninitialized retries count
[koha.git] / misc / workers / background_jobs_worker.pl
1 #!/usr/bin/perl
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 =head1 NAME
19
20 background_jobs_worker.pl - Worker script that will process background jobs
21
22 =head1 SYNOPSIS
23
24 ./background_jobs_worker.pl [--queue QUEUE] [-m|--max-processes MAX_PROCESSES]
25
26 =head1 DESCRIPTION
27
28 This script will connect to the Stomp server (RabbitMQ) and subscribe to the queues passed in parameter (or the 'default' queue),
29 or if a Stomp server is not active it will poll the database every 10s for new jobs in the passed queue.
30
31 You can specify some queues only (using --queue, which is repeatable) if you want to run several workers that will handle their own jobs.
32
33 --m --max-processes specifies how many jobs to process simultaneously
34
35 Max processes will be set from the command line option, the environment variable MAX_PROCESSES, or the koha-conf file, in that order of precedence.
36 By default the script will only run one job at a time.
37
38 =head1 OPTIONS
39
40 =over
41
42 =item B<--queue>
43
44 Repeatable. Give the job queues this worker will process.
45
46 The different values available are:
47
48     default
49     long_tasks
50     elastic_index
51
52 =back
53
54 =cut
55
56 use Modern::Perl;
57 use JSON qw( decode_json );
58 use Try::Tiny;
59 use Pod::Usage;
60 use Getopt::Long;
61 use Parallel::ForkManager;
62 use Time::HiRes;
63
64 use C4::Context;
65 use Koha::Logger;
66 use Koha::BackgroundJobs;
67 use C4::Context;
68
69 $SIG{'PIPE'} = 'IGNORE';    # See BZ 35111; added to ignore PIPE error when connection lost on Ubuntu.
70
71 my ( $help, @queues );
72
73 my $max_processes = $ENV{MAX_PROCESSES};
74 $max_processes ||= C4::Context->config('background_jobs_worker')->{max_processes} if C4::Context->config('background_jobs_worker');
75 $max_processes ||= 1;
76
77 my $not_found_retries = {};
78 my $max_retries = $ENV{MAX_RETRIES} || 10;
79
80 GetOptions(
81     'm|max-processes=i' => \$max_processes,
82     'h|help' => \$help,
83     'queue=s' => \@queues,
84 ) || pod2usage(1);
85
86
87 pod2usage(0) if $help;
88
89 unless (@queues) {
90     push @queues, 'default';
91 }
92
93 my $conn;
94 try {
95     $conn = Koha::BackgroundJob->connect;
96 } catch {
97     warn sprintf "Cannot connect to the message broker, the jobs will be processed anyway (%s)", $_;
98 };
99
100 my $pm = Parallel::ForkManager->new($max_processes);
101
102 if ( $conn ) {
103     # FIXME cf note in Koha::BackgroundJob about $namespace
104     my $namespace = C4::Context->config('memcached_namespace');
105     for my $queue (@queues) {
106         $conn->subscribe(
107             {
108                 destination      => sprintf( "/queue/%s-%s", $namespace, $queue ),
109                 ack              => 'client',
110                 'prefetch-count' => 1,
111             }
112         );
113     }
114 }
115 while (1) {
116     if ( $conn ) {
117         my $frame = $conn->receive_frame;
118         if ( !defined $frame ) {
119             # maybe log connection problems
120             next;    # will reconnect automatically
121         }
122
123         my $args = try {
124             my $body = $frame->body;
125             decode_json($body); # TODO Should this be from_json? Check utf8 flag.
126         } catch {
127             Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame not processed - %s", $_);
128             return;
129         };
130
131         unless ( $args ) {
132             Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame does not have correct args, ignoring it");
133             $conn->nack( { frame => $frame, requeue => 'false' } );
134             next;
135         }
136
137         my $job = Koha::BackgroundJobs->find( $args->{job_id} );
138
139         if ( $job && $job->status ne 'new' ) {
140             Koha::Logger->get( { interface => 'worker' } )
141                 ->warn( sprintf "Job %s has wrong status %s", $args->{job_id}, $job->status );
142
143             # nack without requeue, we do not want to process this frame again
144             $conn->nack( { frame => $frame, requeue => 'false' } );
145             next;
146         }
147
148         unless ($job) {
149             $not_found_retries->{ $args->{job_id} } //= 0;
150             if ( ++$not_found_retries->{ $args->{job_id} } >= $max_retries ) {
151                 Koha::Logger->get( { interface => 'worker' } )
152                     ->warn( sprintf "Job %s not found, no more retry", $args->{job_id} );
153
154                 # nack without requeue, we do not want to process this frame again
155                 $conn->nack( { frame => $frame, requeue => 'false' } );
156                 next;
157             }
158
159             Koha::Logger->get( { interface => 'worker' } )
160                 ->debug( sprintf "Job %s not found, will retry later", $args->{job_id} );
161
162             # nack to force requeue
163             $conn->nack( { frame => $frame, requeue => 'true' } );
164             Time::HiRes::sleep(0.5);
165             next;
166         }
167         $conn->ack( { frame => $frame } );
168
169         $pm->start and next;
170         srand();    # ensure each child process begins with a new seed
171         process_job( $job, $args );
172         $pm->finish;
173
174     } else {
175         my $jobs = Koha::BackgroundJobs->search({ status => 'new', queue => \@queues });
176         while ( my $job = $jobs->next ) {
177             my $args = try {
178                 $job->json->decode($job->data);
179             } catch {
180                 Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Cannot decode data for job id=%s", $job->id);
181                 $job->status('failed')->store;
182                 return;
183             };
184
185             next unless $args;
186
187             $pm->start and next;
188             srand();    # ensure each child process begins with a new seed
189             process_job( $job, { job_id => $job->id, %$args } );
190             $pm->finish;
191
192         }
193         sleep 10;
194     }
195 }
196 $conn->disconnect;
197 $pm->wait_all_children;
198
199 sub process_job {
200     my ( $job, $args ) = @_;
201     try {
202         $job->process( $args );
203     } catch {
204         $job->status('failed')->store;
205     };
206 }