Bug 32558: (QA follow-up) Leave default to 1, remove extra fork
[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
51 =back
52
53 =cut
54
55 use Modern::Perl;
56 use JSON qw( decode_json );
57 use Try::Tiny;
58 use Pod::Usage;
59 use Getopt::Long;
60 use Parallel::ForkManager;
61
62 use C4::Context;
63 use Koha::Logger;
64 use Koha::BackgroundJobs;
65 use C4::Context;
66
67 my ( $help, @queues );
68
69 my $max_processes = $ENV{MAX_PROCESSES};
70 $max_processes ||= C4::Context->config('background_jobs_worker')->{max_processes} if C4::Context->config('background_jobs_worker');
71 $max_processes ||= 1;
72
73 GetOptions(
74     'm|max-processes=i' => \$max_processes,
75     'h|help' => \$help,
76     'queue=s' => \@queues,
77 ) || pod2usage(1);
78
79
80 pod2usage(0) if $help;
81
82 unless (@queues) {
83     push @queues, 'default';
84 }
85
86 my $conn;
87 try {
88     $conn = Koha::BackgroundJob->connect;
89 } catch {
90     warn sprintf "Cannot connect to the message broker, the jobs will be processed anyway (%s)", $_;
91 };
92
93 my $pm = Parallel::ForkManager->new($max_processes);
94
95 if ( $conn ) {
96     # FIXME cf note in Koha::BackgroundJob about $namespace
97     my $namespace = C4::Context->config('memcached_namespace');
98     for my $queue (@queues) {
99         $conn->subscribe(
100             {
101                 destination      => sprintf( "/queue/%s-%s", $namespace, $queue ),
102                 ack              => 'client',
103                 'prefetch-count' => 1,
104             }
105         );
106     }
107 }
108 while (1) {
109     if ( $conn ) {
110         my $frame = $conn->receive_frame;
111         if ( !defined $frame ) {
112             # maybe log connection problems
113             next;    # will reconnect automatically
114         }
115
116         my $args = try {
117             my $body = $frame->body;
118             decode_json($body); # TODO Should this be from_json? Check utf8 flag.
119         } catch {
120             Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame not processed - %s", $_);
121             return;
122         } finally {
123             $conn->ack( { frame => $frame } );
124         };
125
126         next unless $args;
127
128         # FIXME This means we need to have create the DB entry before
129         # It could work in a first step, but then we will want to handle job that will be created from the message received
130         my $job = Koha::BackgroundJobs->find($args->{job_id});
131
132         unless ( $job ) {
133             Koha::Logger->get({ interface => 'worker' })->warn(sprintf "No job found for id=%s", $args->{job_id});
134             next;
135         }
136
137         $pm->start and next;
138         process_job( $job, $args );
139         $pm->finish;
140
141     } else {
142         my $jobs = Koha::BackgroundJobs->search({ status => 'new', queue => \@queues });
143         while ( my $job = $jobs->next ) {
144             my $args = try {
145                 $job->json->decode($job->data);
146             } catch {
147                 Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Cannot decode data for job id=%s", $job->id);
148                 $job->status('failed')->store;
149                 return;
150             };
151
152             next unless $args;
153
154             $pm->start and next;
155             process_job( $job, { job_id => $job->id, %$args } );
156             $pm->finish;
157
158         }
159         sleep 10;
160     }
161 }
162 $conn->disconnect;
163 $pm->wait_all_children;
164
165 sub process_job {
166     my ( $job, $args ) = @_;
167     try {
168         $job->process( $args );
169     } catch {
170         $job->status('failed')->store;
171     };
172 }