Skip to content
Snippets Groups Projects

Issue #3205502: Add a flood table record metric

1 file
+ 93
0
Compare changes
  • Side-by-side
  • Inline
<?php
namespace Drupal\prometheus_exporter\Plugin\MetricsCollector;
use Drupal\Core\Database\Connection;
use Drupal\Core\Flood\DatabaseBackend;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\prometheus_exporter\Plugin\BaseMetricsCollector;
use PNX\Prometheus\Gauge;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Collects metrics for the number of Flood entries.
*
* @MetricsCollector(
* id = "flood_count",
* title = @Translation("Flood count"),
* description = @Translation("Provides metrics for the number of Flood entries.")
* )
*/
class FloodCountCollector extends BaseMetricsCollector implements ContainerFactoryPluginInterface {
/**
* The PDO database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* FloodCountCollector constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Database\Connection $connection
* The PDO database connection.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->connection = $connection;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('database')
);
}
/**
* {@inheritdoc}
*/
public function collectMetrics() {
$gauge = new Gauge($this->getNamespace(), 'total', $this->getDescription());
foreach ($this->query() as $event => $count) {
$gauge->set($count, ['event' => $event]);
}
$metrics[] = $gauge;
return $metrics;
}
/**
* Query the number of records in the flood table.
*
* @return array
* Associative array of the number of events, keyed by the event type.
*/
protected function query() {
// The flood table is generated on-demand and may not exist.
if (!$this->connection->schema()->tableExists(DatabaseBackend::TABLE_NAME)) {
return [];
}
$query = $this->connection->select(DatabaseBackend::TABLE_NAME, 'flood')
->fields('flood', ['event'])
->groupBy('event');
$query->addExpression('count(fid)', 'count');
return $query
->execute()
->fetchAllKeyed(0, 1);
}
}
Loading