You are here

class DiskUsageSensorPlugin in Monitoring 8

Monitors disk space usage.

Plugin annotation


@SensorPlugin(
  id = "disk_usage",
  label = @Translation("Disk Usage"),
  description = @Translation("Monitors disk space usage."),
  addable = TRUE
)

Hierarchy

Expanded class hierarchy of DiskUsageSensorPlugin

File

src/Plugin/monitoring/SensorPlugin/DiskUsageSensorPlugin.php, line 23

Namespace

Drupal\monitoring\Plugin\monitoring\SensorPlugin
View source
class DiskUsageSensorPlugin extends SensorPluginBase {

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * {@inheritdoc}
   */
  public function __construct(SensorConfig $sensor_config, $plugin_id, $plugin_definition, FileSystemInterface $file_system, StateInterface $state_system) {
    parent::__construct($sensor_config, $plugin_id, $plugin_definition);
    $this->fileSystem = $file_system;
    $this->state = $state_system;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, SensorConfig $sensor_config, $plugin_id, $plugin_definition) {
    return new static($sensor_config, $plugin_id, $plugin_definition, $container
      ->get('file_system'), $container
      ->get('state'));
  }

  /**
   * {@inheritdoc}
   */
  public function runSensor(SensorResultInterface $sensor_result) {
    $disk_data = $this
      ->getDiskData();
    $sensor_result
      ->setValue($disk_data['used_space_percent']);
    $sensor_result
      ->addStatusMessage($this
      ->t('@used used of @total available.', [
      '@total' => $disk_data['total_space'],
      '@used' => $disk_data['used_space'],
    ]));
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['directory'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Directory'),
      '#description' => $this
        ->t('A directory of the filesystem or disk partition.'),
      '#default_value' => $this->sensorConfig
        ->getSetting('directory'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultConfiguration() {
    return [
      'caching_time' => 86400,
      'value_type' => 'number',
      'category' => 'System',
      'value_label' => '%',
      'thresholds' => [
        'type' => 'exceeds',
        'warning' => 80,
        'critical' => 95,
      ],
      'settings' => [
        'directory' => 'public://',
      ],
    ];
  }

  /**
   * Get disk info and calculate percent of used space.
   *
   * @return array
   *   Result info array with 3 items: used_space_percent, used_space,
   *   total_space. They represent used disk space in percents (float),
   *   used disk space (string) and total disk space (string). Used and total
   *   disk space are formatted in human readable size ('KB', 'MB', 'GB', 'TB',
   *   'PB', 'EB','ZB', 'YB').
   *
   * @throws \RuntimeException
   *   Thrown when the directory is not valid.
   */
  protected function getDiskData() {

    // Condition is used to simulate data for purpose of testing.
    if ($data = $this->state
      ->get('monitoring.test_disk_usage')) {
      return $data;
    }

    // Get partition info and calculate used space percent.
    $real_path = $this->fileSystem
      ->realpath($this->sensorConfig
      ->getSetting('directory'));
    if (!$real_path || !is_dir($real_path) || !($total_space = disk_total_space($real_path))) {
      throw new \RuntimeException($this
        ->t('Invalid directory.'));
    }
    else {
      $free_space = disk_free_space($real_path);
      return [
        'used_space_percent' => number_format((1 - $free_space / $total_space) * 100, 2),
        'used_space' => format_size($total_space - $free_space),
        'total_space' => format_size($total_space),
      ];
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DiskUsageSensorPlugin::$fileSystem protected property The file system service.
DiskUsageSensorPlugin::$state protected property The state service.
DiskUsageSensorPlugin::buildConfigurationForm public function Form constructor. Overrides SensorPluginBase::buildConfigurationForm
DiskUsageSensorPlugin::create public static function Creates an instance of the sensor with config. Overrides SensorPluginBase::create
DiskUsageSensorPlugin::getDefaultConfiguration public function Default configuration for a sensor. Overrides SensorPluginBase::getDefaultConfiguration
DiskUsageSensorPlugin::getDiskData protected function Get disk info and calculate percent of used space.
DiskUsageSensorPlugin::runSensor public function Runs the sensor, updating $sensor_result. Overrides SensorPluginInterface::runSensor
DiskUsageSensorPlugin::__construct public function Instantiates a sensor object. Overrides SensorPluginBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
SensorPluginBase::$configurableValueType protected property Allows plugins to control if the value type can be configured. 6
SensorPluginBase::$pluginDefinition protected property The plugin implementation definition.
SensorPluginBase::$pluginId protected property The plugin_id.
SensorPluginBase::$sensorConfig protected property Current sensor config object.
SensorPluginBase::$services protected property
SensorPluginBase::addService public function Service setter. Overrides SensorPluginInterface::addService
SensorPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides SensorPluginInterface::calculateDependencies 4
SensorPluginBase::getConfigurableValueType public function Configurable value type. Overrides SensorPluginInterface::getConfigurableValueType
SensorPluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
SensorPluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
SensorPluginBase::getSensorId public function Gets sensor name (not the label). Overrides SensorPluginInterface::getSensorId
SensorPluginBase::getService public function @todo: Replace with injection Overrides SensorPluginInterface::getService
SensorPluginBase::isEnabled public function Determines if sensor is enabled. Overrides SensorPluginInterface::isEnabled
SensorPluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 3
SensorPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.