forked from spatie/fork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fork.php
231 lines (172 loc) · 5.26 KB
/
Fork.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
<?php
namespace Spatie\Fork;
use Closure;
use Exception;
class Fork
{
protected ?Closure $toExecuteBeforeInChildTask = null;
protected ?Closure $toExecuteBeforeInParentTask = null;
protected ?Closure $toExecuteAfterInChildTask = null;
protected ?Closure $toExecuteAfterInParentTask = null;
protected ?int $concurrent = null;
/** @var \Spatie\Fork\Task[] */
protected array $queue = [];
/** @var \Spatie\Fork\Task[] */
protected array $runningTasks = [];
public function __construct()
{
if (! function_exists('pcntl_fork')) {
throw new Exception("Cannot create process forks: PCNTL is not supported on this system.");
}
}
public static function new(): self
{
return new self();
}
public function before(callable $child = null, callable $parent = null): self
{
$this->toExecuteBeforeInChildTask = $child;
$this->toExecuteBeforeInParentTask = $parent;
return $this;
}
public function after(callable $child = null, callable $parent = null): self
{
$this->toExecuteAfterInChildTask = $child;
$this->toExecuteAfterInParentTask = $parent;
return $this;
}
public function concurrent(int $concurrent): self
{
$this->concurrent = $concurrent;
return $this;
}
public function run(callable ...$callables): array
{
$tasks = [];
foreach ($callables as $order => $callable) {
$tasks[] = Task::fromCallable($callable, $order);
}
return $this->waitFor(...$tasks);
}
protected function waitFor(Task ...$queue): array
{
$output = [];
$this->listenForSignals();
$this->startRunning(...$queue);
while ($this->isRunning()) {
foreach ($this->runningTasks as $task) {
if (! $task->isFinished()) {
continue;
}
$output[$task->order()] = $this->finishTask($task);
$this->shiftTaskFromQueue();
}
if ($this->isRunning()) {
usleep(1_000);
}
}
return $output;
}
protected function runTask(Task $task): Task
{
if ($this->toExecuteBeforeInParentTask) {
($this->toExecuteBeforeInParentTask)();
}
return $this->forkForTask($task);
}
protected function finishTask(Task $task): mixed
{
$output = $task->output();
if ($this->toExecuteAfterInParentTask) {
($this->toExecuteAfterInParentTask)($output);
}
unset($this->runningTasks[$task->order()]);
return $output;
}
protected function forkForTask(Task $task): Task
{
[$socketToParent, $socketToChild] = Connection::createPair();
$processId = pcntl_fork();
if ($this->currentlyInChildTask($processId)) {
$socketToChild->close();
try {
$this->executeInChildTask($task, $socketToParent);
} finally {
exit();
}
}
$socketToParent->close();
return $task
->setStartTime(time())
->setPid($processId)
->setConnection($socketToChild);
}
/**
* Enable async signals for the process.
*
* @return void
*/
protected function listenForSignals(): void
{
pcntl_async_signals(true);
pcntl_signal(SIGQUIT, fn () => $this->exit());
pcntl_signal(SIGTERM, fn () => $this->exit());
pcntl_signal(SIGINT, fn () => $this->exit());
}
protected function exit(): void
{
if (! extension_loaded('posix')) {
exit;
}
foreach ($this->runningTasks as $task) {
posix_kill($task->pid(), SIGKILL);
}
posix_kill(getmypid(), SIGKILL);
}
protected function currentlyInChildTask(int $pid): bool
{
return $pid === 0;
}
protected function executeInChildTask(
Task $task,
Connection $connectionToParent,
): void {
if ($this->toExecuteBeforeInChildTask) {
($this->toExecuteBeforeInChildTask)();
}
$output = $task->execute();
$connectionToParent->write($output);
if ($this->toExecuteAfterInChildTask) {
($this->toExecuteAfterInChildTask)($output);
}
$connectionToParent->close();
}
protected function shiftTaskFromQueue(): void
{
if (! count($this->queue)) {
return;
}
$firstTask = array_shift($this->queue);
$this->runningTasks[] = $this->runTask($firstTask);
}
protected function startRunning(
Task ...$queue
): void {
$this->queue = $queue;
foreach ($this->queue as $task) {
$this->runningTasks[$task->order()] = $this->runTask($task);
unset($this->queue[$task->order()]);
if ($this->concurrencyLimitReached()) {
break;
}
}
}
protected function isRunning(): bool
{
return count($this->runningTasks) > 0;
}
protected function concurrencyLimitReached(): bool
{
return $this->concurrent && count($this->runningTasks) >= $this->concurrent;
}
}