Skip to content
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

[9.x] Introducing Signal Traps 🚦 #43933

Merged
merged 24 commits into from
Sep 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/Illuminate/Console/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Command extends SymfonyCommand
use Concerns\CallsCommands,
Concerns\HasParameters,
Concerns\InteractsWithIO,
Concerns\InteractsWithSignals,
Macroable;

/**
Expand Down Expand Up @@ -120,9 +121,13 @@ public function run(InputInterface $input, OutputInterface $output): int

$this->components = $this->laravel->make(Factory::class, ['output' => $this->output]);

return parent::run(
$this->input = $input, $this->output
);
try {
return parent::run(
$this->input = $input, $this->output
);
} finally {
$this->untrap();
}
}

/**
Expand Down
51 changes: 51 additions & 0 deletions src/Illuminate/Console/Concerns/InteractsWithSignals.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Illuminate\Console\Concerns;

use Illuminate\Console\Signals;
use Illuminate\Support\Arr;

trait InteractsWithSignals
{
/**
* The signal registrar instance.
*
* @var \Illuminate\Console\Signals|null
*/
protected $signals;

/**
* Define a callback to be run when the given signal(s) occurs.
*
* @param iterable<array-key, int>|int $signals
* @param callable(int $signal): void $callback
* @return void
*/
public function trap($signals, $callback)
{
Signals::whenAvailable(function () use ($signals, $callback) {
$this->signals ??= new Signals(
$this->getApplication()->getSignalRegistry(),
);

collect(Arr::wrap($signals))
->each(fn ($signal) => $this->signals->register($signal, $callback));
});
}

/**
* Untrap signal handlers set within the command's handler.
*
* @return void
*
* @internal
*/
public function untrap()
{
if (! is_null($this->signals)) {
$this->signals->unregister();

$this->signals = null;
}
}
}
152 changes: 152 additions & 0 deletions src/Illuminate/Console/Signals.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

namespace Illuminate\Console;

/**
* @internal
*/
class Signals
{
/**
* The signal registry instance.
*
* @var \Symfony\Component\Console\SignalRegistry\SignalRegistry
*/
protected $registry;

/**
* The signal registry's previous list of handlers.
*
* @param array<int, array<int, callable>>|null
*/
protected $previousHandlers;

/**
* The current availability resolver, if any.
*
* @param (callable(): bool)|null
*/
protected static $availabilityResolver;

/**
* Create a new signal registrar instance.
*
* @param \Symfony\Component\Console\SignalRegistry\SignalRegistry $registry
* @return void
*/
public function __construct($registry)
nunomaduro marked this conversation as resolved.
Show resolved Hide resolved
{
$this->registry = $registry;

$this->previousHandlers = $this->getHandlers();
}

/**
* Register a new signal handler.
*
* @param int $signal
* @param callable(int $signal): void $callback
* @return void
*/
public function register($signal, $callback)
{
$this->previousHandlers[$signal] ??= $this->initializeSignal($signal);

with($this->getHandlers(), function ($handlers) use ($signal) {
$handlers[$signal] ??= $this->initializeSignal($signal);

$this->setHandlers($handlers);
});

$this->registry->register($signal, $callback);

with($this->getHandlers(), function ($handlers) use ($signal) {
$lastHandlerInserted = array_pop($handlers[$signal]);

array_unshift($handlers[$signal], $lastHandlerInserted);

$this->setHandlers($handlers);
});
}

/**
* Gets the signal's existing handler in array format.
*
* @return array<int, callable(int $signal): void>
*/
protected function initializeSignal($signal)
{
return is_callable($existingHandler = pcntl_signal_get_handler($signal))
? [$existingHandler]
: null;
}

/**
* Unregister the current signal handlers.
*
* @return array<int, array<int, callable(int $signal): void>>
*/
public function unregister()
{
$previousHandlers = $this->previousHandlers;

foreach ($previousHandlers as $signal => $handler) {
if (is_null($handler)) {
pcntl_signal($signal, SIG_DFL);

unset($previousHandlers[$signal]);
}
}

$this->setHandlers($previousHandlers);
}

/**
* Execute the given callback if "signals" should be used and are available.
*
* @param callable $callback
* @return void
*/
public static function whenAvailable($callback)
{
$resolver = static::$availabilityResolver;

if ($resolver()) {
$callback();
}
}

/**
* Get the registry's handlers.
*
* @return array<int, array<int, callable>>
*/
protected function getHandlers()
{
return (fn () => $this->signalHandlers)
->call($this->registry);
}

/**
* Set the registry's handlers.
*
* @param array<int, array<int, callable(int $signal):void>> $handlers
* @return void
nunomaduro marked this conversation as resolved.
Show resolved Hide resolved
*/
protected function setHandlers($handlers)
{
(fn () => $this->signalHandlers = $handlers)
->call($this->registry);
}

/**
* Set the availability resolver.
*
* @param callable(): bool
* @return void
*/
public static function resolveAvailabilityUsing($resolver)
{
static::$availabilityResolver = $resolver;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Illuminate\Console\Scheduling\ScheduleRunCommand;
use Illuminate\Console\Scheduling\ScheduleTestCommand;
use Illuminate\Console\Scheduling\ScheduleWorkCommand;
use Illuminate\Console\Signals;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Database\Console\DbCommand;
use Illuminate\Database\Console\DumpCommand;
Expand Down Expand Up @@ -202,6 +203,12 @@ public function register()
$this->commands,
$this->devCommands
));

Signals::resolveAvailabilityUsing(function () {
return $this->app->runningInConsole()
&& ! $this->app->runningUnitTests()
&& extension_loaded('pcntl');
});
}

/**
Expand Down
127 changes: 127 additions & 0 deletions tests/Console/CommandTrapTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php

namespace Illuminate\Tests\Console;

use Illuminate\Console\Command;
use Illuminate\Console\Signals;
use Illuminate\Tests\Console\Fixtures\FakeSignalsRegistry;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class CommandTrapTest extends TestCase
{
protected $registry;

protected $signals;

protected $state;

protected function setUp(): void
{
Signals::resolveAvailabilityUsing(fn () => true);

$this->registry = new FakeSignalsRegistry();
$this->state = null;
}

protected function tearDown(): void
{
m::close();
}

public function testTrapWhenAvailable()
{
$command = $this->createCommand();

$command->trap('my-signal', function () {
$this->state = 'taylorotwell';
});

$this->registry->handle('my-signal');

$this->assertSame('taylorotwell', $this->state);
}

public function testTrapWhenNotAvailable()
{
Signals::resolveAvailabilityUsing(fn () => false);

$command = $this->createCommand();

$command->trap('my-signal', function () {
$this->state = 'taylorotwell';
});

$this->registry->handle('my-signal');

$this->assertNull($this->state);
}

public function testUntrap()
{
$command = $this->createCommand();

$command->trap('my-signal', function () {
$this->state = 'taylorotwell';
});

$command->untrap();

$this->registry->handle('my-signal');

$this->assertNull($this->state);
}

public function testNestedTraps()
{
$a = $this->createCommand();
$a->trap('my-signal', fn () => $this->state .= '1');

$b = $this->createCommand();
$b->trap('my-signal', fn () => $this->state .= '2');

$c = $this->createCommand();
$c->trap('my-signal', fn () => $this->state .= '3');

$this->state = '';
$this->registry->handle('my-signal');
$this->assertSame('321', $this->state);

$c->untrap();
$this->state = '';
$this->registry->handle('my-signal');
$this->assertSame('21', $this->state);

$d = $this->createCommand();
$d->trap('my-signal', fn () => $this->state .= '3');

$this->state = '';
$this->registry->handle('my-signal');
$this->assertSame('321', $this->state);

$d->untrap();
$this->state = '';
$this->registry->handle('my-signal');
$this->assertSame('21', $this->state);

$b->untrap();
$this->state = '';
$this->registry->handle('my-signal');
$this->assertSame('1', $this->state);

$a->untrap();
$this->state = '';
$this->registry->handle('my-signal');
$this->assertSame('', $this->state);
}

protected function createCommand()
{
$command = new Command;
$registry = $this->registry;

(fn () => $this->signals = new Signals($registry))->call($command);

return $command;
}
}
Loading