File: Session.pm

package info (click to toggle)
libmojo-ioloop-readwriteprocess-perl 1.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 540 kB
  • sloc: perl: 4,655; sh: 101; makefile: 2
file content (540 lines) | stat: -rw-r--r-- 15,010 bytes parent folder | download
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package Mojo::IOLoop::ReadWriteProcess::Session;

use Mojo::Base 'Mojo::EventEmitter';
use Mojo::IOLoop::ReadWriteProcess;
use Carp 'confess';
use POSIX qw( :sys_wait_h :signal_h );
use Mojo::Collection 'c';

our @EXPORT_OK = qw(session);
use Exporter 'import';

use Config;

use constant DEBUG => $ENV{MOJO_PROCESS_DEBUG};

# See https://github.com/torvalds/linux/blob/master/include/uapi/linux/prctl.h
use constant PR_SET_CHILD_SUBREAPER => 36;
use constant PR_GET_CHILD_SUBREAPER => 37;

has subreaper      => 0;
has collect_status => 1;
has orphans        => sub { {} };
has process_table  => sub { {} };
has collected_info => sub { [] };
has 'handler';
has emit_from_sigchld => 1;

my $singleton;

sub new { $singleton ||= __PACKAGE__->SUPER::new }

sub disable {
  $singleton->_protect(sub { $SIG{CHLD} = $singleton->handler() });
}

sub _protect {
  shift if $_[0] && $_[0] eq $singleton;
  my ($sig, $cb) = (@_ > 1 ? pop : SIGCHLD, pop);
  my ($sigset, $blockset) = (POSIX::SigSet->new, POSIX::SigSet->new($sig));
  $singleton->emit(protect => [$cb, $sig]);
  sigprocmask(SIG_BLOCK, $blockset, $sigset);
  my $r = $cb->();
  sigprocmask(SIG_SETMASK, $sigset);
  return $r;
}

sub enable {
  return if $singleton->handler();
  $singleton->handler($SIG{CHLD});
  $singleton->_protect(
    sub {
      $SIG{CHLD} = sub {
        local ($!, $?);
        $singleton->emit('SIG_CHLD');
        return unless $singleton->collect_status;
        while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
          $singleton->add_collected_info($pid, $?, $!);
        }
        $singleton->consume_collected_info()
          if ($singleton->emit_from_sigchld());
      }
    });
}

sub _collect {
  my ($self, $pid, $status, $errno) = @_;
  my $p = $singleton->resolve($pid);
  $p->emit('SIG_CHLD')
    ->emit(collect_status => $pid => $status => $errno)
    ->emit('collected')
    ->emit('stop');
}

sub collect {
  my ($self, $pid, $status, $errno) = @_;
  if ($singleton->resolve($pid)) {
    $singleton->_collect($pid => $status => $errno);
    $singleton->emit(collected => $singleton->resolve($pid));
  }
  else {
    $singleton->orphans->{$pid}
      = Mojo::IOLoop::ReadWriteProcess->new(process_id => $pid)
      ->_fork_collect_status($pid => $status => $errno);
    $singleton->emit(collected_orphan => $singleton->orphan($pid));
  }
  return $singleton;
}

sub consume_collected_info {
  while (my $i = shift @{$singleton->collected_info}) {
    $singleton->collect(@$i);
  }
}

sub add_collected_info {
  shift;
  push @{$singleton->collected_info}, [@_];
}

# Use as $pid => Mojo::IOLoop::ReadWriteProcess
sub register {
  my ($process, $pid) = (pop, pop);
  $singleton->process_table()->{$pid} = \$process;
  $singleton->emit(register => $process);
}

sub unregister { delete($singleton->process_table()->{+pop()}) }

sub _resolve {
  my ($el, $w) = (pop, pop);
  return
      exists $singleton->{$w}->{$el}
    ? $w eq 'orphans'
      ? $singleton->{$w}->{$el}
      : ${$singleton->{$w}->{$el}}
    : undef;
}
sub orphan  { _resolve(orphans       => pop()) }
sub resolve { _resolve(process_table => pop()) }

sub clean {
  $_[0]->resolve($_)->stop() and $_[0]->resolve($_)->DESTROY()
    for keys %{$_[0]->process_table()};
  $_[0]->orphan($_)->stop() and $_[0]->orphan($_)->DESTROY()
    for keys %{$_[0]->orphans()};
  shift->reset();
}

sub all { c($singleton->all_processes, $singleton->all_orphans)->flatten }
sub all_orphans { c(values %{$singleton->orphans}) }

sub all_processes {
  c(values %{$singleton->process_table})->map(sub { ${$_} });
}

sub contains {
  my $pid = pop;
  $singleton->all->grep(sub { $_->pid eq $pid })->size == 1;
}

sub reset {
  @{+shift}
    {qw(events orphans process_table collected_info handler emit_from_sigchld)}
    = ({}, {}, {}, [], undef, 1);
}

# XXX: This should be replaced by PR_GET_CHILD_SUBREAPER
sub disable_subreaper {
  $singleton->subreaper(
    $singleton->_prctl(PR_SET_CHILD_SUBREAPER, 0) == 0 ? 0 : 1);
}

sub enable_subreaper {
  $singleton->subreaper(
    $singleton->_prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 ? 1 : 0);
}

sub _get_prctl_syscall {

  # Courtesy of Sys::Prctl
  confess "Only Linux is supported" unless $^O eq 'linux';

  my $machine = (POSIX::uname())[4];
  die "Could not get machine type" unless $machine;

  # if we're running on an x86_64 kernel, but a 32-bit process,
  # we need to use the i386 syscall numbers.
  $machine = "i386" if ($machine eq "x86_64" && $Config{ptrsize} == 4);

  my $prctl_call
    = $machine
    =~ /^i[3456]86|^blackfin|cris|frv|h8300|m32r|m68k|microblaze|mn10300|sh|s390|parisc$/
    ? 172
    : $machine eq "x86_64"                         ? 157
    : $machine eq "sparc64"                        ? 147
    : $machine eq "aarch64"                        ? 167
    : ($machine eq "ppc" || $machine eq "ppc64le") ? 171
    : $machine eq "ia64"                           ? 1170
    : $machine eq "alpha"                          ? 348
    : $machine eq "avr32"                          ? 148
    : $machine eq "mips"                           ? 4000 + 192
    : $machine eq "mips64"                         ? 5000 + 153
    : $machine eq "xtensa"                         ? 130
    :                                                undef;

  unless (defined $prctl_call) {
    delete @INC{
      qw<syscall.ph asm/unistd.ph bits/syscall.ph _h2ph_pre.ph
        sys/syscall.ph>
    };
    my $rv = eval { require 'syscall.ph'; 1 }     ## no critic
      or eval { require 'sys/syscall.ph'; 1 };    ## no critic

    $prctl_call = eval { &SYS_prctl; };
  }
  return $prctl_call;
}

sub _prctl {
  my ($self, $option, $arg2, $arg3, $arg4, $arg5) = @_;
  confess 'prctl not supported in this platform!'
    unless defined _get_prctl_syscall;
  local $!;
  my $ret = syscall(
    _get_prctl_syscall(), $option,
    ($arg2 or 0),
    ($arg3 or 0),
    ($arg4 or 0),
    ($arg5 or 0));

  warn "prctl($option) is unavailable on this platform." if $!{EINVAL};
  warn "Error! $!"                                       if $!;
  return $ret;
}

*singleton = \&new;
*session   = \&new;
*protect   = \&_protect;

1;

=encoding utf-8

=head1 NAME

Mojo::IOLoop::ReadWriteProcess::Session - Session manager for handling child processes.

=head1 SYNOPSIS

    use Mojo::IOLoop::ReadWriteProcess::Session;
    use Mojo::IOLoop::ReadWriteProcess qw(process);

    my $session = process()->session; # or Mojo::IOLoop::ReadWriteProcess::Session->singleton

    $session->enable; # Modifies your SIG_CHLD

    $session->on(collected => sub { warn "Process ".(shift->pid)." collected! "});
    $session->on(collected_orphan => sub { warn "Orphan process collected! "});

    $session->enable_subreaper(); # Mark the current process as subreaper
    $session->disable_subreaper(); # Disable subreaper

    $session->reset(); # Resets events and clear the process tables
    $session->clean(); # Stop all processes that result as running and reset


=head1 DESCRIPTION

Mojo::IOLoop::ReadWriteProcess::Session is a session manager for the collected processes

=head1 EVENTS

L<Mojo::IOLoop::ReadWriteProcess::Session> inherits all events from L<Mojo::EventEmitter> and can emit
the following new ones.

=head2 SIG_CHLD

 $session->on(SIG_CHLD => sub {
   my ($self) = @_;
   ...
 });

Emitted when we receive SIG_CHLD.

=head2 collected

    $session->on(collected => sub {
      my ($self, $process) = @_;
      ...
    });

Emitted when child process is collected and it's return status is available.

=head2 protect

    $session->on(protect => sub {
      my ($self, $detail) = @_;
      my ($cb, $signal) = @$detail;
      ...
    });

Emitted when protected callbacks are fired.

=head2 collected_orphan

    $session->on(collected_orphan => sub {
      my ($self, $process) = @_;
      $process->pid;
      $process->exit_status;
      ...
    });

Emitted when child process is collected and it's exit status is available.
Note: here are collected processes that weren't created with L<Mojo::IOLoop::ReadWriteProcess>.

=head2 register

    $session->on(register => sub {
      my ($self, $process) = @_;
      $process->pid;
      $process->exit_status;
      ...
    });

Emitted when a process is registering to a session.

=head1 ATTRIBUTES

L<Mojo::IOLoop::ReadWriteProcess::Session> inherits all attributes from L<Mojo::EventEmitter> and implements
the following new ones.


=head2 subreaper

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    session->enable_subreaper;
    my $process = Mojo::IOLoop::ReadWriteProcess->new(code => sub { print "Hello ".$_[1] }, args => "User" );
    $process->start();
    $process->on( stop => sub { shift()->disable_subreaper } );
    $process->stop();

    # The process will print "Hello User"

Mark the current process (not the child) as subreaper on start.
It's on invoker behalf to disable subreaper when process stops, as it marks the current process and not the
child.

=head2 collect_status

Defaults to C<1>, If enabled it will automatically collect the status of the children process.
Disable it in case you want to manage your process child directly, and do not want to rely on
automatic collect status. If you won't overwrite your C<SIGCHLD> handler,
the C<SIG_CHLD> event will be still emitted.

=head2 handler()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    session->handler(sub {});

Default handler for SIG_CHLD processing, used when C<disable()> is invoked.

=head1 METHODS

L<Mojo::IOLoop::ReadWriteProcess::Session> inherits all methods from L<Mojo::EventEmitter> and implements
the following new ones.

=head2 enable()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    session->enable();

Sets the SIG_CHLD handler.

=head2 disable()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    session->disable();

Disables the SIG_CHLD handler and reset with the previous one.

=head2 enable_subreaper()

    use Mojo::IOLoop::ReadWriteProcess qw(process);
    my $p = process()->enable_subreaper;
    # or
    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    session->enable_subreaper;

Mark the current process (not the child) as subreaper.
This is used typically if you want to mark further children as subreapers inside other forks.

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);

    my $master_p = process(
      sub {
        my $p = shift;
        $p->enable_subreaper;

        process(sub { sleep 4; exit 1 })->start();
        process(
          sub {
            sleep 4;
            process(sub { sleep 1; })->start();
          })->start();
        process(sub { sleep 4; exit 0 })->start();
        process(sub { sleep 4; die })->start();
        my $manager
          = process(sub { sleep 2 })->subreaper(1)->start();
        sleep 1 for (0 .. 10);
        $manager->stop;
        return session->all->size;
      });

    $master_p->subreaper(1);
    $master_p->on(collect_status => sub { $status++ });

    $master_p->on(stop => sub { shift()->disable_subreaper });
    $master_p->start();
    session->all->size();
    ....

=head2 disable_subreaper()

    use Mojo::IOLoop::ReadWriteProcess qw(process);
    my $p = process()->disable_subreaper;

Unset the current process as subreaper.

=head2 prctl()

    use Mojo::IOLoop::ReadWriteProcess qw(process);
    my $p = process();
    $p->prctl($option, $arg2, $arg3, $arg4, $arg5);

Internal function to execute and wrap the prctl syscall, accepts the same arguments as prctl.

=head2 reset()

    use Mojo::IOLoop::ReadWriteProcess qw(session);
    session->reset;

Wipe the process tables.

=head2 clean()

    use Mojo::IOLoop::ReadWriteProcess qw(session);
    session->clean;

Wipe the process tables, but before attempt to stop running procesess.

=head2 all()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $collection = session->all;
    $collection->size;

Returns a L<Mojo::Collection> of L<Mojo::IOLoop::ReadWriteProcess> that belongs to a session.

=head2 all_orphans()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $collection = session->all_orphans;
    $collection->size;

Returns a L<Mojo::Collection> of L<Mojo::IOLoop::ReadWriteProcess> of orphaned processes that belongs to a session.
They are automatically turned into a L<Mojo::IOLoop::ReadWriteProcess>, also if processes were created by C<fork()>.

=head2 all_processes()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $collection = session->all_processes;
    $collection->size;

Returns a L<Mojo::Collection> of all L<Mojo::IOLoop::ReadWriteProcess> known processes that belongs to a session.

=head2 contains()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $collection = session->contains(13443);
    $collection->size;

Returns true if the pid is contained in any of the process tables.

=head2 resolve()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $process = session->resolve(12233);

Returns the L<Mojo::IOLoop::ReadWriteProcess> process identified by its pid if belongs to the process table.

=head2 orphan()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $process = session->orphan(12233);

Returns the L<Mojo::IOLoop::ReadWriteProcess> process identified by its pid if belongs to the process table of unknown processes.

=head2 register()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $process = session->register('pid' => Mojo::IOLoop::ReadWriteProcess->new);

Register the L<Mojo::IOLoop::ReadWriteProcess> process to the session.

=head2 unregister()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $process = session->unregister(123342);

Unregister the corresponding L<Mojo::IOLoop::ReadWriteProcess> with the given pid.

=head2 collect()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    my $process = session->collect(123342 => 0 => undef);

Collect the status for the given pid.

=head2 protect()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    use POSIX;

    my $return = session->protect(sub { print "Hello World\n" });

    session->protect(sub { print "Hello World\n" } => SIGTERM);

Try to protect the execution of the callback from signal interrupts.

=head1 EXPORTS

=head2 session()

    use Mojo::IOLoop::ReadWriteProcess::Session qw(session);
    session->enable_subreaper;

Returns the L<Mojo::IOLoop::ReadWriteProcess::Session> singleton.

=head1 DEBUGGING

You can set the MOJO_EVENTEMITTER_DEBUG environment variable to get some advanced diagnostics information printed to STDERR.

    MOJO_EVENTEMITTER_DEBUG=1

Also, you can set MOJO_PROCESS_DEBUG environment variable to get diagnostics about the process execution.

    MOJO_PROCESS_DEBUG=1

=head1 LICENSE

Copyright (C) Ettore Di Giacinto.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 AUTHOR

Ettore Di Giacinto E<lt>edigiacinto@suse.comE<gt>

=cut