Bug 22417: Add the ability to cancel a job
[koha.git] / Koha / BackgroundJob.pm
1 package Koha::BackgroundJob;
2
3 use Modern::Perl;
4 use JSON qw( encode_json decode_json );
5 use Carp qw( croak );
6 use Net::RabbitFoot;
7
8 use C4::Context;
9 use Koha::DateUtils qw( dt_from_string );
10 use Koha::BackgroundJobs;
11
12 use base qw( Koha::Object );
13
14 sub connect {
15     my ( $self );
16     my $conn = Net::RabbitFoot->new()->load_xml_spec()->connect(
17         host => 'localhost', # TODO Move this to KOHA_CONF
18         port => 5672,
19         user => 'guest',
20         pass => 'guest',
21         vhost => '/',
22     );
23
24     return $conn;
25 }
26
27 sub enqueue {
28     my ( $self, $params ) = @_;
29
30     my $job_type = $params->{job_type};
31     my $job_size = $params->{job_size};
32     my $job_args = $params->{job_args};
33
34     my $json_args = encode_json $job_args;
35     $self->set({
36         status => 'new',
37         type => $job_type,
38         size => $job_size,
39         data => $json_args,
40         enqueued_on => dt_from_string,
41         borrowernumber => C4::Context->userenv->{id}, # FIXME Handle non GUI calls
42     })->store;
43
44     my $job_id = $self->id;
45     $job_args->{job_id} = $job_id;
46     $json_args = encode_json $job_args,
47
48     my $conn = $self->connect;
49     my $channel = $conn->open_channel();
50
51     $channel->declare_queue(
52         queue => $job_type,
53         durable => 1,
54     );
55
56     $channel->publish(
57         exchange => '',
58         routing_key => $job_type, # TODO Must be different?
59         body => $json_args,
60     );
61     $conn->close;
62     return $job_id;
63 }
64
65 sub process { croak "This method must be subclassed" }
66
67 sub messages {
68     my ( $self ) = @_;
69
70     my @messages;
71     my $data_dump = decode_json $self->data;
72     if ( exists $data_dump->{messages} ) {
73         @messages = @{ $data_dump->{messages} };
74     }
75
76     return @messages;
77 }
78
79 sub report {
80     my ( $self ) = @_;
81
82     my $data_dump = decode_json $self->data;
83     return $data_dump->{report};
84 }
85
86 sub cancel {
87     my ( $self ) = @_;
88     $self->status('cancelled')->store;
89 }
90
91 sub _type {
92     return 'BackgroundJob';
93 }
94
95 1;