Skip to content

Commit

Permalink
[Console][FrameworkBundle][HttpKernel][WebProfilerBundle] Enable prof…
Browse files Browse the repository at this point in the history
…iling commands
  • Loading branch information
HeahDude committed Oct 17, 2023
1 parent abe5555 commit 2f5ea2e
Show file tree
Hide file tree
Showing 33 changed files with 1,603 additions and 149 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
service('debug.stopwatch')->ignoreOnInvalid(),
service('debug.file_link_formatter')->ignoreOnInvalid(),
param('kernel.charset'),
service('request_stack'),
service('.virtual_request_stack'),
null, // var_dumper.cli_dumper or var_dumper.server_connection when debug.dump_destination is set
])
->tag('data_collector', [
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ CHANGELOG
* Add `--exclude` option to the `cache:pool:clear` command
* Add parameters deprecations to the output of `debug:container` command
* Change `framework.asset_mapper.importmap_polyfill` from a URL to the name of an item in the importmap
* Add the global `--profile` option to the console to enable profiling commands

6.3
---
Expand Down
38 changes: 35 additions & 3 deletions src/Symfony/Bundle/FrameworkBundle/Console/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\Command\TraceableCommand;
use Symfony\Component\Console\Debug\CliRequest;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
Expand Down Expand Up @@ -42,6 +44,7 @@ public function __construct(KernelInterface $kernel)
$inputDefinition = $this->getDefinition();
$inputDefinition->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment()));
$inputDefinition->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switch off debug mode.'));
$inputDefinition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Enables profiling (requires debug).'));
}

/**
Expand Down Expand Up @@ -79,18 +82,47 @@ public function doRun(InputInterface $input, OutputInterface $output): int

protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int
{
$requestStack = null;
$renderRegistrationErrors = true;

if (!$command instanceof ListCommand) {
if ($this->registrationErrors) {
$this->renderRegistrationErrors($input, $output);
$this->registrationErrors = [];
$renderRegistrationErrors = false;
}
}

if ($input->hasParameterOption('--profile')) {
$container = $this->kernel->getContainer();

return parent::doRunCommand($command, $input, $output);
if (!$this->kernel->isDebug()) {
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}

(new SymfonyStyle($input, $output))->warning('Debug mode should be enabled when the "--profile" option is used.');
} elseif (!$container->has('debug.stopwatch')) {
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}

(new SymfonyStyle($input, $output))->warning('The "--profile" option needs the Stopwatch component. Try running "composer require symfony/stopwatch".');
} else {
$command = new TraceableCommand($command, $container->get('debug.stopwatch'));

$requestStack = $container->get('.virtual_request_stack');
$requestStack->push(new CliRequest($command));
}
}

$returnCode = parent::doRunCommand($command, $input, $output);
try {
$returnCode = parent::doRunCommand($command, $input, $output);
} finally {
$requestStack?->pop();
}

if ($this->registrationErrors) {
if ($renderRegistrationErrors && $this->registrationErrors) {
$this->renderRegistrationErrors($input, $output);
$this->registrationErrors = [];
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Debug;

use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Debug\CliRequest;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher as BaseTraceableEventDispatcher;
use Symfony\Component\Stopwatch\Stopwatch;

/**
* @internal
*
* @author Jules Pietri <jules@heahprod.com>
*/
final class TraceableEventDispatcher extends BaseTraceableEventDispatcher
{
public function __construct(
EventDispatcherInterface $dispatcher,
Stopwatch $stopwatch,
LoggerInterface $logger = null,
private readonly ?RequestStack $requestStack = null
) {
parent::__construct($dispatcher, $stopwatch, $logger, $requestStack);
}

/**
* Starts a stopwatch section before a command runs to profile listeners.
*/
protected function beforeDispatch(string $eventName, object $event): void
{
if (!$event instanceof ConsoleCommandEvent) {
parent::beforeDispatch($eventName, $event);

return;
}

$request = $this->requestStack->getCurrentRequest();

if (!$request instanceof CliRequest || $request->command !== $event->getCommand()) {
return;
}

$request->attributes->set('_stopwatch_token', substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6));
$this->stopwatch->openSection();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
use Symfony\Component\Config\ResourceCheckerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Debug\CliRequest;
use Symfony\Component\Console\Messenger\RunCommandMessageHandler;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand Down Expand Up @@ -912,6 +913,10 @@ private function registerProfilerConfiguration(array $config, ContainerBuilder $

$container->getDefinition('profiler_listener')
->addArgument($config['collect_parameter']);

if (!$container->getParameter('kernel.debug') || !class_exists(CliRequest::class) || !$container->has('debug.stopwatch')) {
$container->removeDefinition('console_profiler_listener');
}
}

private function registerWorkflowConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader): void
Expand Down Expand Up @@ -1134,15 +1139,16 @@ private function registerDebugConfiguration(array $config, ContainerBuilder $con
{
$loader->load('debug_prod.php');

$debug = $container->getParameter('kernel.debug');

if (class_exists(Stopwatch::class)) {
$container->register('debug.stopwatch', Stopwatch::class)
->addArgument(true)
->setPublic($debug)
->addTag('kernel.reset', ['method' => 'reset']);
$container->setAlias(Stopwatch::class, new Alias('debug.stopwatch', false));
}

$debug = $container->getParameter('kernel.debug');

if ($debug && !$container->hasParameter('debug.container.dump')) {
$container->setParameter('debug.container.dump', '%kernel.build_dir%/%kernel.container_class%.xml');
}
Expand All @@ -1165,7 +1171,7 @@ private function registerDebugConfiguration(array $config, ContainerBuilder $con

if ($debug && class_exists(DebugProcessor::class)) {
$definition = new Definition(DebugProcessor::class);
$definition->addArgument(new Reference('request_stack'));
$definition->addArgument(new Reference('.virtual_request_stack'));
$definition->addTag('kernel.reset', ['method' => 'reset']);
$container->setDefinition('debug.log_processor', $definition);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\EventListener;

use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Debug\CliRequest;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Stopwatch\Stopwatch;

/**
* @internal
*
* @author Jules Pietri <jules@heahprod.com>
*/
final class ConsoleProfilerListener implements EventSubscriberInterface
{
private ?\Throwable $error = null;
/** @var \SplObjectStorage<Request, Profile> */
private \SplObjectStorage $profiles;
/** @var \SplObjectStorage<Request, ?Request> */
private \SplObjectStorage $parents;

public function __construct(
private readonly Profiler $profiler,
private readonly RequestStack $requestStack,
private readonly Stopwatch $stopwatch,
private readonly UrlGeneratorInterface $urlGenerator,
) {
$this->profiles = new \SplObjectStorage();
$this->parents = new \SplObjectStorage();
}

public static function getSubscribedEvents(): array
{
return [
ConsoleEvents::COMMAND => ['initialize', 2048],
ConsoleEvents::ERROR => ['catch', -2048],
ConsoleEvents::TERMINATE => ['profile', -2048],
];
}

public function initialize(ConsoleCommandEvent $event): void
{
if (!$event->getInput()->getOption('profile')) {
$this->profiler->disable();
}
}

public function catch(ConsoleErrorEvent $event): void
{
$this->error = $event->getError();
}

public function profile(ConsoleTerminateEvent $event): void
{
if (!$this->profiler->isEnabled()) {
return;
}

$request = $this->requestStack->getCurrentRequest();

if (!$request instanceof CliRequest || $request->command !== $event->getCommand()) {
return;
}

if (null !== $sectionId = $request->attributes->get('_stopwatch_token')) {
// we must close the section before saving the profile to allow late collect
try {
$this->stopwatch->stopSection($sectionId);
} catch (\LogicException) {
// noop
}
}

$request->command->exitCode = $event->getExitCode();
$request->command->interruptedBySignal = $event->getInterruptingSignal();

$profile = $this->profiler->collect($request, $request->getResponse(), $this->error);
$this->error = null;
$this->profiles[$request] = $profile;

if ($this->parents[$request] = $this->requestStack->getParentRequest()) {
// do not save on sub commands
return;
}

// attach children to parents
foreach ($this->profiles as $request) {
if (null !== $parentRequest = $this->parents[$request]) {
if (isset($this->profiles[$parentRequest])) {
$this->profiles[$parentRequest]->addChild($this->profiles[$request]);
}
}
}

$output = $event->getOutput();
$output = $output instanceof ConsoleOutputInterface && $output->isVerbose() ? $output->getErrorOutput() : null;

// save profiles
foreach ($this->profiles as $r) {
$p = $this->profiles[$r];
$this->profiler->saveProfile($p);

$token = $p->getToken();
$output?->writeln(sprintf(
'See profile <href=%s>%s</>',
$this->urlGenerator->generate('_profiler', ['token' => $token], UrlGeneratorInterface::ABSOLUTE_URL),
$token
));
}

$this->profiles = new \SplObjectStorage();
$this->parents = new \SplObjectStorage();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector;
use Symfony\Component\Console\DataCollector\CommandDataCollector;
use Symfony\Component\HttpKernel\DataCollector\AjaxDataCollector;
use Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\DataCollector\EventDataCollector;
Expand All @@ -30,7 +31,7 @@

->set('data_collector.request', RequestDataCollector::class)
->args([
service('request_stack')->ignoreOnInvalid(),
service('.virtual_request_stack')->ignoreOnInvalid(),
])
->tag('kernel.event_subscriber')
->tag('data_collector', ['template' => '@WebProfiler/Collector/request.html.twig', 'id' => 'request', 'priority' => 335])
Expand All @@ -48,15 +49,15 @@
->set('data_collector.events', EventDataCollector::class)
->args([
tagged_iterator('event_dispatcher.dispatcher', 'name'),
service('request_stack')->ignoreOnInvalid(),
service('.virtual_request_stack')->ignoreOnInvalid(),
])
->tag('data_collector', ['template' => '@WebProfiler/Collector/events.html.twig', 'id' => 'events', 'priority' => 290])

->set('data_collector.logger', LoggerDataCollector::class)
->args([
service('logger')->ignoreOnInvalid(),
sprintf('%s/%s', param('kernel.build_dir'), param('kernel.container_class')),
service('request_stack')->ignoreOnInvalid(),
service('.virtual_request_stack')->ignoreOnInvalid(),
])
->tag('monolog.logger', ['channel' => 'profiler'])
->tag('data_collector', ['template' => '@WebProfiler/Collector/logger.html.twig', 'id' => 'logger', 'priority' => 300])
Expand All @@ -74,5 +75,8 @@
->set('data_collector.router', RouterDataCollector::class)
->tag('kernel.event_listener', ['event' => KernelEvents::CONTROLLER, 'method' => 'onKernelController'])
->tag('data_collector', ['template' => '@WebProfiler/Collector/router.html.twig', 'id' => 'router', 'priority' => 285])

->set('.data_collector.command', CommandDataCollector::class)
->tag('data_collector', ['template' => '@WebProfiler/Collector/command.html.twig', 'id' => 'command', 'priority' => 335])
;
};

0 comments on commit 2f5ea2e

Please sign in to comment.