Skip to content

Add support for distributed tracing when running a console command #460

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

Merged
merged 2 commits into from
Mar 29, 2021
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- Add support for distributed tracing of Symfony request events (#423)
- Add support for distributed tracing of Twig template rendering (#430)
- Add support for distributed tracing of SQL queries while using Doctrine DBAL (#426)
- Add support for distributed tracing when running a console command (#455)
- Added missing `capture-soft-fails` config schema option (#417)
- Deprecate the `Sentry\SentryBundle\EventListener\ConsoleCommandListener` class in favor of its parent class `Sentry\SentryBundle\EventListener\ConsoleListener` (#429)

Expand Down
87 changes: 87 additions & 0 deletions src/EventListener/TracingConsoleListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

namespace Sentry\SentryBundle\EventListener;

use Sentry\State\HubInterface;
use Sentry\Tracing\Span;
use Sentry\Tracing\SpanContext;
use Sentry\Tracing\Transaction;
use Sentry\Tracing\TransactionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;

/**
* This listener either starts a {@see Transaction} or a child {@see Span} when
* a console command is executed to allow measuring the application performances.
*/
final class TracingConsoleListener
{
/**
* @var HubInterface The current hub
*/
private $hub;

/**
* Constructor.
*
* @param HubInterface $hub The current hub
*/
public function __construct(HubInterface $hub)
{
$this->hub = $hub;
}

/**
* Handles the execution of a console command by starting a new {@see Transaction}
* if it doesn't exists, or a child {@see Span} if it does.
*
* @param ConsoleCommandEvent $event The event
*/
public function handleConsoleCommandEvent(ConsoleCommandEvent $event): void
{
$currentSpan = $this->hub->getSpan();

if (null === $currentSpan) {
$transactionContext = new TransactionContext();
$transactionContext->setOp('console.command');
$transactionContext->setName($this->getSpanName($event->getCommand()));

$span = $this->hub->startTransaction($transactionContext);
} else {
$spanContext = new SpanContext();
$spanContext->setOp('console.command');
$spanContext->setDescription($this->getSpanName($event->getCommand()));

$span = $currentSpan->startChild($spanContext);
}

$this->hub->setSpan($span);
}

/**
* Handles the termination of a console command by stopping the active {@see Span}
* or {@see Transaction}.
*
* @param ConsoleTerminateEvent $event The event
*/
public function handleConsoleTerminateEvent(ConsoleTerminateEvent $event): void
{
$span = $this->hub->getSpan();

if (null !== $span) {
$span->finish();
}
}

private function getSpanName(?Command $command): string
{
if (null === $command || null === $command->getName()) {
return '<unnamed command>';
}

return $command->getName();
}
}
7 changes: 7 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@
<tag name="kernel.event_listener" event="kernel.response" method="handleKernelResponseEvent" priority="15" />
</service>

<service id="Sentry\SentryBundle\EventListener\TracingConsoleListener" class="Sentry\SentryBundle\EventListener\TracingConsoleListener">
<argument type="service" id="Sentry\State\HubInterface" />

<tag name="kernel.event_listener" event="console.command" method="handleConsoleCommandEvent" priority="118" />
<tag name="kernel.event_listener" event="console.terminate" method="handleConsoleTerminateEvent" priority="-54" />
</service>

<service id="Sentry\SentryBundle\EventListener\MessengerListener" class="Sentry\SentryBundle\EventListener\MessengerListener">
<argument type="service" id="Sentry\State\HubInterface" />

Expand Down
185 changes: 185 additions & 0 deletions tests/EventListener/TracingConsoleListenerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
<?php

declare(strict_types=1);

namespace Sentry\SentryBundle\Tests\EventListener;

use Generator;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sentry\SentryBundle\EventListener\TracingConsoleListener;
use Sentry\State\HubInterface;
use Sentry\Tracing\Span;
use Sentry\Tracing\Transaction;
use Sentry\Tracing\TransactionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

final class TracingConsoleListenerTest extends TestCase
{
/**
* @var MockObject&HubInterface
*/
private $hub;

/**
* @var TracingConsoleListener
*/
private $listener;

protected function setUp(): void
{
$this->hub = $this->createMock(HubInterface::class);
$this->listener = new TracingConsoleListener($this->hub);
}

/**
* @dataProvider handleConsoleCommandEventStartsTransactionIfNoSpanIsSetOnHubDataProvider
*/
public function testHandleConsoleCommandEventStartsTransactionIfNoSpanIsSetOnHub(?Command $command, TransactionContext $expectedTransactionContext): void
{
$transaction = new Transaction(new TransactionContext());

$this->hub->expects($this->once())
->method('getSpan')
->willReturn(null);

$this->hub->expects($this->once())
->method('startTransaction')
->with($this->callback(function (TransactionContext $context) use ($expectedTransactionContext): bool {
$this->assertEquals($expectedTransactionContext, $context);

return true;
}))
->willReturn($transaction);

$this->hub->expects($this->once())
->method('setSpan')
->with($transaction)
->willReturnSelf();

$this->listener->handleConsoleCommandEvent(new ConsoleCommandEvent(
$command,
$this->createMock(InputInterface::class),
$this->createMock(OutputInterface::class)
));
}

/**
* @return Generator<mixed>
*/
public function handleConsoleCommandEventStartsTransactionIfNoSpanIsSetOnHubDataProvider(): Generator
{
$transactionContext = new TransactionContext();
$transactionContext->setOp('console.command');
$transactionContext->setName('<unnamed command>');

yield [
null,
$transactionContext,
];

$transactionContext = new TransactionContext();
$transactionContext->setOp('console.command');
$transactionContext->setName('<unnamed command>');

yield [
new Command(),
$transactionContext,
];

$transactionContext = new TransactionContext();
$transactionContext->setOp('console.command');
$transactionContext->setName('app:command');

yield [
new Command('app:command'),
$transactionContext,
];
}

/**
* @dataProvider handleConsoleCommandEventStartsChildSpanIfSpanIsSetOnHubDataProvider
*/
public function testHandleConsoleCommandEventStartsChildSpanIfSpanIsSetOnHub(?Command $command, string $expectedDescription): void
{
$span = new Span();

$this->hub->expects($this->once())
->method('getSpan')
->willReturn($span);

$this->hub->expects($this->once())
->method('setSpan')
->with($this->callback(function (Span $spanArg) use ($span, $expectedDescription): bool {
$this->assertSame('console.command', $spanArg->getOp());
$this->assertSame($expectedDescription, $spanArg->getDescription());
$this->assertSame($span->getSpanId(), $spanArg->getParentSpanId());

return true;
}))
->willReturnSelf();

$this->listener->handleConsoleCommandEvent(new ConsoleCommandEvent(
$command,
$this->createMock(InputInterface::class),
$this->createMock(OutputInterface::class)
));
}

/**
* @return Generator<mixed>
*/
public function handleConsoleCommandEventStartsChildSpanIfSpanIsSetOnHubDataProvider(): Generator
{
yield [
null,
'<unnamed command>',
];

yield [
new Command(),
'<unnamed command>',
];

yield [
new Command('app:command'),
'app:command',
];
}

public function testHandleConsoleTerminateEvent(): void
{
$span = new Span();

$this->hub->expects($this->once())
->method('getSpan')
->willReturn($span);

$this->listener->handleConsoleTerminateEvent(new ConsoleTerminateEvent(
new Command(),
$this->createMock(InputInterface::class),
$this->createMock(OutputInterface::class),
0
));

$this->assertNotNull($span->getEndTimestamp());
}

public function testHandleConsoleTerminateEventDoesNothingIfNoSpanIsSetOnHub(): void
{
$this->hub->expects($this->once())
->method('getSpan')
->willReturn(null);

$this->listener->handleConsoleTerminateEvent(new ConsoleTerminateEvent(
new Command(),
$this->createMock(InputInterface::class),
$this->createMock(OutputInterface::class),
0
));
}
}