This file is indexed.

/usr/share/perl5/FCM/Util/TaskRunner.pm is in fcm 2017.10.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# ------------------------------------------------------------------------------
# (C) British Crown Copyright 2006-17 Met Office.
#
# This file is part of FCM, tools for managing and building source code.
#
# FCM is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FCM is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FCM. If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------------
use strict;
use warnings;
# ------------------------------------------------------------------------------
package FCM::Util::TaskRunner;
use base qw{FCM::Class::CODE};

my $P = 'FCM::Util::TaskRunner::Parallel';
my $S = 'FCM::Util::TaskRunner::Serial';

__PACKAGE__->class({util => '&'}, {action_of => {main => \&_main}});

sub _main {
    my ($attrib_ref, $action_ref, $n_workers) = @_;
    $n_workers ||= 1;
    my $class = $n_workers > 1 ? $P : $S;
    $attrib_ref->{runner} = $class->new({
        action    => $action_ref,
        n_workers => $n_workers,
        util      => $attrib_ref->{util},
    });
}

# ------------------------------------------------------------------------------
package FCM::Util::TaskRunner::Serial;
use base qw{FCM::Class::CODE};

__PACKAGE__->class(
    {action => '&', util => '&'},
    {action_of => {destroy => sub {}, main => \&_main}},
);

sub _main {
    my ($attrib_ref, $get_ref, $put_ref) = @_;
    my $n_done = 0;
    while (my $task = $get_ref->()) {
        my $timer = $attrib_ref->{util}->timer();
        eval {
            $task->set_state($task->ST_WORKING);
            $attrib_ref->{action}->($task->get_ctx());
            $task->set_state($task->ST_OK);
        };
        if ($@) {
            $task->set_error($@);
            $task->set_state($task->ST_FAILED);
        }
        $task->set_elapse($timer->());
        $put_ref->($task);
        ++$n_done;
    }
    $n_done;
}

# ------------------------------------------------------------------------------
package FCM::Util::TaskRunner::Parallel;
use base qw{FCM::Class::CODE};

use FCM::Context::Event;
use IO::Select;
use IO::Socket;
use List::Util qw{first};
use POSIX qw{WNOHANG};
use Socket qw{AF_UNIX SOCK_STREAM PF_UNSPEC};
use Storable qw{freeze thaw};

# Package name of worker event and state
my $CTX_EVENT = 'FCM::Context::Event';
my $CTX_STATE = 'FCM::Util::TaskRunner::WorkerState';

# Length of a packed long integer
my $LEN_OF_LONG = length(pack('N', 0));

# Time out for polling sockets to child processes
my $TIME_OUT = 0.05;

# Creates the class.
__PACKAGE__->class(
    {   action        => '&',
        n_workers     => '$',
        worker_states => '@',
        util          => '&',
    },
    {init => \&_init, action_of => {destroy => \&_destroy, main => \&_main}},
);

# Destroys the child processes.
sub _destroy {
    my $attrib_ref = shift();
    local($SIG{CHLD}) = 'IGNORE';
    my $select = IO::Select->new();
    my @worker_states = @{$attrib_ref->{worker_states}};
    for my $worker_state (@worker_states) {
        $select->add($worker_state->get_socket());
    }
    # TBD: reads $socket for any left over event etc?
    for my $socket ($select->can_write(0)) {
        my $worker_state = first {$_->get_socket() eq $socket} @worker_states;
        _item_send($socket);
        close($socket);
        waitpid($worker_state->get_pid(), 0);
    }
    while (waitpid(-1, WNOHANG) > 0) {
    }
    $attrib_ref->{util}->event(
        FCM::Context::Event->TASK_WORKERS, 'destroy', $attrib_ref->{n_workers},
    );
    1;
}

# On initialisation.
sub _init {
    my $attrib_ref = shift();
    for my $i (1 .. $attrib_ref->{n_workers}) {
        my ($from_boss, $from_worker)
            = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
        if (!defined($from_boss) || !defined($from_worker)) {
            die("socketpair: $!");
        }
        $from_worker->autoflush(1);
        $from_boss->autoflush(1);
        if (my $pid = fork()) {
            # I am the boss
            if ($pid < 0) {
                die("fork: $!");
            }
            local($SIG{CHLD}, $SIG{INT}, $SIG{KILL}, $SIG{TERM}, $SIG{XCPU});
            for my $key (qw{CHLD INT KILL TERM XCPU}) {
                local($SIG{$key}) = sub {_destroy($attrib_ref, @_); die($!)};
            }
            close($from_worker);
            push(
                @{$attrib_ref->{worker_states}},
                $CTX_STATE->new($pid, $from_boss),
            );
        }
        elsif (defined($pid)) {
            # I am a worker
            close($from_boss);
            $attrib_ref->{worker_states} = [];
            open(STDIN, '/dev/null');
            # Ensures that events are sent back to the boss process
            my $util_of_event = bless(
                sub {_item_send($from_worker, @_)},
                __PACKAGE__ . '::WorkerEvent',
            );
            no strict 'refs';
            *{__PACKAGE__ . '::WorkerEvent::main'}
                = sub {my $self = shift(); $self->(@_)};
            use strict 'refs';
            $attrib_ref->{util}->util_of_event($util_of_event);
            _worker(
                $from_worker,
                $attrib_ref->{action},
                $attrib_ref->{util},
            );
            close($from_worker);
            exit();
        }
        else {
            die("fork: $!");
        }
    }
    $attrib_ref->{util}->event(
        FCM::Context::Event->TASK_WORKERS, 'init', $attrib_ref->{n_workers},
    );
}

# Main function of the class.
sub _main {
    my ($attrib_ref, $get_ref, $put_ref) = @_;
    my $n_done = 0;
    my $n_wait = 0;
    my $done_something = 1;
    my $get_task_ref = _get_task_func($get_ref, $attrib_ref->{n_workers});
    my $select = IO::Select->new();
    my @worker_states = @{$attrib_ref->{worker_states}};
    for my $worker_state (@worker_states) {
        $select->add($worker_state->get_socket());
    }
    while ($n_wait || $done_something) {
        $done_something = 0;
        # Handles tasks back from workers
        while (my @sockets = $select->can_read($TIME_OUT)) {
            for my $socket (@sockets) {
                my $worker_state
                    = first {$socket eq $_->get_socket()} @worker_states;
                my $item = _item_receive($socket);
                if (defined($item)) {
                    $done_something = 1;
                    if ($item->isa('FCM::Context::Event')) {
                        # Item is only an event, handles it
                        $attrib_ref->{util}->event($item);
                    }
                    else {
                        # Sends something back to the worker immediately
                        if (defined(my $task = $get_task_ref->())) {
                            _item_send($socket, $task);
                        }
                        else {
                            --$n_wait;
                            $worker_state->set_idle(1);
                        }
                        $put_ref->($item);
                        ++$n_done;
                    }
                }
            }
        }
        # Sends something to the idle workers
        my @idle_worker_states = grep {$_->get_idle()} @worker_states;
        if (@idle_worker_states) {
            for my $worker_state (@idle_worker_states) {
                if (defined(my $task = $get_task_ref->())) {
                    _item_send($worker_state->get_socket(), $task);
                    ++$n_wait;
                    $done_something = 1;
                    $worker_state->set_idle(0);
                }
            }
        }
        else {
            $get_task_ref->(); # only adds more tasks to queue
        }
    }
    $n_done;
}

# Returns a function to fetch more tasks into a queue.
sub _get_task_func {
    my ($get_ref, $n_workers) = @_;
    my $max_n_in_queue = $n_workers * 2;
    my @queue;
    sub {
        while (@queue < $max_n_in_queue && defined(my $task = $get_ref->())) {
            push(@queue, $task);
        }
        if (!defined(wantarray())) {
            return;
        }
        shift(@queue);
    };
}

# Receives an item from a socket.
sub _item_receive {
    my ($socket) = @_;
    my $len_of_data = unpack('N', _item_travel($socket, $LEN_OF_LONG));
    $len_of_data ? thaw(_item_travel($socket, $len_of_data)) : undef;
}

# Sends an item to a socket.
sub _item_send {
    my ($socket, $item) = @_;
    my $item_as_data = $item ? freeze($item) : q{};
    my $message = pack('N', length($item_as_data)) . $item_as_data;
    _item_travel($socket, length($message), $message);
}

# Helper for _item_receive/_item_send.
sub _item_travel {
    my ($socket, $len_to_travel, $data) = @_;
    my $action
        = defined($data) ? sub {syswrite($socket, $data, $_[0], $_[1])}
        :                  sub {sysread( $socket, $data, $_[0], $_[1])}
        ;
    $data ||= q{};
    my $n_bytes = 0;
    while ($n_bytes < $len_to_travel) {
        my $len_remain = $len_to_travel - $n_bytes;
        my $n = $action->($len_remain, $n_bytes);
        if (!defined($n)) {
            die($!);
        }
        $n_bytes += $n;
    }
    $data;
}

# Performs the function of a worker. Receives a task. Actions it. Sends it back.
sub _worker {
    my ($socket, $action, $util) = @_;
    while (defined(my $task = _item_receive($socket))) {
        my $timer = $util->timer();
        eval {
            $task->set_state($task->ST_WORKING);
            $action->($task->get_ctx());
            $task->set_state($task->ST_OK);
        };
        if ($@) {
            $task->set_state($task->ST_FAILED);
            $task->set_error($@);
        }
        $task->set_elapse($timer->());
        _item_send($socket, $task);
    }
    1;
}

# ------------------------------------------------------------------------------
# The state of a worker.
package FCM::Util::TaskRunner::WorkerState;
use base qw{FCM::Class::HASH};

__PACKAGE__->class(
    {   'idle'   => {isa => '$', default => 1}, # worker is idle?
        'pid'    => '$',                        # worker's PID
        'socket' => '*',                        # socket to worker
    },
    {   init_attrib => sub {
            my ($pid, $socket) = @_;
            {'pid' => $pid, 'socket' => $socket};
        },
    },
);

# ------------------------------------------------------------------------------
1;
__END__

=head1 NAME

FCM::Util::TaskRunner

=head1 SYNOPSIS

    use FCM::Context::Task;
    use FCM::Util;
    my $util = FCM::Util->new(\%attrib);
    # ... time passes
    my $runner = $util->task_runner(\&do_task, 4); # run with 4 workers
    # ... time passes
    my $get_ref = sub {
        # ... an iterator to return an FCM::Context::Task object
        # one at a time, returns undef if there is no currently available task
    };
    my $put_ref = sub {
        my ($task) = @_;
        # ... callback at end of each task
    };
    my $n_done = $runner->main($get_ref, $put_ref);

=head1 DESCRIPTION

This module is part of L<FCM::Util|FCM::Util>. See the description of the
task_runner() method for details.

An instance of this class is a runner of tasks. It can be configured to work in
serial (default) or parallel. The class is a sub-class of
L<FCM::Class::CODE|FCM::Class::CODE>.

=head1 SEE ALSO

This module is inspired by the CPAN modules Parallel::Fork::BossWorker and
Parallel::Fork::BossWorkerAsync.

L<FCM::Context::Task|FCM::Context::Task>,
L<FCM::Util::TaskManager|FCM::Util::TaskManager>

=head1 COPYRIGHT

(C) Crown copyright Met Office. All rights reserved.

=cut