-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Parallel.php
393 lines (332 loc) · 11.8 KB
/
Parallel.php
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
<?php
namespace Amp\Parallel\Context;
use Amp\Loop;
use Amp\Parallel\Sync\ChannelledSocket;
use Amp\Parallel\Sync\ExitFailure;
use Amp\Parallel\Sync\ExitResult;
use Amp\Parallel\Sync\ExitSuccess;
use Amp\Parallel\Sync\SerializationException;
use Amp\Parallel\Sync\SynchronizationError;
use Amp\Promise;
use parallel\Runtime;
use function Amp\call;
/**
* Implements an execution context using native threads provided by the parallel extension.
*/
final class Parallel implements Context
{
const EXIT_CHECK_FREQUENCY = 250;
const KEY_LENGTH = 32;
/** @var string|null */
private static $autoloadPath;
/** @var int Next thread ID. */
private static $nextId = 1;
/** @var Internal\ProcessHub */
private $hub;
/** @var int|null */
private $id;
/** @var Runtime|null */
private $runtime;
/** @var ChannelledSocket|null A channel for communicating with the parallel thread. */
private $channel;
/** @var string Script path. */
private $script;
/** @var string[] */
private $args = [];
/** @var int */
private $oid = 0;
/** @var bool */
private $killed = false;
/**
* Checks if threading is enabled.
*
* @return bool True if threading is enabled, otherwise false.
*/
public static function isSupported(): bool
{
return \extension_loaded('parallel');
}
/**
* Creates and starts a new thread.
*
* @param string|array $script Path to PHP script or array with first element as path and following elements options
* to the PHP script (e.g.: ['bin/worker', 'Option1Value', 'Option2Value'].
* @param mixed ...$args Additional arguments to pass to the given callable.
*
* @return Promise<Thread> The thread object that was spawned.
*/
public static function run($script): Promise
{
$thread = new self($script);
return call(function () use ($thread) {
yield $thread->start();
return $thread;
});
}
/**
* @param string|array $script Path to PHP script or array with first element as path and following elements options
* to the PHP script (e.g.: ['bin/worker', 'Option1Value', 'Option2Value'].
*
* @throws \Error Thrown if the pthreads extension is not available.
*/
public function __construct($script)
{
if (!self::isSupported()) {
throw new \Error("The parallel extension is required to create parallel threads.");
}
$this->hub = Loop::getState(self::class);
if (!$this->hub instanceof Internal\ParallelHub) {
$this->hub = new Internal\ParallelHub;
Loop::setState(self::class, $this->hub);
}
if (\is_array($script)) {
$this->script = (string) \array_shift($script);
$this->args = \array_values(\array_map("strval", $script));
} else {
$this->script = (string) $script;
}
if (self::$autoloadPath === null) {
$paths = [
\dirname(__DIR__, 2) . \DIRECTORY_SEPARATOR . "vendor" . \DIRECTORY_SEPARATOR . "autoload.php",
\dirname(__DIR__, 4) . \DIRECTORY_SEPARATOR . "autoload.php",
];
foreach ($paths as $path) {
if (\file_exists($path)) {
self::$autoloadPath = $path;
break;
}
}
if (self::$autoloadPath === null) {
throw new \Error("Could not locate autoload.php");
}
}
}
/**
* Returns the thread to the condition before starting. The new thread can be started and run independently of the
* first thread.
*/
public function __clone()
{
$this->runtime = null;
$this->channel = null;
$this->id = null;
$this->oid = 0;
$this->killed = false;
}
/**
* Kills the thread if it is still running.
*
* @throws \Amp\Parallel\Context\ContextException
*/
public function __destruct()
{
if (\getmypid() === $this->oid) {
$this->kill();
}
}
/**
* Checks if the context is running.
*
* @return bool True if the context is running, otherwise false.
*/
public function isRunning(): bool
{
return $this->channel !== null;
}
/**
* Spawns the thread and begins the thread's execution.
*
* @return Promise<int> Resolved once the thread has started.
*
* @throws \Amp\Parallel\Context\StatusError If the thread has already been started.
* @throws \Amp\Parallel\Context\ContextException If starting the thread was unsuccessful.
*/
public function start(): Promise
{
if ($this->oid !== 0) {
throw new StatusError('The thread has already been started.');
}
$this->oid = \getmypid();
$this->runtime = new Runtime(self::$autoloadPath);
$this->id = self::$nextId++;
$future = $this->runtime->run(static function (int $id, string $uri, string $key, string $path, array $argv): int {
// @codeCoverageIgnoreStart
// Only executed in thread.
\define("AMP_CONTEXT", "parallel");
\define("AMP_CONTEXT_ID", $id);
if (!$socket = \stream_socket_client($uri, $errno, $errstr, 5, \STREAM_CLIENT_CONNECT)) {
\trigger_error("Could not connect to IPC socket", E_USER_ERROR);
return 1;
}
$channel = new ChannelledSocket($socket, $socket);
try {
Promise\wait($channel->send($key));
} catch (\Throwable $exception) {
\trigger_error("Could not send key to parent", E_USER_ERROR);
return 1;
}
try {
Loop::unreference(Loop::repeat(self::EXIT_CHECK_FREQUENCY, function () {
// Timer to give the chance for the PHP VM to be interrupted by Runtime::kill(), since system calls such as
// select() will not be interrupted.
}));
try {
if (!\is_file($path)) {
throw new \Error(\sprintf("No script found at '%s' (be sure to provide the full path to the script)", $path));
}
$argc = \array_unshift($argv, $path);
try {
// Protect current scope by requiring script within another function.
$callable = (function () use ($argc, $argv): callable { // Using $argc so it is available to the required script.
return require $argv[0];
})->bindTo(null, null)();
} catch (\TypeError $exception) {
throw new \Error(\sprintf("Script '%s' did not return a callable function", $path), 0, $exception);
} catch (\ParseError $exception) {
throw new \Error(\sprintf("Script '%s' contains a parse error", $path), 0, $exception);
}
$result = new ExitSuccess(Promise\wait(call($callable, $channel)));
} catch (\Throwable $exception) {
$result = new ExitFailure($exception);
}
Promise\wait(call(function () use ($channel, $result) {
try {
yield $channel->send($result);
} catch (SerializationException $exception) {
// Serializing the result failed. Send the reason why.
yield $channel->send(new ExitFailure($exception));
}
}));
} catch (\Throwable $exception) {
\trigger_error("Could not send result to parent; be sure to shutdown the child before ending the parent", E_USER_ERROR);
return 1;
} finally {
$channel->close();
}
return 0;
// @codeCoverageIgnoreEnd
}, [
$this->id,
$this->hub->getUri(),
$this->hub->generateKey($this->id, self::KEY_LENGTH),
$this->script,
$this->args
]);
return call(function () use ($future) {
try {
$this->channel = yield $this->hub->accept($this->id);
$this->hub->add($this->id, $this->channel, $future);
} catch (\Throwable $exception) {
$this->kill();
throw new ContextException("Starting the parallel runtime failed", 0, $exception);
}
if ($this->killed) {
$this->kill();
}
return $this->id;
});
}
/**
* Immediately kills the context.
*/
public function kill()
{
$this->killed = true;
if ($this->runtime !== null) {
try {
$this->runtime->kill();
} finally {
$this->close();
}
}
}
/**
* Closes channel and socket if still open.
*/
private function close()
{
$this->runtime = null;
if ($this->channel !== null) {
$this->channel->close();
}
$this->channel = null;
$this->hub->remove($this->id);
}
/**
* Gets a promise that resolves when the context ends and joins with the
* parent context.
*
* @return \Amp\Promise<mixed>
*
* @throws StatusError Thrown if the context has not been started.
* @throws SynchronizationError Thrown if an exit status object is not received.
* @throws ContextException If the context stops responding.
*/
public function join(): Promise
{
if ($this->channel === null) {
throw new StatusError('The thread has not been started or has already finished.');
}
return call(function () {
try {
$response = yield $this->channel->receive();
$this->close();
} catch (\Throwable $exception) {
$this->kill();
throw new ContextException("Failed to receive result from thread", 0, $exception);
}
if (!$response instanceof ExitResult) {
$this->kill();
throw new SynchronizationError('Did not receive an exit result from thread.');
}
return $response->getResult();
});
}
/**
* {@inheritdoc}
*/
public function receive(): Promise
{
if ($this->channel === null) {
throw new StatusError('The process has not been started.');
}
return call(function () {
$data = yield $this->channel->receive();
if ($data instanceof ExitResult) {
$data = $data->getResult();
throw new SynchronizationError(\sprintf(
'Thread process unexpectedly exited with result of type: %s',
\is_object($data) ? \get_class($data) : \gettype($data)
));
}
return $data;
});
}
/**
* {@inheritdoc}
*/
public function send($data): Promise
{
if ($this->channel === null) {
throw new StatusError('The thread has not been started or has already finished.');
}
if ($data instanceof ExitResult) {
throw new \Error('Cannot send exit result objects.');
}
return $this->channel->send($data);
}
/**
* Returns the ID of the thread. This ID will be unique to this process.
*
* @return int
*
* @throws \Amp\Process\StatusError
*/
public function getId(): int
{
if ($this->id === null) {
throw new StatusError('The thread has not been started');
}
return $this->id;
}
}