-
-
Notifications
You must be signed in to change notification settings - Fork 65
Add ForkContext #212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
trowski
wants to merge
10
commits into
2.x
Choose a base branch
from
fork-context
base: 2.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add ForkContext #212
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
8ac48fa
Add ForkContext
trowski 31d8b70
Updates
trowski 03a5cdd
Fix
trowski ffedc39
Fixup tests
danog 981895d
Fixup
danog e7333d0
Merge branch '2.x' into fork-context
trowski ec3d242
Fork context (#214)
danog e8207c4
Fix copy/pasta mistake
trowski 141c629
Look for StreamSelectLoop
trowski a538c04
Unused import
trowski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -39,6 +39,7 @@ | |
"SPL", | ||
"standard", | ||
"hash", | ||
"pcntl" | ||
"pcntl", | ||
"posix" | ||
] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
<?php declare(strict_types=1); | ||
|
||
namespace Amp\Parallel\Context; | ||
|
||
use Amp\ByteStream\StreamChannel; | ||
use Amp\Cancellation; | ||
use Amp\Parallel\Context\Internal\AbstractContext; | ||
use Amp\Parallel\Ipc\IpcHub; | ||
use Amp\Serialization\NativeSerializer; | ||
use Amp\Serialization\Serializer; | ||
use Amp\TimeoutCancellation; | ||
use Revolt\EventLoop; | ||
use Revolt\EventLoop\Driver\UvDriver; | ||
|
||
/** | ||
* USE AT YOUR OWN RISK! This context is not used by default in {@see DefaultContextFactory} because the timing of its | ||
* creation must be purposeful and situational. | ||
* | ||
* Forking is not recommended at arbitrary points in an application since the entire state of the parent process is | ||
* inherited into the child process, including the event-loop! | ||
* | ||
* Forking very early in an application, may be beneficial to copy state from the parent that was expensive to set up. | ||
* | ||
* This context is NOT compatible with event-loop extensions such as ext-uv or ext-ev. | ||
* | ||
* @template-covariant TResult | ||
* @template-covariant TReceive | ||
* @template TSend | ||
* @extends AbstractContext<TResult, TReceive, TSend> | ||
*/ | ||
final class ForkContext extends AbstractContext | ||
{ | ||
private const DEFAULT_START_TIMEOUT = 5; | ||
|
||
public static function isSupported(): bool | ||
{ | ||
return \function_exists('pcntl_fork') | ||
&& !EventLoop::getDriver() instanceof UvDriver; | ||
} | ||
|
||
/** | ||
* @param string|non-empty-list<string> $script Path to PHP script or array with first element as path and | ||
* following elements options to the PHP script (e.g.: ['bin/worker.php', 'Option1Value', 'Option2Value']). | ||
* @param positive-int $childConnectTimeout Number of seconds the child will attempt to connect to the parent | ||
* before failing. | ||
* | ||
* @throws ContextException If starting the process fails. | ||
*/ | ||
public static function start( | ||
IpcHub $ipcHub, | ||
string|array $script, | ||
?Cancellation $cancellation = null, | ||
int $childConnectTimeout = self::DEFAULT_START_TIMEOUT, | ||
Serializer $serializer = new NativeSerializer(), | ||
): self { | ||
$key = $ipcHub->generateKey(); | ||
|
||
// Fork | ||
if (($pid = \pcntl_fork()) < 0) { | ||
throw new ContextException("Forking failed: " . \posix_strerror(\posix_get_last_error())); | ||
} | ||
|
||
// Parent | ||
if ($pid > 0) { | ||
try { | ||
$socket = $ipcHub->accept($key, $cancellation); | ||
$ipcChannel = new StreamChannel($socket, $socket, $serializer); | ||
|
||
$socket = $ipcHub->accept($key, $cancellation); | ||
$resultChannel = new StreamChannel($socket, $socket, $serializer); | ||
} catch (\Throwable $exception) { | ||
$cancellation?->throwIfRequested(); | ||
|
||
throw new ContextException("Connecting failed after forking", previous: $exception); | ||
} | ||
|
||
return new self($pid, $ipcChannel, $resultChannel); | ||
} | ||
|
||
// Child | ||
\define("AMP_CONTEXT", "parallel"); | ||
trowski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
\define("AMP_CONTEXT_ID", \getmypid()); | ||
|
||
if (\is_string($script)) { | ||
$script = [$script]; | ||
} | ||
|
||
$connectCancellation = new TimeoutCancellation((float) $childConnectTimeout); | ||
Internal\runContext($ipcHub->getUri(), $key, $connectCancellation, $script, $serializer); | ||
|
||
exit(0); | ||
} | ||
|
||
private ?int $exited = null; | ||
|
||
private bool $weKilled = false; | ||
|
||
/** | ||
* @param StreamChannel<TReceive, TSend> $ipcChannel | ||
*/ | ||
private function __construct( | ||
private readonly int $pid, | ||
StreamChannel $ipcChannel, | ||
StreamChannel $resultChannel, | ||
) { | ||
parent::__construct($ipcChannel, $resultChannel); | ||
} | ||
|
||
public function __destruct() | ||
{ | ||
$this->close(); | ||
} | ||
|
||
public function receive(?Cancellation $cancellation = null): mixed | ||
{ | ||
$this->checkExit(false); | ||
|
||
return parent::receive($cancellation); | ||
} | ||
|
||
public function send(mixed $data): void | ||
{ | ||
$this->checkExit(false); | ||
|
||
parent::send($data); | ||
} | ||
|
||
private function checkExit(bool $wait): ?int | ||
{ | ||
if ($this->exited === null) { | ||
if (\pcntl_waitpid($this->pid, $status, $wait ? 0 : \WNOHANG) === 0) { | ||
return null; | ||
} | ||
|
||
$this->exited = match (true) { | ||
\pcntl_wifsignaled($status) => \pcntl_wtermsig($status), | ||
\pcntl_wifexited($status) => \pcntl_wexitstatus($status) - 128, | ||
\pcntl_wifstopped($status) => \pcntl_wstopsig($status), | ||
default => -1, | ||
}; | ||
} | ||
|
||
if (!$this->weKilled && $this->exited > 0) { | ||
throw new ContextException("Worker exited due to signal {$this->exited}", $this->exited); | ||
} | ||
|
||
return $this->exited; | ||
} | ||
|
||
public function close(): void | ||
{ | ||
if ($this->checkExit(false) === null) { | ||
$this->weKilled = true; | ||
\posix_kill($this->pid, \SIGKILL); | ||
|
||
$this->checkExit(true); | ||
} | ||
|
||
parent::close(); | ||
} | ||
|
||
public function join(?Cancellation $cancellation = null): mixed | ||
{ | ||
$data = $this->receiveExitResult($cancellation); | ||
|
||
$this->close(); | ||
|
||
return $data->getResult(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
<?php declare(strict_types=1); | ||
|
||
namespace Amp\Parallel\Context; | ||
|
||
use Amp\Cancellation; | ||
use Amp\ForbidCloning; | ||
use Amp\ForbidSerialization; | ||
use Amp\Parallel\Ipc\IpcHub; | ||
use Amp\Parallel\Ipc\LocalIpcHub; | ||
|
||
/** | ||
* USE AT YOUR OWN RISK! | ||
* | ||
* Forking is not recommended at arbitrary points in an application since the entire state of the parent process is | ||
* inherited into the child process, including the event-loop! | ||
* | ||
* We recommend using {@see DefaultContextFactory} or {@see ProcessContextFactory} for general-purpose applications. | ||
*/ | ||
final class ForkContextFactory implements ContextFactory | ||
{ | ||
use ForbidCloning; | ||
use ForbidSerialization; | ||
|
||
/** | ||
* @param positive-int $childConnectTimeout Number of seconds the child will attempt to connect to the parent | ||
* before failing. | ||
* @param IpcHub $ipcHub Optional IpcHub instance. | ||
*/ | ||
public function __construct( | ||
private readonly int $childConnectTimeout = 5, | ||
private readonly IpcHub $ipcHub = new LocalIpcHub(), | ||
) { | ||
} | ||
|
||
/** | ||
* @param string|non-empty-list<string> $script | ||
* | ||
* @throws ContextException | ||
*/ | ||
public function start(string|array $script, ?Cancellation $cancellation = null): ForkContext | ||
{ | ||
return ForkContext::start( | ||
ipcHub: $this->ipcHub, | ||
script: $script, | ||
cancellation: $cancellation, | ||
childConnectTimeout: $this->childConnectTimeout, | ||
); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,79 +6,81 @@ | |
use Amp\Cancellation; | ||
use Amp\Future; | ||
use Amp\Parallel\Ipc; | ||
use Amp\Serialization\NativeSerializer; | ||
use Amp\Serialization\SerializationException; | ||
use Revolt\EventLoop; | ||
use Amp\Serialization\Serializer; | ||
|
||
/** @internal */ | ||
function runContext(string $uri, string $key, Cancellation $connectCancellation, array $argv): void | ||
{ | ||
EventLoop::queue(function () use ($argv, $uri, $key, $connectCancellation): void { | ||
/** @noinspection PhpUnusedLocalVariableInspection */ | ||
$argc = \count($argv); | ||
function runContext( | ||
string $uri, | ||
string $key, | ||
Cancellation $connectCancellation, | ||
array $argv, | ||
Serializer $serializer = new NativeSerializer(), | ||
): void { | ||
/** @noinspection PhpUnusedLocalVariableInspection */ | ||
$argc = \count($argv); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why did this code change in this PR? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
||
try { | ||
$socket = Ipc\connect($uri, $key, $connectCancellation); | ||
$ipcChannel = new StreamChannel($socket, $socket); | ||
|
||
$socket = Ipc\connect($uri, $key, $connectCancellation); | ||
$resultChannel = new StreamChannel($socket, $socket); | ||
} catch (\Throwable $exception) { | ||
\trigger_error($exception->getMessage(), E_USER_ERROR); | ||
} | ||
|
||
try { | ||
if (!isset($argv[0])) { | ||
throw new \Error("No script path given"); | ||
} | ||
try { | ||
$socket = Ipc\connect($uri, $key, $connectCancellation); | ||
$ipcChannel = new StreamChannel($socket, $socket, $serializer); | ||
|
||
if (!\is_file($argv[0])) { | ||
throw new \Error(\sprintf( | ||
"No script found at '%s' (be sure to provide the full path to the script)", | ||
$argv[0], | ||
)); | ||
} | ||
$socket = Ipc\connect($uri, $key, $connectCancellation); | ||
$resultChannel = new StreamChannel($socket, $socket, $serializer); | ||
} catch (\Throwable $exception) { | ||
\trigger_error($exception->getMessage(), E_USER_ERROR); | ||
} | ||
|
||
try { | ||
// Protect current scope by requiring script within another function. | ||
// Using $argc, so it is available to the required script. | ||
$callable = (function () use ($argc, $argv): callable { | ||
/** @psalm-suppress UnresolvableInclude */ | ||
return require $argv[0]; | ||
})(); | ||
} catch (\TypeError $exception) { | ||
throw new \Error(\sprintf( | ||
"Script '%s' did not return a callable function: %s", | ||
$argv[0], | ||
$exception->getMessage(), | ||
), 0, $exception); | ||
} catch (\ParseError $exception) { | ||
throw new \Error(\sprintf( | ||
"Script '%s' contains a parse error: %s", | ||
$argv[0], | ||
$exception->getMessage(), | ||
), 0, $exception); | ||
} | ||
try { | ||
if (!isset($argv[0])) { | ||
throw new \Error("No script path given"); | ||
} | ||
|
||
$returnValue = $callable(new ContextChannel($ipcChannel)); | ||
$result = new ExitSuccess($returnValue instanceof Future ? $returnValue->await() : $returnValue); | ||
} catch (\Throwable $exception) { | ||
$result = new ExitFailure($exception); | ||
if (!\is_file($argv[0])) { | ||
throw new \Error(\sprintf( | ||
"No script found at '%s' (be sure to provide the full path to the script)", | ||
$argv[0], | ||
)); | ||
} | ||
|
||
try { | ||
try { | ||
$resultChannel->send($result); | ||
} catch (SerializationException $exception) { | ||
// Serializing the result failed. Send the reason why. | ||
$resultChannel->send(new ExitFailure($exception)); | ||
} | ||
} catch (\Throwable $exception) { | ||
\trigger_error(\sprintf( | ||
"Could not send result to parent: '%s'; be sure to shutdown the child before ending the parent", | ||
// Protect current scope by requiring script within another function. | ||
// Using $argc, so it is available to the required script. | ||
$callable = (function () use ($argc, $argv): callable { | ||
/** @psalm-suppress UnresolvableInclude */ | ||
return require $argv[0]; | ||
})(); | ||
} catch (\TypeError $exception) { | ||
throw new \Error(\sprintf( | ||
"Script '%s' did not return a callable function: %s", | ||
$argv[0], | ||
$exception->getMessage(), | ||
), 0, $exception); | ||
} catch (\ParseError $exception) { | ||
throw new \Error(\sprintf( | ||
"Script '%s' contains a parse error: %s", | ||
$argv[0], | ||
$exception->getMessage(), | ||
), E_USER_ERROR); | ||
), 0, $exception); | ||
} | ||
}); | ||
|
||
EventLoop::run(); | ||
$returnValue = $callable(new ContextChannel($ipcChannel)); | ||
$result = new ExitSuccess($returnValue instanceof Future ? $returnValue->await() : $returnValue); | ||
} catch (\Throwable $exception) { | ||
$result = new ExitFailure($exception); | ||
} | ||
|
||
try { | ||
try { | ||
$resultChannel->send($result); | ||
} catch (SerializationException $exception) { | ||
// Serializing the result failed. Send the reason why. | ||
$resultChannel->send(new ExitFailure($exception)); | ||
} | ||
} catch (\Throwable $exception) { | ||
\trigger_error(\sprintf( | ||
"Could not send result to parent: '%s'; be sure to shutdown the child before ending the parent", | ||
$exception->getMessage(), | ||
), E_USER_ERROR); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Docs say it's not compatible with extension based event loops, but we only check for UV here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, this needs fixing, @trowski mind bumping