Bug 32482: (follow-up) Add markup comments
[koha.git] / misc / 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]
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 =head1 OPTIONS
34
35 =over
36
37 =item B<--queue>
38
39 Repeatable. Give the job queues this worker will process.
40
41 The different values available are:
42
43     default
44     long_tasks
45
46 =back
47
48 =cut
49
50 use Modern::Perl;
51 use JSON qw( decode_json );
52 use Try::Tiny;
53 use Pod::Usage;
54 use Getopt::Long;
55
56 use Koha::Logger;
57 use Koha::BackgroundJobs;
58
59 my ( $help, @queues );
60 GetOptions(
61     'h|help' => \$help,
62     'queue=s' => \@queues,
63 ) || pod2usage(1);
64
65 pod2usage(0) if $help;
66
67 unless (@queues) {
68     push @queues, 'default';
69 }
70
71 my $conn;
72 try {
73     $conn = Koha::BackgroundJob->connect;
74 } catch {
75     warn sprintf "Cannot connect to the message broker, the jobs will be processed anyway (%s)", $_;
76 };
77
78 if ( $conn ) {
79     # FIXME cf note in Koha::BackgroundJob about $namespace
80     my $namespace = C4::Context->config('memcached_namespace');
81     for my $queue (@queues) {
82         $conn->subscribe({
83             destination => sprintf("/queue/%s-%s", $namespace, $queue),
84             ack => 'client',
85             'prefetch-count' => 1,
86         });
87     }
88 }
89 while (1) {
90     if ( $conn ) {
91         my $frame = $conn->receive_frame;
92         if ( !defined $frame ) {
93             # maybe log connection problems
94             next;    # will reconnect automatically
95         }
96
97         my $args = try {
98             my $body = $frame->body;
99             decode_json($body); # TODO Should this be from_json? Check utf8 flag.
100         } catch {
101             Koha::Logger->get->warn(sprintf "Frame not processed - %s", $_);
102             return;
103         } finally {
104             $conn->ack( { frame => $frame } );
105         };
106
107         next unless $args;
108
109         # FIXME This means we need to have create the DB entry before
110         # It could work in a first step, but then we will want to handle job that will be created from the message received
111         my $job = Koha::BackgroundJobs->find($args->{job_id});
112
113         unless ( $job ) {
114             Koha::Logger->get->warn(sprintf "No job found for id=%s", $args->{job_id});
115             next;
116         }
117
118         process_job( $job, $args );
119
120     } else {
121         my $jobs = Koha::BackgroundJobs->search({ status => 'new', queue => \@queues });
122         while ( my $job = $jobs->next ) {
123             my $args = try {
124                 $job->json->decode($job->data);
125             } catch {
126                 Koha::Logger->get->warn(sprintf "Cannot decode data for job id=%s", $job->id);
127                 $job->status('failed')->store;
128                 return;
129             };
130
131             next unless $args;
132
133             process_job( $job, { job_id => $job->id, %$args } );
134
135         }
136         sleep 10;
137     }
138 }
139 $conn->disconnect;
140
141 sub process_job {
142     my ( $job, $args ) = @_;
143
144     my $pid;
145     if ( $pid = fork ) {
146         wait;
147         return;
148     }
149
150     die "fork failed!" unless defined $pid;
151
152     try {
153         $job->process( $args );
154     } catch {
155         $job->status('failed')->store;
156     };
157
158     exit;
159 }