ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-Fork/Fork.pm
(Generate patch)

Comparing AnyEvent-Fork/Fork.pm (file contents):
Revision 1.3 by root, Tue Apr 2 18:00:04 2013 UTC vs.
Revision 1.13 by root, Thu Apr 4 07:58:01 2013 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent::ProcessPool - manage pools of perl worker processes, exec'ed or fork'ed 3AnyEvent::Fork - everything you wanted to use fork() for, but couldn't
4
5ATTENTION, this is a very early release, and very untested. Consider it a
6technology preview.
4 7
5=head1 SYNOPSIS 8=head1 SYNOPSIS
6 9
7 use AnyEvent::ProcessPool; 10 use AnyEvent::Fork;
11
12 ##################################################################
13 # create a single new process, tell it to run your worker function
14
15 AnyEvent::Fork
16 ->new
17 ->require ("MyModule")
18 ->run ("MyModule::worker, sub {
19 my ($master_filehandle) = @_;
20
21 # now $master_filehandle is connected to the
22 # $slave_filehandle in the new process.
23 });
24
25 # MyModule::worker might look like this
26 sub MyModule::worker {
27 my ($slave_filehandle) = @_;
28
29 # now $slave_filehandle is connected to the $master_filehandle
30 # in the original prorcess. have fun!
31 }
32
33 ##################################################################
34 # create a pool of server processes all accepting on the same socket
35
36 # create listener socket
37 my $listener = ...;
38
39 # create a pool template, initialise it and give it the socket
40 my $pool = AnyEvent::Fork
41 ->new
42 ->require ("Some::Stuff", "My::Server")
43 ->send_fh ($listener);
44
45 # now create 10 identical workers
46 for my $id (1..10) {
47 $pool
48 ->fork
49 ->send_arg ($id)
50 ->run ("My::Server::run");
51 }
52
53 # now do other things - maybe use the filehandle provided by run
54 # to wait for the processes to die. or whatever.
55
56 # My::Server::run might look like this
57 sub My::Server::run {
58 my ($slave, $listener, $id) = @_;
59
60 close $slave; # we do not use the socket, so close it to save resources
61
62 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
63 # or anything we usually couldn't do in a process forked normally.
64 while (my $socket = $listener->accept) {
65 # do sth. with new socket
66 }
67 }
8 68
9=head1 DESCRIPTION 69=head1 DESCRIPTION
10 70
11This module allows you to create single worker processes but also worker 71This module allows you to create new processes, without actually forking
12pool that share memory, by forking from the main program, or exec'ing new 72them from your current process (avoiding the problems of forking), but
13perl interpreters from a module. 73preserving most of the advantages of fork.
14 74
15You create a new processes in a pool by specifying a function to call 75It can be used to create new worker processes or new independent
16with any combination of string values and file handles. 76subprocesses for short- and long-running jobs, process pools (e.g. for use
77in pre-forked servers) but also to spawn new external processes (such as
78CGI scripts from a webserver), which can be faster (and more well behaved)
79than using fork+exec in big processes.
17 80
18A pool can have initialisation code which is executed before forking. The 81Special care has been taken to make this module useful from other modules,
19initialisation code is only executed once and the resulting process is 82while still supporting specialised environments such as L<App::Staticperl>
20cached, to be used as a template. 83or L<PAR::Packer>.
21
22Pools without such initialisation code don't cache an extra process.
23 84
24=head1 PROBLEM STATEMENT 85=head1 PROBLEM STATEMENT
25 86
26There are two ways to implement parallel processing on UNIX like operating 87There are two ways to implement parallel processing on UNIX like operating
27systems - fork and process, and fork+exec and process. They have different 88systems - fork and process, and fork+exec and process. They have different
110time, and the memory is not shared with anything else. 171time, and the memory is not shared with anything else.
111 172
112This is ideal for when you only need one extra process of a kind, with the 173This is ideal for when you only need one extra process of a kind, with the
113option of starting and stipping it on demand. 174option of starting and stipping it on demand.
114 175
176Example:
177
178 AnyEvent::Fork
179 ->new
180 ->require ("Some::Module")
181 ->run ("Some::Module::run", sub {
182 my ($fork_fh) = @_;
183 });
184
115=item fork a new template process, load code, then fork processes off of 185=item fork a new template process, load code, then fork processes off of
116it and run the code 186it and run the code
117 187
118When you need to have a bunch of processes that all execute the same (or 188When you need to have a bunch of processes that all execute the same (or
119very similar) tasks, then a good way is to create a new template process 189very similar) tasks, then a good way is to create a new template process
127The disadvantage of this approach is that you need to create a template 197The disadvantage of this approach is that you need to create a template
128process for the sole purpose of forking new processes from it, but if you 198process for the sole purpose of forking new processes from it, but if you
129only need a fixed number of proceses you can create them, and then destroy 199only need a fixed number of proceses you can create them, and then destroy
130the template process. 200the template process.
131 201
202Example:
203
204 my $template = AnyEvent::Fork->new->require ("Some::Module");
205
206 for (1..10) {
207 $template->fork->run ("Some::Module::run", sub {
208 my ($fork_fh) = @_;
209 });
210 }
211
212 # at this point, you can keep $template around to fork new processes
213 # later, or you can destroy it, which causes it to vanish.
214
132=item execute a new perl interpreter, load some code, run it 215=item execute a new perl interpreter, load some code, run it
133 216
134This is relatively slow, and doesn't allow you to share memory between 217This is relatively slow, and doesn't allow you to share memory between
135multiple processes. 218multiple processes.
136 219
137The only advantage is that you don't have to have a template process 220The only advantage is that you don't have to have a template process
138hanging around all the time to fork off some new processes, which might be 221hanging around all the time to fork off some new processes, which might be
139an advantage when there are long time spans where no extra processes are 222an advantage when there are long time spans where no extra processes are
140needed. 223needed.
141 224
225Example:
226
227 AnyEvent::Fork
228 ->new_exec
229 ->require ("Some::Module")
230 ->run ("Some::Module::run", sub {
231 my ($fork_fh) = @_;
232 });
233
142=back 234=back
143 235
144=head1 FUNCTIONS 236=head1 FUNCTIONS
145 237
146=over 4 238=over 4
147 239
148=cut 240=cut
149 241
150package AnyEvent::ProcessPool; 242package AnyEvent::Fork;
151 243
152use common::sense; 244use common::sense;
153 245
154use Socket (); 246use Socket ();
155 247
156use Proc::FastSpawn;
157use AnyEvent; 248use AnyEvent;
158use AnyEvent::ProcessPool::Util; 249use AnyEvent::Fork::Util;
159use AnyEvent::Util (); 250use AnyEvent::Util ();
160 251
161BEGIN { 252our $VERSION = $AnyEvent::Fork::Util::VERSION;
162# require Exporter;
163}
164 253
254our $PERL; # the path to the perl interpreter, deduces with various forms of magic
255
165=item my $pool = new AnyEvent::ProcessPool key => value... 256=item my $pool = new AnyEvent::Fork key => value...
166 257
167Create a new process pool. The following named parameters are supported: 258Create a new process pool. The following named parameters are supported:
168 259
169=over 4 260=over 4
170 261
171=back 262=back
172 263
173=cut 264=cut
174 265
266# the early fork template process
267our $EARLY;
268
175# the template process 269# the empty template process
176our $template; 270our $TEMPLATE;
177 271
178sub _queue { 272sub _cmd {
273 my $self = shift;
274
275 #TODO: maybe append the packet to any existing string command already in the queue
276
277 # ideally, we would want to use "a (w/a)*" as format string, but perl versions
278 # from at least 5.8.9 to 5.16.3 are all buggy and can't unpack it.
279 push @{ $self->[2] }, pack "N/a*", pack "(w/a*)*", @_;
280
281 $self->[3] ||= AE::io $self->[1], 1, sub {
282 # send the next "thing" in the queue - either a reference to an fh,
283 # or a plain string.
284
285 if (ref $self->[2][0]) {
286 # send fh
287 AnyEvent::Fork::Util::fd_send fileno $self->[1], fileno ${ $self->[2][0] }
288 and shift @{ $self->[2] };
289
290 } else {
291 # send string
292 my $len = syswrite $self->[1], $self->[2][0]
293 or do { undef $self->[3]; die "AnyEvent::Fork: command write failure: $!" };
294
295 substr $self->[2][0], 0, $len, "";
296 shift @{ $self->[2] } unless length $self->[2][0];
297 }
298
299 unless (@{ $self->[2] }) {
300 undef $self->[3];
301 # invoke run callback
302 $self->[0]->($self->[1]) if $self->[0];
303 }
304 };
305}
306
307sub _new {
179 my ($pid, $fh) = @_; 308 my ($self, $fh) = @_;
180 309
181 [ 310 AnyEvent::Util::fh_nonblocking $fh, 1;
182 $pid, 311
312 $self = bless [
313 undef, # run callback
183 $fh, 314 $fh,
184 [], 315 [], # write queue - strings or fd's
185 undef 316 undef, # AE watcher
186 ] 317 ], $self;
187}
188 318
189sub queue_cmd { 319 $self
190 my $queue = shift;
191
192 push @{ $queue->[2] }, pack "N/a", pack "a (w/a)*", @_;
193
194 $queue->[3] ||= AE::io $queue->[1], 1, sub {
195 if (ref $queue->[2][0]) {
196 AnyEvent::ProcessPool::Util::fd_send fileno $queue->[1], fileno ${ $queue->[2][0] }
197 and shift @{ $queue->[2] };
198 } else {
199 my $len = syswrite $queue->[1], $queue->[2][0]
200 or do { undef $queue->[3]; die "AnyEvent::ProcessPool::queue write failure: $!" };
201 substr $queue->[2][0], 0, $len, "";
202 shift @{ $queue->[2] } unless length $queue->[2][0];
203 }
204
205 undef $queue->[3] unless @{ $queue->[2] };
206 };
207} 320}
208 321
209sub run_template { 322# fork template from current process, used by AnyEvent::Fork::Early/Template
210 return if $template; 323sub _new_fork {
211
212 my ($fh, $slave) = AnyEvent::Util::portable_socketpair; 324 my ($fh, $slave) = AnyEvent::Util::portable_socketpair;
213 AnyEvent::Util::fh_nonblocking $fh, 1; 325 my $parent = $$;
214 fd_inherit fileno $slave;
215 326
216 my %env = %ENV; 327 my $pid = fork;
217 $env{PERL5LIB} = join ":", grep !ref, @INC;
218 328
219 my $pid = spawn 329 if ($pid eq 0) {
220 $^X, 330 require AnyEvent::Fork::Serve;
221 ["perl", "-MAnyEvent::ProcessPool::Serve", "-e", "AnyEvent::ProcessPool::Serve::me", fileno $slave], 331 $AnyEvent::Fork::Serve::OWNER = $parent;
222 [map "$_=$env{$_}", keys %env], 332 close $fh;
223 or die "unable to spawn AnyEvent::ProcessPool server: $!"; 333 $0 = "$_[1] of $parent";
334 AnyEvent::Fork::Serve::serve ($slave);
335 AnyEvent::Fork::Util::_exit 0;
336 } elsif (!$pid) {
337 die "AnyEvent::Fork::Early/Template: unable to fork template process: $!";
338 }
224 339
225 close $slave; 340 AnyEvent::Fork->_new ($fh)
226
227 $template = _queue $pid, $fh;
228
229 my ($a, $b) = AnyEvent::Util::portable_socketpair;
230
231 queue_cmd $template, "Iabc";
232 push @{ $template->[2] }, \$b;
233
234 use Coro::AnyEvent; Coro::AnyEvent::sleep 1;
235 undef $b;
236 die "x" . <$a>;
237} 341}
342
343=item my $proc = new AnyEvent::Fork
344
345Create a new "empty" perl interpreter process and returns its process
346object for further manipulation.
347
348The new process is forked from a template process that is kept around
349for this purpose. When it doesn't exist yet, it is created by a call to
350C<new_exec> and kept around for future calls.
351
352When the process object is destroyed, it will release the file handle
353that connects it with the new process. When the new process has not yet
354called C<run>, then the process will exit. Otherwise, what happens depends
355entirely on the code that is executed.
356
357=cut
238 358
239sub new { 359sub new {
240 my $class = shift; 360 my $class = shift;
241 361
242 my $self = bless { 362 $TEMPLATE ||= $class->new_exec;
243 @_ 363 $TEMPLATE->fork
244 }, $class; 364}
245 365
246 run_template; 366=item $new_proc = $proc->fork
367
368Forks C<$proc>, creating a new process, and returns the process object
369of the new process.
370
371If any of the C<send_> functions have been called before fork, then they
372will be cloned in the child. For example, in a pre-forked server, you
373might C<send_fh> the listening socket into the template process, and then
374keep calling C<fork> and C<run>.
375
376=cut
377
378sub fork {
379 my ($self) = @_;
380
381 my ($fh, $slave) = AnyEvent::Util::portable_socketpair;
382
383 $self->send_fh ($slave);
384 $self->_cmd ("f");
385
386 AnyEvent::Fork->_new ($fh)
387}
388
389=item my $proc = new_exec AnyEvent::Fork
390
391Create a new "empty" perl interpreter process and returns its process
392object for further manipulation.
393
394Unlike the C<new> method, this method I<always> spawns a new perl process
395(except in some cases, see L<AnyEvent::Fork::Early> for details). This
396reduces the amount of memory sharing that is possible, and is also slower.
397
398You should use C<new> whenever possible, except when having a template
399process around is unacceptable.
400
401The path to the perl interpreter is divined usign various methods - first
402C<$^X> is investigated to see if the path ends with something that sounds
403as if it were the perl interpreter. Failing this, the module falls back to
404using C<$Config::Config{perlpath}>.
405
406=cut
407
408sub new_exec {
409 my ($self) = @_;
410
411 return $EARLY->fork
412 if $EARLY;
413
414 # first find path of perl
415 my $perl = $;
416
417 # first we try $^X, but the path must be absolute (always on win32), and end in sth.
418 # that looks like perl. this obviously only works for posix and win32
419 unless (
420 (AnyEvent::Fork::Util::WIN32 || $perl =~ m%^/%)
421 && $perl =~ m%[/\\]perl(?:[0-9]+(\.[0-9]+)+)?(\.exe)?$%i
422 ) {
423 # if it doesn't look perlish enough, try Config
424 require Config;
425 $perl = $Config::Config{perlpath};
426 $perl =~ s/(?:\Q$Config::Config{_exe}\E)?$/$Config::Config{_exe}/;
427 }
428
429 require Proc::FastSpawn;
430
431 my ($fh, $slave) = AnyEvent::Util::portable_socketpair;
432 Proc::FastSpawn::fd_inherit (fileno $slave);
433
434 # new fh's should always be set cloexec (due to $^F),
435 # but hey, not on win32, so we always clear the inherit flag.
436 Proc::FastSpawn::fd_inherit (fileno $fh, 0);
437
438 # quick. also doesn't work in win32. of course. what did you expect
439 #local $ENV{PERL5LIB} = join ":", grep !ref, @INC;
440 my %env = %ENV;
441 $env{PERL5LIB} = join +(AnyEvent::Fork::Util::WIN32 ? ";" : ":"), grep !ref, @INC;
442
443 Proc::FastSpawn::spawn (
444 $perl,
445 ["perl", "-MAnyEvent::Fork::Serve", "-e", "AnyEvent::Fork::Serve::me", fileno $slave, $$],
446 [map "$_=$env{$_}", keys %env],
447 ) or die "unable to spawn AnyEvent::Fork server: $!";
448
449 $self->_new ($fh)
450}
451
452=item $proc = $proc->eval ($perlcode, @args)
453
454Evaluates the given C<$perlcode> as ... perl code, while setting C<@_> to
455the strings specified by C<@args>.
456
457This call is meant to do any custom initialisation that might be required
458(for example, the C<require> method uses it). It's not supposed to be used
459to completely take over the process, use C<run> for that.
460
461The code will usually be executed after this call returns, and there is no
462way to pass anything back to the calling process. Any evaluation errors
463will be reported to stderr and cause the process to exit.
464
465Returns the process object for easy chaining of method calls.
466
467=cut
468
469sub eval {
470 my ($self, $code, @args) = @_;
471
472 $self->_cmd (e => $code, @args);
247 473
248 $self 474 $self
249} 475}
250 476
477=item $proc = $proc->require ($module, ...)
478
479Tries to load the given module(s) into the process
480
481Returns the process object for easy chaining of method calls.
482
483=cut
484
485sub require {
486 my ($self, @modules) = @_;
487
488 s%::%/%g for @modules;
489 $self->eval ('require "$_.pm" for @_', @modules);
490
491 $self
492}
493
494=item $proc = $proc->send_fh ($handle, ...)
495
496Send one or more file handles (I<not> file descriptors) to the process,
497to prepare a call to C<run>.
498
499The process object keeps a reference to the handles until this is done,
500so you must not explicitly close the handles. This is most easily
501accomplished by simply not storing the file handles anywhere after passing
502them to this method.
503
504Returns the process object for easy chaining of method calls.
505
506Example: pass an fh to a process, and release it without closing. it will
507be closed automatically when it is no longer used.
508
509 $proc->send_fh ($my_fh);
510 undef $my_fh; # free the reference if you want, but DO NOT CLOSE IT
511
512=cut
513
514sub send_fh {
515 my ($self, @fh) = @_;
516
517 for my $fh (@fh) {
518 $self->_cmd ("h");
519 push @{ $self->[2] }, \$fh;
520 }
521
522 $self
523}
524
525=item $proc = $proc->send_arg ($string, ...)
526
527Send one or more argument strings to the process, to prepare a call to
528C<run>. The strings can be any octet string.
529
530Returns the process object for easy chaining of emthod calls.
531
532=cut
533
534sub send_arg {
535 my ($self, @arg) = @_;
536
537 $self->_cmd (a => @arg);
538
539 $self
540}
541
542=item $proc->run ($func, $cb->($fh))
543
544Enter the function specified by the fully qualified name in C<$func> in
545the process. The function is called with the communication socket as first
546argument, followed by all file handles and string arguments sent earlier
547via C<send_fh> and C<send_arg> methods, in the order they were called.
548
549If the called function returns, the process exits.
550
551Preparing the process can take time - when the process is ready, the
552callback is invoked with the local communications socket as argument.
553
554The process object becomes unusable on return from this function.
555
556If the communication socket isn't used, it should be closed on both sides,
557to save on kernel memory.
558
559The socket is non-blocking in the parent, and blocking in the newly
560created process. The close-on-exec flag is set on both. Even if not used
561otherwise, the socket can be a good indicator for the existance of the
562process - if the other process exits, you get a readable event on it,
563because exiting the process closes the socket (if it didn't create any
564children using fork).
565
566Example: create a template for a process pool, pass a few strings, some
567file handles, then fork, pass one more string, and run some code.
568
569 my $pool = AnyEvent::Fork
570 ->new
571 ->send_arg ("str1", "str2")
572 ->send_fh ($fh1, $fh2);
573
574 for (1..2) {
575 $pool
576 ->fork
577 ->send_arg ("str3")
578 ->run ("Some::function", sub {
579 my ($fh) = @_;
580
581 # fh is nonblocking, but we trust that the OS can accept these
582 # extra 3 octets anyway.
583 syswrite $fh, "hi #$_\n";
584
585 # $fh is being closed here, as we don't store it anywhere
586 });
587 }
588
589 # Some::function might look like this - all parameters passed before fork
590 # and after will be passed, in order, after the communications socket.
591 sub Some::function {
592 my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_;
593
594 print scalar <$fh>; # prints "hi 1\n" and "hi 2\n"
595 }
596
597=cut
598
599sub run {
600 my ($self, $func, $cb) = @_;
601
602 $self->[0] = $cb;
603 $self->_cmd (r => $func);
604}
605
251=back 606=back
607
608=head1 PORTABILITY NOTES
609
610Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a nop,
611and ::Template is not going to work), and it cost a lot of blood and sweat
612to make it so, mostly due to the bloody broken perl that nobody seems to
613care about. The fork emulation is a bad joke - I have yet to see something
614useful that you cna do with it without running into memory corruption
615issues or other braindamage. Hrrrr.
616
617Cygwin perl is not supported at the moment, as it should implement fd
618passing, but doesn't, and rolling my own is hard, as cygwin doesn't
619support enough functionality to do it.
620
621=head1 SEE ALSO
622
623L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter),
624L<AnyEvent::Fork::Template> (to create a process by forking the main
625program at a convenient time).
252 626
253=head1 AUTHOR 627=head1 AUTHOR
254 628
255 Marc Lehmann <schmorp@schmorp.de> 629 Marc Lehmann <schmorp@schmorp.de>
256 http://home.schmorp.de/ 630 http://home.schmorp.de/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines