You are here

class SystemMemorySensorPlugin in Monitoring 8

Monitors system memory.

Plugin annotation


@SensorPlugin(
  id = "monitoring_system_memory",
  label = @Translation("System memory"),
  description = @Translation("Monitors system memory."),
  addable = TRUE
)

Hierarchy

Expanded class hierarchy of SystemMemorySensorPlugin

File

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

Namespace

Drupal\monitoring\Plugin\monitoring\SensorPlugin
View source
class SystemMemorySensorPlugin extends SensorPluginBase implements ExtendedInfoSensorPluginInterface {

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

  /**
   * {@inheritdoc}
   */
  public function __construct(SensorConfig $sensor_config, $plugin_id, $plugin_definition, StateInterface $state_system) {
    parent::__construct($sensor_config, $plugin_id, $plugin_definition);
    $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('state'));
  }

  /**
   * {@inheritdoc}
   */
  public function runSensor(SensorResultInterface $sensor_result) {
    $data = $this
      ->readMemInfo();
    $data = explode("\n", $data);
    $meminfo = [];
    foreach ($data as $line) {
      list($key, $val) = array_pad(explode(':', $line, 2), 2, NULL);
      $meminfo[$key] = explode(' ', trim($val))[0];
    }

    // Evaluates the free memory in percentage.
    if (isset($meminfo['MemAvailable']) && isset($meminfo['MemTotal'])) {
      $memory = NULL;
      if ($this->sensorConfig
        ->getSetting('memory') == 'free') {
        $memory = $meminfo['MemAvailable'];
      }
      else {
        $memory = $meminfo['MemTotal'] - $meminfo['MemAvailable'];
      }
      if ($this->sensorConfig
        ->getSetting('value') == 'percentage') {
        $memory = $memory / $meminfo['MemTotal'] * 100;
      }
      else {

        // Converts memory value from KB to MB.
        $memory /= 1000;
      }
      $sensor_result
        ->setValue((int) $memory);
    }
    else {
      $sensor_result
        ->setStatus(SensorResultInterface::STATUS_CRITICAL);
      $sensor_result
        ->setMessage('This sensor is not supported by your system. It is based on memory information from /proc/meminfo, only provided by UNIX-like systems.');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultConfiguration() {
    $default_config = [
      'settings' => [
        'memory' => 'free',
        'value' => 'percentage',
      ],
    ];
    return $default_config;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $memory_track = [
      'free' => $this
        ->t('Free memory'),
      'used' => $this
        ->t('Used memory'),
    ];
    $memory_value = [
      'percentage' => $this
        ->t('Percentage'),
      'megabytes' => $this
        ->t('MB'),
    ];
    $form['memory'] = [
      '#title' => $this
        ->t('Track'),
      '#type' => 'radios',
      '#options' => $memory_track,
      '#required' => TRUE,
      '#default_value' => $this->sensorConfig
        ->getSetting('memory'),
    ];
    $form['value'] = [
      '#title' => $this
        ->t('Report as'),
      '#type' => 'radios',
      '#options' => $memory_value,
      '#required' => TRUE,
      '#default_value' => $this->sensorConfig
        ->getSetting('value'),
    ];
    return $form;
  }

  /**
   * Reads the memory info file.
   *
   * @return string $data
   *   The content of /proc/meminfo.
   */
  protected function readMemInfo() {

    // Checks if any test data is available. The state is solely used to
    // simulate data for tests.
    if ($this->state
      ->get('monitoring.test_meminfo') !== NULL) {
      return $this->state
        ->get('monitoring.test_meminfo');
    }
    else {
      return file_get_contents("/proc/meminfo");
    }
  }

  /**
   * {@inheritdoc}
   */
  public function resultVerbose(SensorResultInterface $result) {
    $data = $this
      ->readMemInfo();
    $data = explode("\n", $data);
    $rows = [];
    foreach ($data as $line) {
      list($key, $val) = array_pad(explode(':', $line, 2), 2, NULL);
      if (trim($key)) {
        $rows[] = [
          'type' => $key,
          'memory' => trim($val),
        ];
      }
    }
    $output = NULL;
    if (count($rows) > 0) {
      $header = [
        'type' => $this
          ->t('Type'),
        'memory' => $this
          ->t('Memory'),
      ];
      $output['memory_info'] = [
        '#type' => 'verbose_table_result',
        '#title' => $this
          ->t('Memory information'),
        '#header' => $header,
        '#rows' => $rows,
      ];
    }
    return $output;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
SystemMemorySensorPlugin::$state protected property The state service.
SystemMemorySensorPlugin::buildConfigurationForm public function Form constructor. Overrides SensorPluginBase::buildConfigurationForm
SystemMemorySensorPlugin::create public static function Creates an instance of the sensor with config. Overrides SensorPluginBase::create
SystemMemorySensorPlugin::getDefaultConfiguration public function Default configuration for a sensor. Overrides SensorPluginBase::getDefaultConfiguration
SystemMemorySensorPlugin::readMemInfo protected function Reads the memory info file.
SystemMemorySensorPlugin::resultVerbose public function Provide additional info about sensor call. Overrides ExtendedInfoSensorPluginInterface::resultVerbose
SystemMemorySensorPlugin::runSensor public function Runs the sensor, updating $sensor_result. Overrides SensorPluginInterface::runSensor
SystemMemorySensorPlugin::__construct public function Instantiates a sensor object. Overrides SensorPluginBase::__construct