Bug 35819: Add simple delay
[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 GetOptions(
78     'm|max-processes=i' => \$max_processes,
79     'h|help' => \$help,
80     'queue=s' => \@queues,
81 ) || pod2usage(1);
82
83
84 pod2usage(0) if $help;
85
86 unless (@queues) {
87     push @queues, 'default';
88 }
89
90 my $conn;
91 try {
92     $conn = Koha::BackgroundJob->connect;
93 } catch {
94     warn sprintf "Cannot connect to the message broker, the jobs will be processed anyway (%s)", $_;
95 };
96
97 my $pm = Parallel::ForkManager->new($max_processes);
98
99 if ( $conn ) {
100     # FIXME cf note in Koha::BackgroundJob about $namespace
101     my $namespace = C4::Context->config('memcached_namespace');
102     for my $queue (@queues) {
103         $conn->subscribe(
104             {
105                 destination      => sprintf( "/queue/%s-%s", $namespace, $queue ),
106                 ack              => 'client',
107                 'prefetch-count' => 1,
108             }
109         );
110     }
111 }
112 while (1) {
113     if ( $conn ) {
114         my $frame = $conn->receive_frame;
115         if ( !defined $frame ) {
116             # maybe log connection problems
117             next;    # will reconnect automatically
118         }
119
120         my $args = try {
121             my $body = $frame->body;
122             decode_json($body); # TODO Should this be from_json? Check utf8 flag.
123         } catch {
124             Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame not processed - %s", $_);
125             return;
126         };
127
128         my $job;
129
130         if ($args) {
131             $job = Koha::BackgroundJobs->search( { id => $args->{job_id}, status => 'new' } )->next;
132             unless ($job) {
133                 Koha::Logger->get( { interface => 'worker' } )
134                     ->warn( sprintf "Job %s not found, or has wrong status", $args->{job_id} );
135
136                 # nack to force requeue
137                 $conn->nack( { frame => $frame, requeue => 1 } );
138                 Time::HiRes::sleep(0.5);
139                 next;
140             }
141             $conn->ack( { frame => $frame } );
142         } else {
143             next;
144         }
145
146         $pm->start and next;
147         srand();    # ensure each child process begins with a new seed
148         process_job( $job, $args );
149         $pm->finish;
150
151     } else {
152         my $jobs = Koha::BackgroundJobs->search({ status => 'new', queue => \@queues });
153         while ( my $job = $jobs->next ) {
154             my $args = try {
155                 $job->json->decode($job->data);
156             } catch {
157                 Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Cannot decode data for job id=%s", $job->id);
158                 $job->status('failed')->store;
159                 return;
160             };
161
162             next unless $args;
163
164             $pm->start and next;
165             srand();    # ensure each child process begins with a new seed
166             process_job( $job, { job_id => $job->id, %$args } );
167             $pm->finish;
168
169         }
170         sleep 10;
171     }
172 }
173 $conn->disconnect;
174 $pm->wait_all_children;
175
176 sub process_job {
177     my ( $job, $args ) = @_;
178     try {
179         $job->process( $args );
180     } catch {
181         $job->status('failed')->store;
182     };
183 }