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

[Console][FrameworkBundle][HttpKernel][WebProfilerBundle] Enable profiling commands #47416

Merged
merged 1 commit into from
Oct 17, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -33,6 +33,7 @@ CHANGELOG
* 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
* Provide `$buildDir` when running `CacheWarmer` to build read-only resources
* 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;
HeahDude marked this conversation as resolved.
Show resolved Hide resolved

if (!$command instanceof ListCommand) {
if ($this->registrationErrors) {
$this->renderRegistrationErrors($input, $output);
$this->registrationErrors = [];
$renderRegistrationErrors = false;
HeahDude marked this conversation as resolved.
Show resolved Hide resolved
}
}

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
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 @@

$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 @@
{
$loader->load('debug_prod.php');

$debug = $container->getParameter('kernel.debug');
HeahDude marked this conversation as resolved.
Show resolved Hide resolved

if (class_exists(Stopwatch::class)) {
HeahDude marked this conversation as resolved.
Show resolved Hide resolved
$container->register('debug.stopwatch', Stopwatch::class)
->addArgument(true)
->setPublic($debug)

Check failure on line 1147 in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php:1147:29: InvalidArgument: Argument 1 of Symfony\Component\DependencyInjection\Definition::setPublic expects bool, but UnitEnum|array<array-key, mixed>|null|scalar provided (see https://psalm.dev/004)

Check failure on line 1147 in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php:1147:29: InvalidArgument: Argument 1 of Symfony\Component\DependencyInjection\Definition::setPublic expects bool, but UnitEnum|array<array-key, mixed>|null|scalar provided (see https://psalm.dev/004)
->addTag('kernel.reset', ['method' => 'reset']);
$container->setAlias(Stopwatch::class, new Alias('debug.stopwatch', false));
HeahDude marked this conversation as resolved.
Show resolved Hide resolved
}

$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 @@

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,144 @@
<?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', 4096],
ConsoleEvents::ERROR => ['catch', -2048],
ConsoleEvents::TERMINATE => ['profile', -4096],
];
}

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

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();
}

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</>',
HeahDude marked this conversation as resolved.
Show resolved Hide resolved
$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])
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\HttpKernel\Controller\TraceableArgumentResolver;
use Symfony\Component\HttpKernel\Controller\TraceableControllerResolver;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpKernel\Debug\VirtualRequestStack;

return static function (ContainerConfigurator $container) {
$container->services()
Expand All @@ -24,7 +25,7 @@
service('debug.event_dispatcher.inner'),
service('debug.stopwatch'),
service('logger')->nullOnInvalid(),
service('request_stack')->nullOnInvalid(),
service('.virtual_request_stack')->nullOnInvalid(),
])
->tag('monolog.logger', ['channel' => 'event'])
->tag('kernel.reset', ['method' => 'reset'])
Expand All @@ -46,5 +47,9 @@
->set('argument_resolver.not_tagged_controller', NotTaggedControllerValueResolver::class)
->args([abstract_arg('Controller argument, set in FrameworkExtension')])
->tag('controller.argument_value_resolver', ['priority' => -200])

->set('.virtual_request_stack', VirtualRequestStack::class)
->args([service('request_stack')])
->public()
;
};
10 changes: 10 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/profiling.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bundle\FrameworkBundle\EventListener\ConsoleProfilerListener;
use Symfony\Component\HttpKernel\EventListener\ProfilerListener;
use Symfony\Component\HttpKernel\Profiler\FileProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profiler;
Expand All @@ -35,5 +36,14 @@
param('profiler_listener.only_main_requests'),
])
->tag('kernel.event_subscriber')

->set('console_profiler_listener', ConsoleProfilerListener::class)
->args([
service('profiler'),
service('.virtual_request_stack'),
service('debug.stopwatch'),
HeahDude marked this conversation as resolved.
Show resolved Hide resolved
service('router'),
])
->tag('kernel.event_subscriber')
;
};