monitoring-8.x-1.x-dev/src/Plugin/monitoring/SensorPlugin/OpCacheMemoryUsageSensorPlugin.php
src/Plugin/monitoring/SensorPlugin/OpCacheMemoryUsageSensorPlugin.php
<?php
/**
* @file
* Contains \Drupal\monitoring\Plugin\monitoring\SensorPlugin\TwigDebugSensorPlugin.
*/
namespace Drupal\monitoring\Plugin\monitoring\SensorPlugin;
use Drupal\Component\Utility\Bytes;
use Drupal\Core\StringTranslation\ByteSizeMarkup;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\monitoring\Attribute\SensorPlugin;
use Drupal\monitoring\Result\SensorResultInterface;
use Drupal\monitoring\SensorPlugin\SensorPluginBase;
/**
* Monitors the OPcache memory usage
*/
#[SensorPlugin(
id: 'opcache_usage',
label: new TranslatableMarkup('OPcache usage'),
addable: FALSE,
metric_type: 'gauge',
)]
class OpCacheMemoryUsageSensorPlugin extends SensorPluginBase {
/**
* {@inheritdoc}
*/
public function runSensor(SensorResultInterface $sensor_result) {
if (!ini_get('opcache.enable') || !function_exists('apcu_cache_info')) {
$sensor_result->setValue(0);
$sensor_result->setStatus(SensorResultInterface::STATUS_UNKNOWN);
$sensor_result->setMessage('OPCache not enabled');
return;
}
if (php_sapi_name() === 'cli') {
$sensor_result->setValue(0);
$sensor_result->setStatus(SensorResultInterface::STATUS_UNKNOWN);
$sensor_result->setMessage('CLI OPcache information not representative, skipped');
return;
}
$status = opcache_get_status(FALSE);
$used = $status['memory_usage']['used_memory'];
$free = $status['memory_usage']['free_memory'];
$sensor_result->setValue(round(100 / ($used + $free) * $used, 2));
$sensor_result->addStatusMessage(ByteSizeMarkup::create($used) . ' of ' . ByteSizeMarkup::create($used + $free));
$sensor_result->addStatusMessage(round($status['opcache_statistics']['opcache_hit_rate'], 2) . '% hit rate');
foreach (['oom', 'hash', 'manual'] as $type) {
if (!empty($status['opcache_statistics'][$type . '_restarts'])) {
$sensor_result->addStatusMessage($status['opcache_statistics'][$type . '_restarts'] . ' ' . $type . ' restarts');
}
}
}
}
