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

Add Cron Jobs names to New Relic transactions #23784

Closed
54 changes: 39 additions & 15 deletions app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/**
* Handling cron jobs
*/

namespace Magento\Cron\Observer;

use Magento\Cron\Model\Schedule;
Expand Down Expand Up @@ -69,6 +71,11 @@ class ProcessCronQueueObserver implements ObserverInterface
*/
const LOCK_PREFIX = 'CRON_GROUP_';

/**
* Cron Job name pattern for Profiling
*/
private const CRON_TIMERID = 'job %s';

/**
* @var \Magento\Cron\Model\ResourceModel\Schedule\Collection
*/
Expand Down Expand Up @@ -311,7 +318,7 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule,

$schedule->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp()))->save();

$this->startProfiling();
$this->startProfiling($jobCode);
try {
$this->logger->info(sprintf('Cron Job %s is run', $jobCode));
//phpcs:ignore Magento2.Functions.DiscouragedFunction
Expand All @@ -323,7 +330,7 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule,
'Cron Job %s has an error: %s. Statistics: %s',
$jobCode,
$e->getMessage(),
$this->getProfilingStat()
$this->getProfilingStat($jobCode)
)
);
if (!$e instanceof \Exception) {
Expand All @@ -335,7 +342,7 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule,
}
throw $e;
} finally {
$this->stopProfiling();
$this->stopProfiling($jobCode);
}

$schedule->setStatus(
Expand All @@ -351,40 +358,55 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule,
sprintf(
'Cron Job %s is successfully finished. Statistics: %s',
$jobCode,
$this->getProfilingStat()
$this->getProfilingStat($jobCode)
)
);
}

/**
* Starts profiling
*
* @param string $jobName
* @return void
*/
private function startProfiling()
private function startProfiling(string $jobName)
{
$this->statProfiler->clear();
$this->statProfiler->start('job', microtime(true), memory_get_usage(true), memory_get_usage());
$this->statProfiler->start(
sprintf(self::CRON_TIMERID, $jobName),
microtime(true),
memory_get_usage(true),
memory_get_usage()
);
}

/**
* Stops profiling
*
* @param string $jobName
* @return void
*/
private function stopProfiling()
private function stopProfiling(string $jobName)
{
$this->statProfiler->stop('job', microtime(true), memory_get_usage(true), memory_get_usage());
$this->statProfiler->stop(
sprintf(self::CRON_TIMERID, $jobName),
microtime(true),
memory_get_usage(true),
memory_get_usage()
);
}

/**
* Retrieves statistics in the JSON format
*
* @param string $jobName
* @return string
*/
private function getProfilingStat()
private function getProfilingStat(string $jobName): string
{
$stat = $this->statProfiler->get('job');
$stat = $this->statProfiler->get(
sprintf(self::CRON_TIMERID, $jobName)
);
unset($stat[Stat::START]);
return json_encode($stat);
}
Expand Down Expand Up @@ -418,7 +440,9 @@ private function getNonExitedSchedules($groupId)
'status',
[
'in' => [
Schedule::STATUS_PENDING, Schedule::STATUS_RUNNING, Schedule::STATUS_SUCCESS
Schedule::STATUS_PENDING,
Schedule::STATUS_RUNNING,
Schedule::STATUS_SUCCESS
]
]
);
Expand Down Expand Up @@ -478,10 +502,10 @@ private function generateSchedules($groupId)
/**
* Generate jobs for config information
*
* @param array $jobs
* @param array $exists
* @param string $groupId
* @return void
* @param array $jobs
* @param array $exists
* @param string $groupId
* @return void
*/
protected function _generateJobs($jobs, $exists, $groupId)
{
Expand Down
33 changes: 33 additions & 0 deletions app/code/Magento/NewRelicReporting/Model/NewRelicWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
*/
class NewRelicWrapper
{
/**
* @TODO Remove this in 2.4-dev branch
* @var bool
*/
private $transactionOpen = false;

/**
* Wrapper for 'newrelic_add_custom_parameter' function
*
Expand Down Expand Up @@ -49,8 +55,15 @@ public function reportError($exception)
*/
public function setAppName(string $appName)
{
if ($this->transactionOpen === true) {
$this->endTransaction();
}

if ($this->isExtensionInstalled()) {
newrelic_set_appname($appName);

// Remove following line in 2.4-dev branch
$this->transactionOpen = true;
}
}

Expand All @@ -67,6 +80,26 @@ public function setTransactionName(string $transactionName): void
}
}

/**
* Wrapper for 'newrelic_end_transaction'
* Cannot be public in 2.3-dev due to Backward Compatibility
*
* @see https://devdocs.magento.com/guides/v2.3/contributor-guide/backward-compatible-development/
* @TODO Make it public in 2.4-dev branch.
*
* @param bool $ignore
* @return void
*/
private function endTransaction($ignore = false)
{
if ($this->isExtensionInstalled()) {
newrelic_end_transaction($ignore);

// @TODO Remove following line in 2.4-dev branch
$this->transactionOpen = false;
}
}

/**
* Checks whether newrelic-php5 agent is installed
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);

namespace Magento\NewRelicReporting\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

/**
* @TODO Remove with all the uses in 2.4-dev branch
* @package Magento\NewRelicReporting\Observer
*/
class NewrelicEndTransactionObserver implements ObserverInterface
{
/**
* @param Observer $observer
* @return void
*/
public function execute(Observer $observer)
{
$this->endTransaction(true);
}

/**
* @param bool $ignore
* @return void
*/
private function endTransaction($ignore = false)
{
if ($this->isExtensionInstalled()) {
newrelic_end_transaction($ignore);
}
}

/**
* Checks whether newrelic-php5 agent is installed
*
* @return bool
*/
public function isExtensionInstalled()
{
if (extension_loaded('newrelic')) {
return true;
}
return false;
}
}
18 changes: 14 additions & 4 deletions app/code/Magento/NewRelicReporting/Plugin/CommandPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,24 @@ class CommandPlugin
*/
private $newRelicWrapper;

/**
* @var string[]
*/
private $skipCommands;

/**
* @param Config $config
* @param NewRelicWrapper $newRelicWrapper
* @param array $skipCommands
*/
public function __construct(
Config $config,
NewRelicWrapper $newRelicWrapper
NewRelicWrapper $newRelicWrapper,
array $skipCommands = []
) {
$this->config = $config;
$this->newRelicWrapper = $newRelicWrapper;
$this->skipCommands = $skipCommands;
}

/**
Expand All @@ -46,9 +54,11 @@ public function __construct(
*/
public function beforeRun(Command $command, ...$args)
{
$this->newRelicWrapper->setTransactionName(
sprintf('CLI %s', $command->getName())
);
if (!in_array($command->getName(), $this->skipCommands)) {
$this->newRelicWrapper->setTransactionName(
sprintf('CLI %s', $command->getName())
);
}

return $args;
}
Expand Down
101 changes: 101 additions & 0 deletions app/code/Magento/NewRelicReporting/Plugin/StatPlugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\NewRelicReporting\Plugin;

use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Profiler\Driver\Standard\Stat;
use Magento\NewRelicReporting\Model\Config;
use Magento\NewRelicReporting\Model\NewRelicWrapper;
use Psr\Log\LoggerInterface;

/**
* Class StatPlugin handles single Cron Jobs transaction names
*/
class StatPlugin
{
private const TIMER_NAME_CRON_PREFIX = 'job';

/**
* @var Config
*/
private $config;

/**
* @var NewRelicWrapper
*/
private $newRelicWrapper;

/**
* @var LoggerInterface
*/
private $logger;

/**
* @var ManagerInterface
*/
private $eventManager;

/**
* @param Config $config
* @param NewRelicWrapper $newRelicWrapper
* @param LoggerInterface $logger
* @param ManagerInterface $eventManager
*/
public function __construct(
Config $config,
NewRelicWrapper $newRelicWrapper,
LoggerInterface $logger,
ManagerInterface $eventManager
) {
$this->config = $config;
$this->newRelicWrapper = $newRelicWrapper;
$this->logger = $logger;
$this->eventManager = $eventManager;
}

/**
* Before running original profiler, register NewRelic transaction
*
* @param Stat $schedule
* @param array $args
* @return array
* @see \Magento\Cron\Observer\ProcessCronQueueObserver::startProfiling
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeStart(Stat $schedule, ...$args): array
{
$timerName = current($args);

if (0 === strpos($timerName, static::TIMER_NAME_CRON_PREFIX)) {
$this->newRelicWrapper->setTransactionName(
sprintf('Cron %s', $timerName)
);
}

return $args;
}

/**
* Before stopping original profiler, close NewRelic transaction
*
* @TODO Replace with direct call to newRelicWrapper->endTransaction() in 2.4-dev branch
*
* @param Stat $schedule
* @param array $args
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeStop(Stat $schedule, ...$args): array
{
$this->eventManager->dispatch('newrelic_end_transaction');

return $args;
}
}
Loading