Skip to content

Commit 446ce6e

Browse files
Integrated shutdown exception to be triggered following SIGINT and after the connection pool had been shutdown
1 parent 2dd19e3 commit 446ce6e

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed

src/Daemon.php

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PHPFastCGI\FastCGIDaemon\Connection\ConnectionPoolInterface;
66
use PHPFastCGI\FastCGIDaemon\ConnectionHandler\ConnectionHandlerFactoryInterface;
7+
use PHPFastCGI\FastCGIDaemon\Exception\ShutdownException;
78
use Psr\Log\LoggerAwareInterface;
89
use Psr\Log\LoggerAwareTrait;
910
use Psr\Log\LoggerInterface;
@@ -55,18 +56,24 @@ public function __construct(ConnectionPoolInterface $connectionPool, ConnectionH
5556
*/
5657
public function run()
5758
{
59+
declare(ticks = 1);
60+
61+
pcntl_signal(SIGINT, function () {
62+
$this->connectionPool->shutdown();
63+
throw new ShutdownException('Received SIGINT, shutting down...');
64+
});
65+
5866
try {
5967
while (1) {
6068
$this->connectionPool->operate($this->connectionHandlerFactory, 5);
6169
// @codeCoverageIgnoreStart
6270
}
6371
// @codeCoverageIgnoreEnd
72+
} catch (ShutdownException $exception) {
73+
$this->logger->notice($exception->getMessage());
6474
} catch (\RuntimeException $exception) {
6575
$this->logger->emergency($exception->getMessage());
6676
throw $exception;
6777
}
68-
69-
// @codeCoverageIgnoreStart
7078
}
71-
// @codeCoverageIgnoreEnd
7279
}

test/DaemonTest.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ public function testRun()
3030

3131
throw new \RuntimeException('foo');
3232
};
33-
3433
$mockConnectionPool = new CallableConnectionPool($connectionPoolCallback);
3534

3635
// Create daemon
@@ -51,4 +50,31 @@ public function testRun()
5150
$this->assertEquals('foo', $messages[0]['message']);
5251
}
5352
}
53+
54+
/**
55+
* Tests that the daemon shuts down cleanly after a SIGINT
56+
*/
57+
public function testInterruptSignal()
58+
{
59+
$logger = new InMemoryLogger;
60+
61+
// Create mock connection handler factory
62+
$mockConnectionHandlerFactory = new CallableConnectionHandlerFactory(function () { });
63+
64+
// Create mock connection pool that sends a SIGINT to itself immediately
65+
$connectionPoolCallback = function () {
66+
posix_kill(posix_getpid(), SIGINT);
67+
};
68+
$mockConnectionPool = new CallableConnectionPool($connectionPoolCallback);
69+
70+
// Create daemon
71+
$daemon = new Daemon($mockConnectionPool, $mockConnectionHandlerFactory, $logger);
72+
73+
$daemon->run();
74+
75+
// Check that the daemon exits and the correct message is logged
76+
$messages = $logger->getMessages();
77+
$this->assertEquals('notice', $messages[0]['level']);
78+
$this->assertEquals('Received SIGINT, shutting down...', $messages[0]['message']);
79+
}
5480
}

0 commit comments

Comments
 (0)