You are here

class SensorManager in Monitoring 8

Same name and namespace in other branches
  1. 7 lib/Drupal/monitoring/Sensor/SensorManager.php \Drupal\monitoring\Sensor\SensorManager

Manages sensor definitions and settings.

Provides list of enabled sensors. Sensors can be listed by category.

Maintains a (non persistent) info cache. Enables and disables sensors.

Hierarchy

Expanded class hierarchy of SensorManager

8 files declare their use of SensorManager
ForceRunController.php in src/Controller/ForceRunController.php
MonitoringCommands.php in src/Commands/MonitoringCommands.php
MonitoringSensorConfigResource.php in src/Plugin/rest/resource/MonitoringSensorConfigResource.php
Definition of Drupal\monitoring\Plugin\rest\resource\MonitoringSensorResource.
MonitoringSensorResultResource.php in src/Plugin/rest/resource/MonitoringSensorResultResource.php
Definition of Drupal\monitoring\Plugin\rest\resource\MonitoringSensorInfoResource.
RequirementsIgnore.php in src/Controller/RequirementsIgnore.php
Contains \Drupal\monitoring\Controller\RequirementsIgnore.

... See full list

1 string reference to 'SensorManager'
monitoring.services.yml in ./monitoring.services.yml
monitoring.services.yml
1 service uses SensorManager
monitoring.sensor_manager in ./monitoring.services.yml
Drupal\monitoring\Sensor\SensorManager

File

src/Sensor/SensorManager.php, line 30
Contains \Drupal\monitoring\Sensor\SensorManager.

Namespace

Drupal\monitoring\Sensor
View source
class SensorManager extends DefaultPluginManager {
  use StringTranslationTrait;

  /**
   * List of sensor definitions.
   *
   * @var \Drupal\monitoring\Entity\SensorConfig[]
   */
  protected $sensor_config;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a sensor manager.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke the alter hook with.
   */
  function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config, EntityTypeManagerInterface $entity_type_manager, MessengerInterface $messenger) {
    parent::__construct('Plugin/monitoring/SensorPlugin', $namespaces, $module_handler, '\\Drupal\\monitoring\\SensorPlugin\\SensorPluginInterface', 'Drupal\\monitoring\\Annotation\\SensorPlugin');
    $this
      ->alterInfo('monitoring_sensor_plugins');
    $this
      ->setCacheBackend($cache_backend, 'monitoring_sensor_plugins');
    $this->config = $config;
    $this->entityTypeManager = $entity_type_manager;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public function createInstance($plugin_id, array $configuration = array()) {

    // Configuration contains SensorConfig object. Extracting
    // it to use for sensor object creation.
    $sensor_config = $configuration['sensor_config'];
    $definition = $this
      ->getDefinition($plugin_id);

    // SensorPlugin class from the sensor definition.

    /** @var \Drupal\monitoring\SensorPlugin\SensorPluginInterface $class */
    $class = $definition['class'];

    // Creating instance of the sensor. Refer SensorPlugin.php for arguments.
    return $class::create(\Drupal::getContainer(), $sensor_config, $plugin_id, $definition);
  }

  /**
   * Returns monitoring sensor config.
   *
   * @return \Drupal\monitoring\Entity\SensorConfig[]
   *   List of SensorConfig instances.
   */
  public function getAllSensorConfig() {
    $sensors = SensorConfig::loadMultiple();

    // Sort the sensors by category and label.
    uasort($sensors, "\\Drupal\\monitoring\\Entity\\SensorConfig::sort");
    return $sensors;
  }

  /**
   * Returns monitoring sensor config for enabled sensors.
   *
   * @return \Drupal\monitoring\Entity\SensorConfig[]
   *   List of SensorConfig instances.
   */
  public function getEnabledSensorConfig() {
    $enabled_sensors = array();
    foreach ($this
      ->getAllSensorConfig() as $sensor_config) {
      if ($sensor_config
        ->isEnabled()) {
        $enabled_sensors[$sensor_config
          ->id()] = $sensor_config;
      }
    }
    return $enabled_sensors;
  }

  /**
   * Returns monitoring sensor config for a given sensor.
   *
   * Directly use SensorConfig::load($name) if sensor existence assured.
   *
   * @param string $sensor_name
   *   Sensor id.
   *
   * @return \Drupal\monitoring\Entity\SensorConfig
   *   A single SensorConfig instance.
   *
   * @throws \Drupal\monitoring\Sensor\NonExistingSensorException
   *   Thrown if the requested sensor does not exist.
   */
  public function getSensorConfigByName($sensor_name) {
    $sensor_config = SensorConfig::load($sensor_name);
    if ($sensor_config == NULL) {
      throw new NonExistingSensorException(new FormattableMarkup('Sensor @sensor_name does not exist', array(
        '@sensor_name' => $sensor_name,
      )));
    }
    return $sensor_config;
  }

  /**
   * Gets sensor config grouped by categories.
   *
   * @todo: The enabled flag is strange, FALSE should return all?
   *
   * @param bool $enabled
   *   Sensor isEnabled flag.
   *
   * @return \Drupal\monitoring\Entity\SensorConfig[][]
   *   Sensor config.
   */
  public function getSensorConfigByCategories($enabled = TRUE) {
    $config_by_categories = array();
    foreach ($this
      ->getAllSensorConfig() as $sensor_name => $sensor_config) {
      if ($sensor_config
        ->isEnabled() != $enabled) {
        continue;
      }
      $config_by_categories[$sensor_config
        ->getCategory()][$sensor_name] = $sensor_config;
    }
    return $config_by_categories;
  }

  /**
   * Reset the static cache.
   */
  public function resetCache() {
    $this->sensor_config = array();
  }

  /**
   * Enable a sensor.
   *
   * Checks if the sensor is enabled and enables it if not.
   *
   * @param string $sensor_name
   *   Sensor name to be enabled.
   *
   * @throws \Drupal\monitoring\Sensor\NonExistingSensorException
   *   Thrown if the requested sensor does not exist.
   */
  public function enableSensor($sensor_name) {
    $sensor_config = $this
      ->getSensorConfigByName($sensor_name);
    if (!$sensor_config
      ->isEnabled()) {
      $sensor_config->status = TRUE;
      $sensor_config
        ->save();
      $available_sensors = \Drupal::state()
        ->get('monitoring.available_sensors', array());
      if (!isset($available_sensors[$sensor_name])) {

        // Use the watchdog message as the disappeared sensor does when new
        // sensors are detected.
        \Drupal::logger('monitoring')
          ->notice('@count new sensor/s added: @names', array(
          '@count' => 1,
          '@names' => $sensor_name,
        ));
      }
      $available_sensors[$sensor_name]['enabled'] = TRUE;
      $available_sensors[$sensor_name]['name'] = $sensor_name;
      \Drupal::state()
        ->set('monitoring.available_sensors', $available_sensors);
    }
  }

  /**
   * Disable a sensor.
   *
   * Checks if the sensor is enabled and if so it will disable it and remove
   * from the active sensor list.
   *
   * @param string $sensor_name
   *   Sensor name to be disabled.
   *
   * @throws \Drupal\monitoring\Sensor\NonExistingSensorException
   *   Thrown if the requested sensor does not exist.
   */
  public function disableSensor($sensor_name) {
    $sensor_config = $this
      ->getSensorConfigByName($sensor_name);
    if ($sensor_config
      ->isEnabled()) {
      $sensor_config->status = FALSE;
      $sensor_config
        ->save();
      $available_sensors = \Drupal::state()
        ->get('monitoring.available_sensors', array());
      $available_sensors[$sensor_name]['enabled'] = FALSE;
      $available_sensors[$sensor_name]['name'] = $sensor_name;
      \Drupal::state()
        ->set('monitoring.available_sensors', $available_sensors);
    }
  }

  /**
   * Rebuild the sensor list.
   *
   * Automatically creates sensors based on new
   */
  public function rebuildSensors() {

    // Declaring a flag for updated sensors.
    $updated_sensors = FALSE;

    // Load .install files
    include DRUPAL_ROOT . '/core/includes/install.inc';
    drupal_load_updates();
    $storage = $this->entityTypeManager
      ->getStorage('monitoring_sensor_config');
    $this->moduleHandler
      ->resetImplementations();

    // Iterate through the installed implemented modules to see if
    // there are any new requirements hook updates and initialize them.
    foreach ($this->moduleHandler
      ->getImplementations('requirements') as $module) {
      if (!$storage
        ->load('core_requirements_' . $module)) {
        if (initialize_requirements_sensors($module)) {
          $this->messenger
            ->addMessage($this
            ->t('The sensor @sensor has been added.', [
            '@sensor' => $storage
              ->load('core_requirements_' . $module)
              ->label(),
          ]));
          $updated_sensors = TRUE;
        }
      }
    }

    // Delete any updated sensors that are not implemented in the requirements
    // hook anymore.
    $sensor_ids = $storage
      ->getQuery()
      ->condition('plugin_id', 'core_requirements')
      ->execute();

    /** @var \Drupal\monitoring\SensorConfigInterface $sensor */
    foreach ($storage
      ->loadMultiple($sensor_ids) as $sensor) {
      $module = $sensor
        ->getSetting('module');
      if (!$this->moduleHandler
        ->implementsHook($module, 'requirements')) {
        $this->messenger
          ->addMessage($this
          ->t('The sensor @sensor has been removed.', [
          '@sensor' => $sensor
            ->label(),
        ]));
        $sensor
          ->delete();
        $updated_sensors = TRUE;

        // Remove the sensor from the list of available sensors.
        $available_sensors = \Drupal::state()
          ->get('monitoring.available_sensors', []);
        unset($available_sensors[$sensor
          ->id()]);
        \Drupal::state()
          ->set('monitoring.available_sensors', $available_sensors);
      }
    }

    /** @var \Drupal\Core\Config\StorageInterface[] $config_storages */
    $config_storages[] = new FileStorage($this->moduleHandler
      ->getModule('monitoring')
      ->getPath() . '/config/install');
    $config_storages[] = new FileStorage($this->moduleHandler
      ->getModule('monitoring')
      ->getPath() . '/config/optional');

    // Rebuilds all non-addable sensors.
    foreach ($this
      ->getDefinitions() as $sensor_definition) {
      if (!$sensor_definition['addable']) {
        if ($sensor_definition['id'] !== 'update_status') {
          $config_ids = [
            $sensor_definition['id'],
          ];
        }
        else {
          $config_ids = [
            'update_core',
            'update_contrib',
          ];
        }
        foreach ($config_ids as $config_id) {

          // Checks if the sensor is not created.
          if (!$storage
            ->load($config_id)) {

            // Check the two directories install and optional for sensors that need to be created.
            foreach ($config_storages as $config_storage) {
              if ($data = $config_storage
                ->read('monitoring.sensor_config.' . $config_id)) {
                $storage
                  ->create($data)
                  ->trustData()
                  ->save();
                $this->messenger
                  ->addMessage($this
                  ->t('The sensor @sensor has been created.', [
                  '@sensor' => (string) $sensor_definition['label'],
                ]));
                $updated_sensors = TRUE;
                break;
              }
            }
          }
        }
      }
    }

    // Set message to inform the user that there were no updated sensors.
    if ($updated_sensors == FALSE) {
      $this->messenger
        ->addMessage($this
        ->t('No changes were made.'));
    }
  }

  /**
   * Returns if an array is flat.
   *
   * @param array $array
   *   The array to check.
   *
   * @return bool
   *   TRUE if the array has no values that are arrays again.
   */
  protected function isFlatArray(array $array) {
    foreach ($array as $value) {
      if (is_array($value)) {
        return FALSE;
      }
    }
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultPluginManager::$additionalAnnotationNamespaces protected property Additional namespaces the annotation discovery mechanism should scan for annotation definitions.
DefaultPluginManager::$alterHook protected property Name of the alter hook if one should be invoked.
DefaultPluginManager::$cacheKey protected property The cache key.
DefaultPluginManager::$cacheTags protected property An array of cache tags to use for the cached definitions.
DefaultPluginManager::$defaults protected property A set of defaults to be referenced by $this->processDefinition() if additional processing of plugins is necessary or helpful for development purposes. 9
DefaultPluginManager::$moduleHandler protected property The module handler to invoke the alter hook. 1
DefaultPluginManager::$namespaces protected property An object that implements \Traversable which contains the root paths keyed by the corresponding namespace to look for plugin implementations.
DefaultPluginManager::$pluginDefinitionAnnotationName protected property The name of the annotation that contains the plugin definition.
DefaultPluginManager::$pluginInterface protected property The interface each plugin should implement. 1
DefaultPluginManager::$subdir protected property The subdirectory within a namespace to look for plugins, or FALSE if the plugins are in the top level of the namespace.
DefaultPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. 1
DefaultPluginManager::alterInfo protected function Sets the alter hook name.
DefaultPluginManager::clearCachedDefinitions public function Clears static and persistent plugin definition caches. Overrides CachedDiscoveryInterface::clearCachedDefinitions 5
DefaultPluginManager::extractProviderFromDefinition protected function Extracts the provider from a plugin definition.
DefaultPluginManager::findDefinitions protected function Finds plugin definitions. 7
DefaultPluginManager::fixContextAwareDefinitions private function Fix the definitions of context-aware plugins.
DefaultPluginManager::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
DefaultPluginManager::getCachedDefinitions protected function Returns the cached plugin definitions of the decorated discovery class.
DefaultPluginManager::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
DefaultPluginManager::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
DefaultPluginManager::getDefinitions public function Gets the definition of all plugins for this type. Overrides DiscoveryTrait::getDefinitions 2
DefaultPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides PluginManagerBase::getDiscovery 12
DefaultPluginManager::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
DefaultPluginManager::processDefinition public function Performs extra processing on plugin definitions. 13
DefaultPluginManager::providerExists protected function Determines if the provider of a definition exists. 3
DefaultPluginManager::setCacheBackend public function Initialize the cache backend.
DefaultPluginManager::setCachedDefinitions protected function Sets a cache of plugin definitions for the decorated discovery class.
DefaultPluginManager::useCaches public function Disable the use of caches. Overrides CachedDiscoveryInterface::useCaches 1
DiscoveryCachedTrait::$definitions protected property Cached definitions array. 1
DiscoveryCachedTrait::getDefinition public function Overrides DiscoveryTrait::getDefinition 3
DiscoveryTrait::doGetDefinition protected function Gets a specific plugin definition.
DiscoveryTrait::hasDefinition public function
PluginManagerBase::$discovery protected property The object that discovers plugins managed by this manager.
PluginManagerBase::$factory protected property The object that instantiates plugins managed by this manager.
PluginManagerBase::$mapper protected property The object that returns the preconfigured plugin instance appropriate for a particular runtime condition.
PluginManagerBase::getInstance public function Gets a preconfigured instance of a plugin. Overrides MapperInterface::getInstance 7
PluginManagerBase::handlePluginNotFound protected function Allows plugin managers to specify custom behavior if a plugin is not found. 1
SensorManager::$config protected property The config factory.
SensorManager::$entityTypeManager protected property The entity type manager.
SensorManager::$messenger protected property The messenger.
SensorManager::$sensor_config protected property List of sensor definitions.
SensorManager::createInstance public function Creates a pre-configured instance of a plugin. Overrides PluginManagerBase::createInstance
SensorManager::disableSensor public function Disable a sensor.
SensorManager::enableSensor public function Enable a sensor.
SensorManager::getAllSensorConfig public function Returns monitoring sensor config.
SensorManager::getEnabledSensorConfig public function Returns monitoring sensor config for enabled sensors.
SensorManager::getSensorConfigByCategories public function Gets sensor config grouped by categories.
SensorManager::getSensorConfigByName public function Returns monitoring sensor config for a given sensor.
SensorManager::isFlatArray protected function Returns if an array is flat.
SensorManager::rebuildSensors public function Rebuild the sensor list.
SensorManager::resetCache public function Reset the static cache.
SensorManager::__construct function Constructs a sensor manager. Overrides DefaultPluginManager::__construct
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.
UseCacheBackendTrait::$cacheBackend protected property Cache backend instance.
UseCacheBackendTrait::$useCaches protected property Flag whether caches should be used or skipped.
UseCacheBackendTrait::cacheGet protected function Fetches from the cache backend, respecting the use caches flag. 1
UseCacheBackendTrait::cacheSet protected function Stores data in the persistent cache, respecting the use caches flag.