From fde26033315d74cb1cf60ec4a0a3e6d821df5e63 Mon Sep 17 00:00:00 2001 From: Adrien Morais-Mestre <31647811+adr-mo@users.noreply.github.com> Date: Tue, 19 Jul 2022 09:32:55 +0200 Subject: [PATCH] enh(resources): remove resource status repository switch possibility (#11354) * enh(resources): remove resource status repository switch possibility * try to fix tests * Rename service for acknowledgement * Remove console statement Co-authored-by: Tom Darneix --- config/packages/Centreon.yaml | 33 +- lang/fr_FR.UTF-8/LC_MESSAGES/help.po | 5 - lang/fr_FR.UTF-8/LC_MESSAGES/messages.po | 16 - .../Interfaces/ResourceServiceInterface.php | 72 --- .../Domain/Monitoring/ResourceService.php | 28 +- .../Resource/Provider/HostProvider.php | 290 ------------ .../Resource/Provider/MetaServiceProvider.php | 296 ------------- .../Monitoring/Resource/Provider/Provider.php | 136 ------ .../Resource/Provider/ProviderInterface.php | 77 ---- .../Resource/Provider/ServiceProvider.php | 377 ---------------- .../Resource/ResourceRepositoryFactory.php | 49 --- .../Resource/ResourceRepositoryRDB.php | 412 ------------------ .../ReadResourceRepositoryInterface.php} | 10 +- .../Repository}/DbReadResourceRepository.php | 23 +- .../Repository}/DbResourceFactory.php | 3 +- tests/e2e/cypress/commons.ts | 2 +- .../resources/clapi/service1/01-add.json | 2 +- .../clapi/service1/02-set-max-check.json | 2 +- .../service1/03-disable-active-check.json | 2 +- .../service1/04-enable-passive-check.json | 2 +- .../resources/clapi/submit-results.json | 2 +- .../Resources-status/01-listing/index.ts | 2 +- .../Resources-status/02-actions/index.ts | 6 +- .../Domain/Monitoring/ResourceServiceTest.php | 4 +- .../Resource/Provider/HostProviderTest.php | 163 ------- .../Provider/MetaServiceProviderTest.php | 209 --------- .../Resource/Provider/ServiceProviderTest.php | 208 --------- .../Repository}/DbResourceFactoryTest.php | 5 +- .../Administration/parameters/DB-Func.php | 73 ---- .../parameters/engine/form.ihtml | 12 - .../Administration/parameters/engine/form.php | 30 -- .../Administration/parameters/engine/help.php | 8 - 32 files changed, 39 insertions(+), 2520 deletions(-) delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProvider.php delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProvider.php delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/Provider/Provider.php delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/Provider/ProviderInterface.php delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/Provider/ServiceProvider.php delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/ResourceRepositoryFactory.php delete mode 100644 src/Centreon/Infrastructure/Monitoring/Resource/ResourceRepositoryRDB.php rename src/{Centreon/Domain/Monitoring/Interfaces/ResourceRepositoryInterface.php => Core/Resources/Application/Repository/ReadResourceRepositoryInterface.php} (89%) rename src/{Centreon/Infrastructure/Monitoring/Resource => Core/Resources/Infrastructure/Repository}/DbReadResourceRepository.php (98%) rename src/{Centreon/Infrastructure/Monitoring/Resource => Core/Resources/Infrastructure/Repository}/DbResourceFactory.php (98%) delete mode 100644 tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProviderTest.php delete mode 100644 tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProviderTest.php delete mode 100644 tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/ServiceProviderTest.php rename tests/php/{Centreon/Infrastructure/Monitoring/Resource => Core/Resources/Infrastructure/Repository}/DbResourceFactoryTest.php (98%) diff --git a/config/packages/Centreon.yaml b/config/packages/Centreon.yaml index 4c308f62bf4..daf958f2533 100644 --- a/config/packages/Centreon.yaml +++ b/config/packages/Centreon.yaml @@ -19,9 +19,6 @@ parameters: debug_log_file: '%log_path%/centreon-web.log' env(DEBUG_LEVEL): !php/const Monolog\Logger::NOTICE curl.timeout: 60 - resource.status.repository.legacy: 'legacy' - env(APP_RESOURCE_STATUS_REPOSITORY_MODE): '%resource.status.repository.legacy%' - resource.status.repository: '%env(APP_RESOURCE_STATUS_REPOSITORY_MODE)%' debug_level: "%env(int:DEBUG_LEVEL)%" env(DEBUG_CONTACT): null @@ -225,11 +222,6 @@ services: # Monitoring resources _instanceof: - Centreon\Infrastructure\Monitoring\Resource\Provider\ProviderInterface: - tags: ['monitoring.resource.providers'] - calls: - - method: setSqlRequestTranslator - arguments: ['@sqlRequestTranslator'] Core\Infrastructure\RealTime\Hypermedia\HypermediaProviderInterface: tags: ['realtime.hypermedia'] Core\Security\Application\ProviderConfiguration\Repository\ReadProviderConfigurationsRepositoryInterface: @@ -239,14 +231,10 @@ services: Core\Security\Infrastructure\Api\FindProviderConfigurations\ProviderPresenter\ProviderPresenterInterface: tags: ['authentication.provider.presenters'] - Centreon\Domain\Monitoring\Interfaces\ResourceRepositoryInterface: - factory: ['@Centreon\Infrastructure\Monitoring\Resource\ResourceRepositoryFactory', 'createResourceRepository'] - - Centreon\Infrastructure\Monitoring\Resource\ResourceRepositoryFactory: - class: Centreon\Infrastructure\Monitoring\Resource\ResourceRepositoryFactory - arguments: ['@=parameter("resource.status.repository") === parameter("resource.status.repository.legacy") - ? service("Centreon\\Infrastructure\\Monitoring\\Resource\\ResourceRepositoryRDB") - : service("Centreon\\Infrastructure\\Monitoring\\Resource\\DbReadResourceRepository")'] + Core\Resources\Application\Repository\ReadResourceRepositoryInterface: + class: Core\Resources\Infrastructure\Repository\DbReadResourceRepository + arguments: + $sqlRequestTranslator: '@sqlRequestTranslator' Core\Security\Application\UseCase\FindProviderConfigurations\FindProviderConfigurations: arguments: @@ -256,19 +244,6 @@ services: Core\Security\Infrastructure\Api\FindProviderConfigurations\FindProviderConfigurationsPresenter: arguments: [!tagged_iterator 'authentication.provider.presenters'] - - Centreon\Infrastructure\Monitoring\Resource\ResourceRepositoryRDB: - calls: - - method: setSqlRequestTranslator - arguments: ['@sqlRequestTranslator'] - - method: setProviders - arguments: [!tagged_iterator 'monitoring.resource.providers'] - - Centreon\Infrastructure\Monitoring\Resource\DbReadResourceRepository: - calls: - - method: setSqlRequestTranslator - arguments: ['@sqlRequestTranslator'] - Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator: class: Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator calls: diff --git a/lang/fr_FR.UTF-8/LC_MESSAGES/help.po b/lang/fr_FR.UTF-8/LC_MESSAGES/help.po index 5e0a4fb2f34..19a776a428f 100644 --- a/lang/fr_FR.UTF-8/LC_MESSAGES/help.po +++ b/lang/fr_FR.UTF-8/LC_MESSAGES/help.po @@ -7215,11 +7215,6 @@ msgstr "" msgid "Expected TLS certificate common name (CN) - leave blank if unsure." msgstr "Champ common name (CN) attendu dans le certificat TLS - laisser vide en cas de doute" -msgid "Mode used to retrieve information displayed in Resource Status page." -"The optimized mode will only be available and functional when using the BBDO 3.0.0 protocol for the collect engine." -msgstr "Mode utilisé pour récupérer les données affichées dans la page Resource Status." -"Le mode optimisé pourra être utilisé et fonctionnel que si le moteur de supervision utilise le protocole BBDO 3.0.0" - msgid "Poller Configuration Actions / Poller Management" msgstr "Actions de configuration du collecteur / Gestion du collecteur" diff --git a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po index e0c8fc4daec..093d8f13cab 100644 --- a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po +++ b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po @@ -16856,22 +16856,6 @@ msgstr "Vous n'êtes pas autorisé à accéder aux groupes de contacts" msgid "Error while searching for the host template %d" msgstr "Erreur lors de la recherche du modèle d'hôte %d" -#: www/include/Administration/parameters/DB-Func.php -msgid "Could not change resource status mode." -msgstr "Le mode pour Resource Status n'a pas pu être changé" - -#: www/include/Administration/parameters/DB-Func.php -msgid "Reason: error when updating PHP environment file" -msgstr "Raison: erreur lors de la mise à jour du fichier PHP d'environnement" - -#: www/include/Administration/parameters/DB-Func.php -msgid "Reason: PHP environment file is not writable" -msgstr "Raison: le fichier PHP d'environnement n'est pas éditable" - -#: www/include/Administration/parameters/engine/form.php -msgid "Resource Status mod" -msgstr "Mode pour Resource Status" - msgid "This section allows you to give authorizations in order to link an imported user to an access group." msgstr "Cette section vous permet de donner des autorisations afin de lier un utilisateur importé à un groupe d'accès." diff --git a/src/Centreon/Domain/Monitoring/Interfaces/ResourceServiceInterface.php b/src/Centreon/Domain/Monitoring/Interfaces/ResourceServiceInterface.php index 9ce3ae61a45..0f3bd5ddbee 100644 --- a/src/Centreon/Domain/Monitoring/Interfaces/ResourceServiceInterface.php +++ b/src/Centreon/Domain/Monitoring/Interfaces/ResourceServiceInterface.php @@ -22,83 +22,11 @@ namespace Centreon\Domain\Monitoring\Interfaces; -use Centreon\Domain\Monitoring\Interfaces\ResourceRepositoryInterface; use Centreon\Domain\Monitoring\ResourceFilter; use Centreon\Domain\Monitoring\Resource as ResourceEntity; -use Centreon\Domain\Monitoring\Exception\ResourceException; interface ResourceServiceInterface { - public const TYPE_SERVICE = 'service'; - public const TYPE_HOST = 'host'; - - /** - * List of all types - */ - public const TYPES = [ - self::TYPE_HOST, - self::TYPE_SERVICE, - ]; - - /** - * Non-ok status in hard state , not acknowledged & not in downtime - */ - public const STATE_UNHANDLED_PROBLEMS = 'unhandled_problems'; - - /** - * Non-ok status in hard state - */ - public const STATE_RESOURCES_PROBLEMS = 'resources_problems'; - - /** - * Resources in downtime - */ - public const STATE_IN_DOWNTIME = 'in_downtime'; - - /** - * Acknowledged resources - */ - public const STATE_ACKNOWLEDGED = 'acknowledged'; - - /** - * All status & resources - */ - public const STATE_ALL = 'all'; - - /** - * List of all states - */ - public const STATES = [ - self::STATE_UNHANDLED_PROBLEMS, - self::STATE_RESOURCES_PROBLEMS, - self::STATE_IN_DOWNTIME, - self::STATE_ACKNOWLEDGED, - self::STATE_ALL, - ]; - - public const STATUS_OK = 'OK'; - public const STATUS_UP = 'UP'; - public const STATUS_WARNING = 'WARNING'; - public const STATUS_DOWN = 'DOWN'; - public const STATUS_CRITICAL = 'CRITICAL'; - public const STATUS_UNREACHABLE = 'UNREACHABLE'; - public const STATUS_UNKNOWN = 'UNKNOWN'; - public const STATUS_PENDING = 'PENDING'; - - /** - * List of all types - */ - public const STATUSES = [ - self::STATUS_OK, - self::STATUS_UP, - self::STATUS_WARNING, - self::STATUS_DOWN, - self::STATUS_CRITICAL, - self::STATUS_UNREACHABLE, - self::STATUS_UNKNOWN, - self::STATUS_PENDING, - ]; - /** * Find all resources. * diff --git a/src/Centreon/Domain/Monitoring/ResourceService.php b/src/Centreon/Domain/Monitoring/ResourceService.php index b6b7dd9db95..6171f77fb1a 100644 --- a/src/Centreon/Domain/Monitoring/ResourceService.php +++ b/src/Centreon/Domain/Monitoring/ResourceService.php @@ -30,9 +30,9 @@ use Centreon\Domain\Monitoring\Exception\ResourceException; use Symfony\Component\Validator\ConstraintViolationListInterface; use Centreon\Domain\Monitoring\Interfaces\ResourceServiceInterface; -use Centreon\Domain\Monitoring\Interfaces\ResourceRepositoryInterface; use Core\Security\Application\Repository\ReadAccessGroupRepositoryInterface; use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface; +use Core\Resources\Application\Repository\ReadResourceRepositoryInterface; /** * Service manage the resources in real-time monitoring : hosts and services. @@ -41,34 +41,16 @@ */ class ResourceService extends AbstractCentreonService implements ResourceServiceInterface { - /** - * @var ResourceRepositoryInterface - */ - private $resourceRepository; - - /** - * @var MonitoringRepositoryInterface - */ - private $monitoringRepository; - - /** - * @var ReadAccessGroupRepositoryInterface - */ - private $accessGroupRepository; - /** * @param MonitoringRepositoryInterface $monitoringRepository , * @param ReadAccessGroupRepositoryInterface $accessGroupRepository - * @param ResourceRepositoryInterface $resourceRepository + * @param ReadResourceRepositoryInterface $resourceRepository */ public function __construct( - MonitoringRepositoryInterface $monitoringRepository, - ReadAccessGroupRepositoryInterface $accessGroupRepository, - ResourceRepositoryInterface $resourceRepository + private MonitoringRepositoryInterface $monitoringRepository, + private ReadAccessGroupRepositoryInterface $accessGroupRepository, + private ReadResourceRepositoryInterface $resourceRepository ) { - $this->monitoringRepository = $monitoringRepository; - $this->accessGroupRepository = $accessGroupRepository; - $this->resourceRepository = $resourceRepository; } /** diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProvider.php b/src/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProvider.php deleted file mode 100644 index be603c68f77..00000000000 --- a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProvider.php +++ /dev/null @@ -1,290 +0,0 @@ -hasOnlyServiceSearch() - || ($filter->getTypes() && !$filter->hasType(ResourceFilter::TYPE_HOST)) - || ($filter->getStatuses() && !ResourceFilter::map( - $filter->getStatuses(), - ResourceFilter::MAP_STATUS_HOST - )) - || $filter->getServicegroupNames() - ) { - return false; - } - - return true; - } - - /** - * @inheritDoc - */ - public function prepareSubQueryWithoutAcl(ResourceFilter $filter, StatementCollector $collector): string - { - return $this->prepareSubQuery($filter, $collector, null); - } - - /** - * @inheritDoc - */ - public function prepareSubQueryWithAcl( - ResourceFilter $filter, - StatementCollector $collector, - array $accessGroupIds - ): string { - $aclSubQuery = ' EXISTS (SELECT 1 FROM `:dbstg`.`centreon_acl` AS host_acl WHERE host_acl.host_id = h.host_id - AND host_acl.service_id IS NULL - AND host_acl.group_id IN (' . implode(',', $accessGroupIds) . ') LIMIT 1) '; - - return $this->prepareSubQuery($filter, $collector, $aclSubQuery); - } - - /** - * Prepare SQL query - * - * @param ResourceFilter $filter - * @param StatementCollector $collector - * @param string|null $aclSubQuery - * @return string - */ - private function prepareSubQuery( - ResourceFilter $filter, - StatementCollector $collector, - ?string $aclSubQuery - ): string { - $sql = "SELECT - h.host_id AS `id`, - 'host' AS `type`, - h.name AS `name`, - h.alias AS `alias`, - h.address AS `fqdn`, - h.host_id AS `host_id`, - NULL AS `service_id`, - h.icon_image_alt AS `icon_name`, - h.icon_image AS `icon_url`, - h.action_url AS `action_url`, - h.notes_url AS `notes_url`, - h.notes AS `notes_label`, - i.name AS `monitoring_server_name`, - i.instance_id AS `monitoring_server_id`, - h.command_line AS `command_line`, - h.timezone AS `timezone`, - NULL AS `parent_id`, - NULL AS `parent_name`, - NULL AS `parent_alias`, - NULL AS `parent_fqdn`, - NULL AS `parent_type`, - NULL AS `parent_icon_name`, - NULL AS `parent_icon_url`, - NULL AS `parent_status_code`, - NULL AS `parent_status_name`, - NULL as `parent_status_severity_code`, - h.state AS `status_code`, - CASE - WHEN h.state = 0 THEN 'UP' - WHEN h.state = 1 THEN 'DOWN' - WHEN h.state = 2 THEN 'UNREACHABLE' - WHEN h.state = 4 THEN 'PENDING' - END AS `status_name`, - CASE - WHEN h.state = 0 THEN " . ResourceStatus::SEVERITY_OK . " - WHEN h.state = 1 THEN " . ResourceStatus::SEVERITY_HIGH . " - WHEN h.state = 2 THEN " . ResourceStatus::SEVERITY_LOW . " - WHEN h.state = 4 THEN " . ResourceStatus::SEVERITY_PENDING . " - END AS `status_severity_code`, - h.flapping AS `flapping`, - h.percent_state_change AS `percent_state_change`, - h.scheduled_downtime_depth AS `in_downtime`, - h.acknowledged AS `acknowledged`, - h.active_checks AS `active_checks`, - h.passive_checks AS `passive_checks`, - host_cvl.value AS `severity_level`, - h.last_state_change AS `last_status_change`, - h.last_notification AS `last_notification`, - h.notification_number AS `notification_number`, - h.state_type AS `state_type`, - CONCAT(h.check_attempt, '/', h.max_check_attempts, ' (', CASE - WHEN h.state_type = 1 THEN 'H' - WHEN h.state_type = 0 THEN 'S' - END, ')') AS `tries`, - h.last_check AS `last_check`, - CASE - WHEN h.active_checks = 0 THEN NULL - WHEN h.active_checks = 1 THEN h.next_check - END AS `next_check`, - h.output AS `information`, - h.perfdata AS `performance_data`, - h.execution_time AS `execution_time`, - h.latency AS `latency`, - h.notify AS `notification_enabled`, - h.last_time_up AS `last_time_with_no_issue` - FROM `:dbstg`.`hosts` AS h"; - - // get monitoring server information - $sql .= " INNER JOIN `:dbstg`.`instances` AS i ON i.instance_id = h.instance_id"; - - // get Severity level, name, icon - $sql .= ' LEFT JOIN `:dbstg`.`customvariables` AS host_cvl ON host_cvl.host_id = h.host_id - AND host_cvl.service_id = 0 - AND host_cvl.name = "CRITICALITY_LEVEL"'; - - $hasWhereCondition = false; - - $this->sqlRequestTranslator->setConcordanceArray($this->hostConcordances); - try { - $searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql(); - } catch (RequestParametersTranslatorException $ex) { - throw new RepositoryException($ex->getMessage(), 0, $ex); - } - - if ($searchRequest !== null) { - $hasWhereCondition = true; - $sql .= $searchRequest; - } - - // set ACL limitations - if ($aclSubQuery !== null) { - $sql .= ($hasWhereCondition ? ' AND ' : ' WHERE ') . $aclSubQuery; - $hasWhereCondition = true; - } - - // show active hosts and aren't related to some module - $sql .= ($hasWhereCondition ? ' AND ' : ' WHERE ') - . 'h.enabled = 1 AND h.name NOT LIKE "\_Module\_%"'; - - // apply the state filter to SQL query - if ($filter->getStates() && !$filter->hasState(ResourceServiceInterface::STATE_ALL)) { - $sqlState = []; - $sqlStateCatalog = [ - ResourceServiceInterface::STATE_UNHANDLED_PROBLEMS => "(h.state_type = '1'" - . " AND h.acknowledged = 0" - . " AND h.scheduled_downtime_depth = 0" - . " AND h.state != 0" - . " AND h.state != 4)", - ResourceServiceInterface::STATE_RESOURCES_PROBLEMS => '(h.state != 0 AND h.state != 4)', - ResourceServiceInterface::STATE_IN_DOWNTIME => 'h.scheduled_downtime_depth = 1', - ResourceServiceInterface::STATE_ACKNOWLEDGED => 'h.acknowledged = 1', - ]; - - foreach ($filter->getStates() as $state) { - $sqlState[] = $sqlStateCatalog[$state]; - } - - if ($sqlState) { - $sql .= ' AND (' . implode(' OR ', $sqlState) . ')'; - } - } - - // apply the status filter to SQL query - $statuses = ResourceFilter::map($filter->getStatuses(), ResourceFilter::MAP_STATUS_HOST); - if ($statuses) { - $statusList = []; - - foreach ($statuses as $index => $status) { - $key = ":hostStatuses_{$index}"; - - $statusList[] = $key; - $collector->addValue($key, $status, \PDO::PARAM_INT); - } - - $sql .= ' AND h.state IN (' . implode(', ', $statusList) . ')'; - } - - // apply the state types filter to SQL query - $statusTypes = ResourceFilter::map($filter->getStatusTypes(), ResourceFilter::MAP_STATUS_TYPES); - if ($statusTypes) { - $statusTypesList = []; - - foreach ($statusTypes as $index => $statusType) { - $key = ":hostStateTypes_{$index}"; - - $statusTypesList[] = $key; - $collector->addValue($key, $statusType, \PDO::PARAM_INT); - } - - $sql .= ' AND h.state_type IN (' . implode(', ', $statusTypesList) . ')'; - } - - if (!empty($filter->getHostIds())) { - $hostIds = []; - - foreach ($filter->getHostIds() as $index => $hostId) { - $key = ":hostId_{$index}"; - - $hostIds[] = $key; - $collector->addValue($key, $hostId, \PDO::PARAM_INT); - } - - $sql .= ' AND h.host_id IN (' . implode(', ', $hostIds) . ')'; - } - - // apply the monitoring server filter to SQL query - if (!empty($filter->getMonitoringServerNames())) { - $monitoringServerNames = []; - - foreach ($filter->getMonitoringServerNames() as $index => $monitoringServerName) { - $key = ":monitoringServerName_{$index}"; - - $monitoringServerNames[] = $key; - $collector->addValue($key, $monitoringServerName, \PDO::PARAM_STR); - } - - $sql .= ' AND i.name IN (' . implode(', ', $monitoringServerNames) . ')'; - } - - return $sql; - } - - /** - * @inheritDoc - */ - public function excludeResourcesWithoutMetrics(array $resources): array - { - $filteredResources = []; - - foreach ($resources as $resource) { - if ($resource->getType() !== Resource::TYPE_HOST) { - $filteredResources[] = $resource; - } - } - - return $filteredResources; - } -} diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProvider.php b/src/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProvider.php deleted file mode 100644 index 243139dbb43..00000000000 --- a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProvider.php +++ /dev/null @@ -1,296 +0,0 @@ -hasOnlyHostSearch() - || $this->hasOnlyServiceSearch() - || ($filter->getTypes() && !$filter->hasType(ResourceFilter::TYPE_META)) - || ($filter->getStatuses() && !ResourceFilter::map( - $filter->getStatuses(), - ResourceFilter::MAP_STATUS_SERVICE - )) - || $filter->getHostgroupNames() - || $filter->getServicegroupNames() - ) { - return false; - } - - return true; - } - - /** - * @inheritDoc - */ - public function prepareSubQueryWithoutAcl(ResourceFilter $filter, StatementCollector $collector): string - { - return $this->prepareSubQuery($filter, $collector, null); - } - - /** - * @inheritDoc - */ - public function prepareSubQueryWithAcl( - ResourceFilter $filter, - StatementCollector $collector, - array $accessGroupIds - ): string { - $aclSubQuery = ' EXISTS ( - SELECT 1 FROM `:dbstg`.`centreon_acl` AS service_acl - WHERE service_acl.host_id = s.host_id - AND service_acl.service_id = s.service_id - AND service_acl.group_id IN (' . implode(',', $accessGroupIds) . ') - LIMIT 1) '; - - return $this->prepareSubQuery($filter, $collector, $aclSubQuery); - } - - /** - * Prepare SQL query - * - * @param ResourceFilter $filter - * @param StatementCollector $collector - * @param string|null $aclSubQuery - * @return string - */ - private function prepareSubQuery( - ResourceFilter $filter, - StatementCollector $collector, - ?string $aclSubQuery - ): string { - $sql = "SELECT - SUBSTRING(s.description, 6) AS `id`, - 'metaservice' AS `type`, - s.display_name AS `name`, - NULL AS `alias`, - NULL AS `fqdn`, - sh.host_id AS `host_id`, - s.service_id AS `service_id`, - NULL AS `icon_name`, - NULL AS `icon_url`, - NULL AS `action_url`, - NULL AS `notes_url`, - NULL AS `notes_label`, - i.name AS `monitoring_server_name`, - i.instance_id AS `monitoring_server_id`, - s.command_line AS `command_line`, - NULL AS `timezone`, - NULL AS `parent_id`, - NULL AS `parent_name`, - NULL AS `parent_alias`, - NULL AS `parent_fqdn`, - NULL AS `parent_type`, - NULL AS `parent_icon_name`, - NULL AS `parent_icon_url`, - NULL AS `parent_status_code`, - NULL AS `parent_status_name`, - NULL AS `parent_status_severity_code`, - s.state AS `status_code`, - CASE - WHEN s.state = 0 THEN 'OK' - WHEN s.state = 1 THEN 'WARNING' - WHEN s.state = 2 THEN 'CRITICAL' - WHEN s.state = 3 THEN 'UNKNOWN' - WHEN s.state = 4 THEN 'PENDING' - END AS `status_name`, - CASE - WHEN s.state = 0 THEN " . ResourceStatus::SEVERITY_OK . " - WHEN s.state = 1 THEN " . ResourceStatus::SEVERITY_MEDIUM . " - WHEN s.state = 2 THEN " . ResourceStatus::SEVERITY_HIGH . " - WHEN s.state = 3 THEN " . ResourceStatus::SEVERITY_LOW . " - WHEN s.state = 4 THEN " . ResourceStatus::SEVERITY_PENDING . " - END AS `status_severity_code`, - s.flapping AS `flapping`, - s.percent_state_change AS `percent_state_change`, - s.scheduled_downtime_depth AS `in_downtime`, - s.acknowledged AS `acknowledged`, - 1 AS `active_checks`, - 1 AS `passive_checks`, - NULL AS `severity_level`, - s.last_state_change AS `last_status_change`, - s.last_notification AS `last_notification`, - s.notification_number AS `notification_number`, - s.state_type AS `state_type`, - CONCAT(s.check_attempt, '/', s.max_check_attempts, ' (', CASE - WHEN s.state_type = 1 THEN 'H' - WHEN s.state_type = 0 THEN 'S' - END, ')') AS `tries`, - s.last_check AS `last_check`, - s.next_check AS `next_check`, - s.output AS `information`, - s.perfdata AS `performance_data`, - s.execution_time AS `execution_time`, - s.latency AS `latency`, - s.notify AS `notification_enabled`, - s.last_time_ok AS `last_time_with_no_issue` - FROM `:dbstg`.`services` AS s - INNER JOIN `:dbstg`.`hosts` sh - ON sh.host_id = s.host_id - AND sh.name LIKE '\_Module\_Meta%' - AND sh.enabled = 1"; - - // get monitoring server information - $sql .= " INNER JOIN `:dbstg`.`instances` AS i ON i.instance_id = sh.instance_id"; - - // show active services only - $sql .= ' WHERE s.enabled = 1 '; - - - // set ACL limitations - if ($aclSubQuery !== null) { - $sql .= ' AND ' . $aclSubQuery; - } - - // apply the state filter to SQL query - if ($filter->getStates() && !$filter->hasState(ResourceServiceInterface::STATE_ALL)) { - $sqlState = []; - $sqlStateCatalog = [ - ResourceServiceInterface::STATE_UNHANDLED_PROBLEMS => "(s.state_type = '1'" - . " AND s.acknowledged = 0" - . " AND s.scheduled_downtime_depth = 0" - . " AND sh.acknowledged = 0" - . " AND sh.scheduled_downtime_depth = 0" - . " AND s.state != 0" - . " AND s.state != 4)", - ResourceServiceInterface::STATE_RESOURCES_PROBLEMS => '(s.state != 0 AND s.state != 4)', - ResourceServiceInterface::STATE_IN_DOWNTIME => '(s.scheduled_downtime_depth = 1' - . ' OR sh.scheduled_downtime_depth = 1)', - ResourceServiceInterface::STATE_ACKNOWLEDGED => '(s.acknowledged = 1 OR sh.acknowledged = 1)', - ]; - - foreach ($filter->getStates() as $state) { - $sqlState[] = $sqlStateCatalog[$state]; - } - - $sql .= ' AND (' . implode(' OR ', $sqlState) . ')'; - } - - // apply the status filter to SQL query - $statuses = ResourceFilter::map($filter->getStatuses(), ResourceFilter::MAP_STATUS_SERVICE); - if ($statuses) { - $statusList = []; - - foreach ($statuses as $index => $status) { - $key = ":serviceStatuses_{$index}"; - - $statusList[] = $key; - $collector->addValue($key, $status, \PDO::PARAM_INT); - } - - $sql .= ' AND s.state IN (' . implode(', ', $statusList) . ')'; - } - - if (!empty($filter->getMetaServiceIds())) { - $metaServiceIds = []; - - foreach ($filter->getMetaServiceIds() as $index => $metaServiceId) { - $key = ":metaServiceId_{$index}"; - - $metaServiceIds[] = $key; - $collector->addValue($key, 'meta_' . $metaServiceId, \PDO::PARAM_STR); - } - - $sql .= ' AND s.description IN (' . implode(', ', $metaServiceIds) . ')'; - } - - // apply the state types filter to SQL query - $stateTypes = ResourceFilter::map($filter->getStatusTypes(), ResourceFilter::MAP_STATUS_TYPES); - if ($stateTypes) { - $stateTypesList = []; - - foreach ($stateTypes as $index => $stateType) { - $key = ":serviceStateType_{$index}"; - - $stateTypesList[] = $key; - $collector->addValue($key, $stateType, \PDO::PARAM_INT); - } - - $sql .= ' AND s.state_type IN (' . implode(', ', $stateTypesList) . ')'; - } - - return $sql; - } - - /** - * @inheritDoc - */ - public function excludeResourcesWithoutMetrics(array $resources): array - { - $filteredResources = []; - $collector = new StatementCollector(); - $where = []; - $metaServiceResources = []; - - foreach ($resources as $key => $resource) { - if ($resource->getType() === Resource::TYPE_META) { - $where[] = "(s.description = :service_description_{$key})"; - $collector->addValue(":service_description_{$key}", 'meta_' . $resource->getId(), \PDO::PARAM_STR); - $metaServiceResources[] = $resource; - } else { - $filteredResources[] = $resource; - } - } - - if (empty($metaServiceResources)) { - return $filteredResources; - } - - $statement = $this->db->prepare( - $this->translateDbName( - 'SELECT i.host_id, i.service_id, s.description - FROM `:dbstg`.metrics AS m, `:dbstg`.index_data AS i, `:dbstg`.services AS s - WHERE (' . implode(' OR ', $where) . ') - AND i.id = m.index_id - AND i.service_id = s.service_id - AND m.hidden = "0" - GROUP BY host_id, service_id' - ) - ); - $collector->bind($statement); - $statement->execute(); - - while ($row = $statement->fetch()) { - foreach ($metaServiceResources as $metaServiceResource) { - if ($metaServiceResource->getId() === (int)substr($row['description'], 5)) { - $filteredResources[] = $metaServiceResource; - } - } - } - - return $filteredResources; - } -} diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/Provider.php b/src/Centreon/Infrastructure/Monitoring/Resource/Provider/Provider.php deleted file mode 100644 index ca3441bcc6f..00000000000 --- a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/Provider.php +++ /dev/null @@ -1,136 +0,0 @@ - 'h.name', - 'h.alias' => 'h.alias', - 'h.address' => 'h.address', - 'h.fqdn' => 'h.address', - ]; - - /** - * @var array Association of service search parameters - */ - protected $serviceConcordances = [ - 'h.name' => 'sh.name', - 'h.alias' => 'sh.alias', - 'h.address' => 'sh.address', - 'h.fqdn' => 'sh.address', - 's.description' => 's.description', - ]; - - /** - * @param DatabaseConnection $databaseConnection - */ - public function __construct(DatabaseConnection $databaseConnection) - { - $this->db = $databaseConnection; - } - - /** - * @inheritDoc - */ - public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void - { - $this->sqlRequestTranslator = $sqlRequestTranslator; - $this->sqlRequestTranslator - ->getRequestParameters() - ->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT) - ->setConcordanceErrorMode(RequestParameters::CONCORDANCE_ERRMODE_SILENT); - } - - /** - * Check if a service filter is given in request parameters - * - * @return bool - */ - protected function hasOnlyHostSearch(): bool - { - return $this->hasOnlyConcordanceSearch($this->hostConcordances); - } - - /** - * Check if a service filter is given in request parameters - * - * @return bool - */ - protected function hasOnlyServiceSearch(): bool - { - $serviceOnlyConcordances = []; - foreach (array_keys($this->serviceConcordances) as $serviceOnlyConcordanceKey) { - if (!in_array($serviceOnlyConcordanceKey, array_keys($this->hostConcordances))) { - $serviceOnlyConcordances[$serviceOnlyConcordanceKey] = - $this->serviceConcordances[$serviceOnlyConcordanceKey]; - } - } - - return $this->hasOnlyConcordanceSearch($serviceOnlyConcordances); - } - - /** - * Check if search contains keys from only given concordances - * - * @param array $concordances - * @return boolean - */ - private function hasOnlyConcordanceSearch(array $concordances): bool - { - $search = $this->sqlRequestTranslator->getRequestParameters()->getSearch(); - $searchNames = $this->sqlRequestTranslator->getRequestParameters()->extractSearchNames(); - - if (empty($searchNames)) { - return false; - } - - $concordanceMatches = []; - foreach ($searchNames as $searchName) { - if (in_array($searchName, array_keys($concordances))) { - $concordanceMatches[] = $searchName; - } - } - - $operator = array_keys($search)[0]; - if ($operator === RequestParameters::AGGREGATE_OPERATOR_OR) { - return count($searchNames) === count($concordanceMatches); - } - - return !empty($concordanceMatches); - } -} diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/ProviderInterface.php b/src/Centreon/Infrastructure/Monitoring/Resource/Provider/ProviderInterface.php deleted file mode 100644 index 29276f7fa1d..00000000000 --- a/src/Centreon/Infrastructure/Monitoring/Resource/Provider/ProviderInterface.php +++ /dev/null @@ -1,77 +0,0 @@ -getTypes() && !$filter->hasType(ResourceFilter::TYPE_SERVICE)) { - return false; - } - - if ( - $filter->getStatuses() && - !ResourceFilter::map( - $filter->getStatuses(), - ResourceFilter::MAP_STATUS_SERVICE - ) - ) { - return false; - } - - return true; - } - - /** - * @inheritDoc - */ - public function prepareSubQueryWithoutAcl(ResourceFilter $filter, StatementCollector $collector): string - { - return $this->prepareSubQuery($filter, $collector, null); - } - - /** - * @inheritDoc - */ - public function prepareSubQueryWithAcl( - ResourceFilter $filter, - StatementCollector $collector, - array $accessGroupIds - ): string { - $aclSubQuery = ' EXISTS ( - SELECT 1 FROM `:dbstg`.`centreon_acl` AS service_acl - WHERE service_acl.host_id = s.host_id - AND service_acl.service_id = s.service_id - AND service_acl.group_id IN (' . implode(',', $accessGroupIds) . ') - LIMIT 1) '; - - return $this->prepareSubQuery($filter, $collector, $aclSubQuery); - } - - /** - * Prepare SQL query - * - * @param ResourceFilter $filter - * @param StatementCollector $collector - * @param string|null $aclSubQuery - * @return string - */ - private function prepareSubQuery( - ResourceFilter $filter, - StatementCollector $collector, - ?string $aclSubQuery - ): string { - $sql = "SELECT DISTINCT - s.service_id AS `id`, - 'service' AS `type`, - s.description AS `name`, - NULL AS `alias`, - NULL AS `fqdn`, - sh.host_id AS `host_id`, - s.service_id AS `service_id`, - s.icon_image_alt AS `icon_name`, - s.icon_image AS `icon_url`, - s.action_url AS `action_url`, - s.notes_url AS `notes_url`, - s.notes AS `notes_label`, - i.name AS `monitoring_server_name`, - i.instance_id AS `monitoring_server_id`, - s.command_line AS `command_line`, - NULL AS `timezone`, - sh.host_id AS `parent_id`, - sh.name AS `parent_name`, - sh.alias AS `parent_alias`, - sh.address AS `parent_fqdn`, - 'host' AS `parent_type`, - sh.icon_image_alt AS `parent_icon_name`, - sh.icon_image AS `parent_icon_url`, - sh.state AS `parent_status_code`, - CASE - WHEN sh.state = 0 THEN 'UP' - WHEN sh.state = 1 THEN 'DOWN' - WHEN sh.state = 2 THEN 'UNREACHABLE' - WHEN sh.state = 4 THEN 'PENDING' - END AS `parent_status_name`, - CASE - WHEN sh.state = 0 THEN " . ResourceStatus::SEVERITY_OK . " - WHEN sh.state = 1 THEN " . ResourceStatus::SEVERITY_HIGH . " - WHEN sh.state = 2 THEN " . ResourceStatus::SEVERITY_LOW . " - WHEN sh.state = 4 THEN " . ResourceStatus::SEVERITY_PENDING . " - END AS `parent_status_severity_code`, - s.state AS `status_code`, - CASE - WHEN s.state = 0 THEN 'OK' - WHEN s.state = 1 THEN 'WARNING' - WHEN s.state = 2 THEN 'CRITICAL' - WHEN s.state = 3 THEN 'UNKNOWN' - WHEN s.state = 4 THEN 'PENDING' - END AS `status_name`, - CASE - WHEN s.state = 0 THEN " . ResourceStatus::SEVERITY_OK . " - WHEN s.state = 1 THEN " . ResourceStatus::SEVERITY_MEDIUM . " - WHEN s.state = 2 THEN " . ResourceStatus::SEVERITY_HIGH . " - WHEN s.state = 3 THEN " . ResourceStatus::SEVERITY_LOW . " - WHEN s.state = 4 THEN " . ResourceStatus::SEVERITY_PENDING . " - END AS `status_severity_code`, - s.flapping AS `flapping`, - s.percent_state_change AS `percent_state_change`, - s.scheduled_downtime_depth AS `in_downtime`, - s.acknowledged AS `acknowledged`, - s.active_checks AS `active_checks`, - s.passive_checks AS `passive_checks`, - service_cvl.value AS `severity_level`, - s.last_state_change AS `last_status_change`, - s.last_notification AS `last_notification`, - s.notification_number AS `notification_number`, - s.state_type AS `state_type`, - CONCAT(s.check_attempt, '/', s.max_check_attempts, ' (', CASE - WHEN s.state_type = 1 THEN 'H' - WHEN s.state_type = 0 THEN 'S' - END, ')') AS `tries`, - s.last_check AS `last_check`, - CASE - WHEN s.active_checks = 0 THEN NULL - WHEN s.active_checks = 1 THEN s.next_check - END AS `next_check`, - s.output AS `information`, - s.perfdata AS `performance_data`, - s.execution_time AS `execution_time`, - s.latency AS `latency`, - s.notify AS `notification_enabled`, - s.last_time_ok AS `last_time_with_no_issue` - FROM `:dbstg`.`services` AS s - INNER JOIN `:dbstg`.`hosts` sh - ON sh.host_id = s.host_id - AND sh.name NOT LIKE '\_Module\_%' - AND sh.enabled = 1"; - - // get monitoring server information - $sql .= " INNER JOIN `:dbstg`.`instances` AS i ON i.instance_id = sh.instance_id"; - - // get Severity level, name, icon - $sql .= ' LEFT JOIN `:dbstg`.`customvariables` AS service_cvl ON service_cvl.host_id = s.host_id - AND service_cvl.service_id = s.service_id - AND service_cvl.name = "CRITICALITY_LEVEL"'; - - $hasWhereCondition = false; - - $this->sqlRequestTranslator->setConcordanceArray($this->serviceConcordances); - try { - $searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql(); - } catch (RequestParametersTranslatorException $ex) { - throw new RepositoryException($ex->getMessage(), 0, $ex); - } - - if ($searchRequest !== null) { - $hasWhereCondition = true; - $sql .= $searchRequest; - } - - // show active services only - $sql .= ($hasWhereCondition ? ' AND ' : ' WHERE ') - . 's.enabled = 1'; - - // set ACL limitations - if ($aclSubQuery !== null) { - $sql .= ' AND ' . $aclSubQuery; - } - - // apply the service group filter to SQL query - if ($filter->getServicegroupNames()) { - $groupList = []; - - foreach ($filter->getServicegroupNames() as $index => $groupName) { - $key = ":serviceServicegroupName_{$index}"; - - $groupList[] = $key; - $collector->addValue($key, $groupName, \PDO::PARAM_STR); - } - - $sql .= ' AND EXISTS (SELECT 1 FROM `:dbstg`.`services_servicegroups` AS ssg - WHERE ssg.host_id = s.host_id AND ssg.service_id = s.service_id - AND EXISTS (SELECT 1 FROM `:dbstg`.`servicegroups` AS sg - WHERE ssg.servicegroup_id = sg.servicegroup_id - AND sg.name IN (' . implode(', ', $groupList) . ') LIMIT 1) LIMIT 1)'; - } - - // apply the state filter to SQL query - if ($filter->getStates() && !$filter->hasState(ResourceServiceInterface::STATE_ALL)) { - $sqlState = []; - $sqlStateCatalog = [ - ResourceServiceInterface::STATE_UNHANDLED_PROBLEMS => "(s.state_type = '1'" - . " AND s.acknowledged = 0" - . " AND s.scheduled_downtime_depth = 0" - . " AND sh.acknowledged = 0" - . " AND sh.scheduled_downtime_depth = 0" - . " AND s.state != 0" - . " AND s.state != 4)", - ResourceServiceInterface::STATE_RESOURCES_PROBLEMS => '(s.state != 0 AND s.state != 4)', - ResourceServiceInterface::STATE_IN_DOWNTIME => '(s.scheduled_downtime_depth = 1' - . ' OR sh.scheduled_downtime_depth = 1)', - ResourceServiceInterface::STATE_ACKNOWLEDGED => '(s.acknowledged = 1 OR sh.acknowledged = 1)', - ]; - - foreach ($filter->getStates() as $state) { - $sqlState[] = $sqlStateCatalog[$state]; - } - - $sql .= ' AND (' . implode(' OR ', $sqlState) . ')'; - } - - // apply the status filter to SQL query - $statuses = ResourceFilter::map($filter->getStatuses(), ResourceFilter::MAP_STATUS_SERVICE); - if ($statuses) { - $statusList = []; - - foreach ($statuses as $index => $status) { - $key = ":serviceStatuses_{$index}"; - - $statusList[] = $key; - $collector->addValue($key, $status, \PDO::PARAM_INT); - } - - $sql .= ' AND s.state IN (' . implode(', ', $statusList) . ')'; - } - - // apply the state types filter to SQL query - $statusTypes = ResourceFilter::map($filter->getStatusTypes(), ResourceFilter::MAP_STATUS_TYPES); - if ($statusTypes) { - $statusTypesList = []; - - foreach ($statusTypes as $index => $statusType) { - $key = ":serviceStateType_{$index}"; - - $statusTypesList[] = $key; - $collector->addValue($key, $statusType, \PDO::PARAM_INT); - } - - $sql .= ' AND s.state_type IN (' . implode(', ', $statusTypesList) . ')'; - } - - if (!empty($filter->getHostIds())) { - $hostIds = []; - - foreach ($filter->getHostIds() as $index => $hostId) { - $key = ":hostId_{$index}"; - - $hostIds[] = $key; - $collector->addValue($key, $hostId, \PDO::PARAM_INT); - } - - $sql .= ' AND sh.host_id IN (' . implode(', ', $hostIds) . ')'; - } - - if (!empty($filter->getServiceIds())) { - $serviceIds = []; - - foreach ($filter->getServiceIds() as $index => $serviceId) { - $key = ":serviceId_{$index}"; - - $serviceIds[] = $key; - $collector->addValue($key, $serviceId, \PDO::PARAM_INT); - } - - $sql .= ' AND s.service_id IN (' . implode(', ', $serviceIds) . ')'; - } - - // apply the monitoring server filter to SQL query - if (!empty($filter->getMonitoringServerNames())) { - $monitoringServerNames = []; - - foreach ($filter->getMonitoringServerNames() as $index => $monitoringServerName) { - $key = ":monitoringServerName_{$index}"; - - $monitoringServerNames[] = $key; - $collector->addValue($key, $monitoringServerName, \PDO::PARAM_STR); - } - - $sql .= ' AND i.name IN (' . implode(', ', $monitoringServerNames) . ')'; - } - return $sql; - } - - /** - * @inheritDoc - */ - public function excludeResourcesWithoutMetrics(array $resources): array - { - $filteredResources = []; - $collector = new StatementCollector(); - $where = []; - $serviceResources = []; - - foreach ($resources as $key => $resource) { - if ($resource->getType() === Resource::TYPE_SERVICE) { - $where[] = "(i.host_id = :host_id_{$key} AND i.service_id = :service_id_{$key})"; - $collector->addValue(":service_id_{$key}", $resource->getId(), \PDO::PARAM_INT); - $collector->addValue(":host_id_{$key}", $resource->getParent()->getId(), \PDO::PARAM_INT); - $serviceResources[] = $resource; - } else { - $filteredResources[] = $resource; - } - } - - if (empty($serviceResources)) { - return $filteredResources; - } - - $statement = $this->db->prepare( - $this->translateDbName( - 'SELECT i.host_id, i.service_id - FROM `:dbstg`.metrics AS m, `:dbstg`.index_data AS i - WHERE (' . implode(' OR ', $where) . ') - AND i.id = m.index_id - AND m.hidden = "0" - GROUP BY host_id, service_id' - ) - ); - $collector->bind($statement); - $statement->execute(); - - while ($row = $statement->fetch()) { - foreach ($serviceResources as $serviceResource) { - if ( - $serviceResource->getParent()->getId() === (int)$row['host_id'] - && $serviceResource->getId() === (int)$row['service_id'] - ) { - $filteredResources[] = $serviceResource; - } - } - } - - return $filteredResources; - } -} diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/ResourceRepositoryFactory.php b/src/Centreon/Infrastructure/Monitoring/Resource/ResourceRepositoryFactory.php deleted file mode 100644 index d57d52af4ee..00000000000 --- a/src/Centreon/Infrastructure/Monitoring/Resource/ResourceRepositoryFactory.php +++ /dev/null @@ -1,49 +0,0 @@ - Association of resource search parameters - */ - private $resourceConcordances = [ - 'id' => 'resource.id', - 'name' => 'resource.name', - 'alias' => 'resource.alias', - 'fqdn' => 'resource.fqdn', - 'type' => 'resource.type', - 'status_code' => 'resource.status_code', - 'status' => 'resource.status_name', - 'status_severity_code' => 'resource.status_severity_code', - 'action_url' => 'resource.action_url', - 'parent_name' => 'resource.parent_name', - 'parent_alias' => 'resource.parent_alias', - 'parent_status' => 'resource.parent_status_name', - 'severity_level' => 'resource.severity_level', - 'in_downtime' => 'resource.in_downtime', - 'acknowledged' => 'resource.acknowledged', - 'last_status_change' => 'resource.last_status_change', - 'tries' => 'resource.tries', - 'last_check' => 'resource.last_check', - 'monitoring_server_name' => 'resource.monitoring_server_name', - 'information' => 'resource.information', - ]; - - /** - * @param DatabaseConnection $pdo - */ - public function __construct(DatabaseConnection $pdo) - { - $this->db = $pdo; - } - - /** - * Initialized by the dependency injector. - * - * @param SqlRequestParametersTranslator $sqlRequestTranslator - */ - public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void - { - $this->sqlRequestTranslator = $sqlRequestTranslator; - $this->sqlRequestTranslator - ->getRequestParameters() - ->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT) - ->setConcordanceErrorMode(RequestParameters::CONCORDANCE_ERRMODE_SILENT); - } - - /** - * @param \Traversable $providers - * @return void - */ - public function setProviders(\Traversable $providers): void - { - if (count($providers) === 0) { - throw new \InvalidArgumentException( - _('You must at least add one resource provider') - ); - } - - $this->providers = iterator_to_array($providers); - } - - /** - * {@inheritDoc} - */ - public function setContact(ContactInterface $contact): ResourceRepositoryInterface - { - $this->contact = $contact; - - return $this; - } - - /** - * {@inheritDoc} - */ - public function filterByAccessGroups(?array $accessGroups): ResourceRepositoryInterface - { - $this->accessGroups = $accessGroups; - - return $this; - } - - /** - * {@inheritDoc} - */ - public function findResources(ResourceFilter $filter): array - { - $resources = []; - - if ($this->hasNotEnoughRightsToContinue()) { - return $resources; - } - - $collector = new StatementCollector(); - $request = 'SELECT SQL_CALC_FOUND_ROWS ' - . 'resource.id, resource.type, resource.name, resource.alias, resource.fqdn, ' - . 'resource.host_id, resource.service_id, ' - . 'resource.status_code, resource.status_name, resource.status_severity_code, ' // status - . 'resource.icon_name, resource.icon_url, ' // icon - . 'resource.command_line, resource.timezone, ' - . 'resource.parent_id, resource.parent_name, resource.parent_type, ' // parent - . 'resource.parent_alias, resource.parent_fqdn, ' // parent - . 'resource.parent_icon_name, resource.parent_icon_url, ' // parent icon - . 'resource.action_url, resource.notes_url, resource.notes_label, ' // external urls - . 'resource.monitoring_server_name, resource.monitoring_server_id, ' // monitoring server - // parent status - . 'resource.parent_status_code, resource.parent_status_name, resource.parent_status_severity_code, ' - . 'resource.flapping, resource.percent_state_change, ' - . 'resource.severity_level, ' // severity - . 'resource.in_downtime, resource.acknowledged, ' - . 'resource.active_checks, resource.passive_checks,' - . 'resource.last_status_change, ' - . 'resource.last_notification, resource.notification_number, ' - . 'resource.state_type, resource.tries, resource.last_check, resource.next_check, ' - . 'resource.information, resource.performance_data, ' - . 'resource.execution_time, resource.latency, ' - . 'resource.notification_enabled, resource.last_time_with_no_issue ' - . 'FROM ('; - - $subRequests = []; - foreach ($this->providers as $provider) { - if ($provider->shouldBeSearched($filter)) { - if ($this->isAdmin()) { - $subRequest = $provider->prepareSubQueryWithoutAcl($filter, $collector); - } else { - $accessGroupIds = array_map( - function ($accessGroup) { - return $accessGroup->getId(); - }, - $this->accessGroups - ); - $subRequest = $provider->prepareSubQueryWithAcl($filter, $collector, $accessGroupIds); - } - $subRequests[] = '(' . $subRequest . ')'; - } - } - - if (!$subRequests) { - $this->sqlRequestTranslator->getRequestParameters()->setTotal(0); - - return []; - } - - $request .= implode(' UNION ALL ', $subRequests); - unset($subRequests); - - $request .= ') AS `resource`'; - - $hasWhereCondition = false; - - // Search - $this->sqlRequestTranslator->setConcordanceArray($this->resourceConcordances); - try { - $searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql(); - } catch (RequestParametersTranslatorException $ex) { - throw new RepositoryException($ex->getMessage(), 0, $ex); - } - - if ($searchRequest !== null) { - $hasWhereCondition = true; - $request .= $searchRequest; - } - - // apply the host group filter to SQL query - if ($filter->getHostgroupNames()) { - $groupList = []; - - foreach ($filter->getHostgroupNames() as $index => $groupName) { - $key = ":resourceHostgroupName_{$index}"; - $groupList[] = $key; - $collector->addValue($key, $groupName, \PDO::PARAM_STR); - } - - $request .= ($hasWhereCondition === false) ? ' WHERE ' : ' AND '; - $hasWhereCondition = true; - - $request .= ' EXISTS ( - SELECT 1 FROM `:dbstg`.`hosts_hostgroups` AS hhg - WHERE hhg.host_id = resource.host_id - AND EXISTS ( - SELECT 1 FROM `:dbstg`.`hostgroups` AS hg - WHERE hg.hostgroup_id = hhg.hostgroup_id AND hg.name IN (' . implode(', ', $groupList) . ') - LIMIT 1) - LIMIT 1) '; - } - - /** - * If we specify that user only wants resources with available performance datas. - * Then only resources with existing metrics referencing index_data services will be returned. - */ - if ($filter->getOnlyWithPerformanceData() === true) { - $request .= $hasWhereCondition ? ' AND ' : ' WHERE '; - $request .= ' EXISTS ( - SELECT 1 FROM `:dbstg`.index_data AS idata - WHERE idata.host_id = resource.parent_id - AND idata.service_id = resource.id - AND resource.type = "service" - AND EXISTS (SELECT 1 FROM `:dbstg`.metrics AS m - WHERE m.index_id = idata.id - AND m.hidden = "0" LIMIT 1) LIMIT 1) '; - } - - foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) { - $collector->addValue($key, current($data), key($data)); - } - - // Sort - $request .= $this->sqlRequestTranslator->translateSortParameterToSql() - ?: ' ORDER BY resource.status_name DESC, resource.name ASC'; - - // Pagination - $request .= $this->sqlRequestTranslator->translatePaginationToSql(); - - $statement = $this->db->prepare( - $this->translateDbName($request) - ); - $collector->bind($statement); - - $statement->execute(); - - $this->sqlRequestTranslator->getRequestParameters()->setTotal( - (int)$this->db->query('SELECT FOUND_ROWS()')->fetchColumn() - ); - - while ($result = $statement->fetch()) { - $resources[] = $this->parseResource($result); - } - - return $resources; - } - - /** - * Parse array data from DB into Resource model - * - * @param array $data - * @return ResourceEntity - * @throws \Exception - */ - protected function parseResource(array $data): ResourceEntity - { - $resource = EntityCreator::createEntityByArray( - ResourceEntity::class, - $data - ); - - $resource->setHostId((int)$data['host_id']); - $resource->setServiceId((int)$data['service_id']); - - // parse ResourceStatus object - $resource->setStatus(EntityCreator::createEntityByArray( - ResourceStatus::class, - $data, - 'status_' - )); - - // parse Icon object - $icon = EntityCreator::createEntityByArray( - Icon::class, - $data, - 'icon_' - ); - - if ($icon->getUrl()) { - $resource->setIcon($icon); - } - - $parent = null; - if ($resource->getType() === ResourceEntity::TYPE_SERVICE) { - // parse parent Resource object - $parent = EntityCreator::createEntityByArray( - ResourceEntity::class, - $data, - 'parent_' - ); - - if ($parent->getId()) { - $parentIcon = EntityCreator::createEntityByArray( - Icon::class, - $data, - 'parent_icon_' - ); - - if ($parentIcon->getUrl()) { - $parent->setIcon($parentIcon); - } - - $parentStatus = EntityCreator::createEntityByArray( - ResourceStatus::class, - $data, - 'parent_status_' - ); - $parent->setStatus($parentStatus); - } - } - - $resource->setParent($parent); - - // Setting the External links - $externalLinks = $resource->getLinks()->getExternals(); - $externalLinks->setActionUrl($data['action_url']); - $notes = (new Notes()) - ->setUrl($data['notes_url']) - ->setLabel($data['notes_label']); - $externalLinks->setNotes($notes); - - return $resource; - } - - /** - * {@inheritDoc} - */ - public function extractResourcesWithGraphData(array $resources): array - { - foreach ($this->providers as $provider) { - $resources = $provider->excludeResourcesWithoutMetrics($resources); - } - - return $resources; - } - - /** - * Check if the contact is admin - * - * @return bool - */ - private function isAdmin(): bool - { - return ($this->contact !== null) - ? $this->contact->isAdmin() - : false; - } - - /** - * @return bool Return FALSE if the contact is an admin or has at least one access group. - */ - private function hasNotEnoughRightsToContinue(): bool - { - return ($this->contact !== null) - ? !($this->contact->isAdmin() || count($this->accessGroups) > 0) - : count($this->accessGroups) == 0; - } -} diff --git a/src/Centreon/Domain/Monitoring/Interfaces/ResourceRepositoryInterface.php b/src/Core/Resources/Application/Repository/ReadResourceRepositoryInterface.php similarity index 89% rename from src/Centreon/Domain/Monitoring/Interfaces/ResourceRepositoryInterface.php rename to src/Core/Resources/Application/Repository/ReadResourceRepositoryInterface.php index 315b309e60f..9bbbb5caba8 100644 --- a/src/Centreon/Domain/Monitoring/Interfaces/ResourceRepositoryInterface.php +++ b/src/Core/Resources/Application/Repository/ReadResourceRepositoryInterface.php @@ -20,13 +20,13 @@ */ declare(strict_types=1); -namespace Centreon\Domain\Monitoring\Interfaces; +namespace Core\Resources\Application\Repository; use Centreon\Domain\Monitoring\ResourceFilter; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Monitoring\Resource as ResourceEntity; -interface ResourceRepositoryInterface +interface ReadResourceRepositoryInterface { /** * Find all resources. @@ -38,7 +38,7 @@ public function findResources(ResourceFilter $filter): array; /** * @param ContactInterface $contact - * @return ResourceRepositoryInterface + * @return self */ public function setContact(ContactInterface $contact): self; @@ -46,9 +46,9 @@ public function setContact(ContactInterface $contact): self; * Sets the access groups that will be used to filter services and the host. * * @param \Core\Security\Domain\AccessGroup\Model\AccessGroup[]|null $accessGroups - * @return ResourceRepositoryInterface + * @return self */ - public function filterByAccessGroups(?array $accessGroups): ResourceRepositoryInterface; + public function filterByAccessGroups(?array $accessGroups): self; /** * Get list of resources with graph data. diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/DbReadResourceRepository.php b/src/Core/Resources/Infrastructure/Repository/DbReadResourceRepository.php similarity index 98% rename from src/Centreon/Infrastructure/Monitoring/Resource/DbReadResourceRepository.php rename to src/Core/Resources/Infrastructure/Repository/DbReadResourceRepository.php index a47e7bc3b0b..c97ee95e00c 100644 --- a/src/Centreon/Infrastructure/Monitoring/Resource/DbReadResourceRepository.php +++ b/src/Core/Resources/Infrastructure/Repository/DbReadResourceRepository.php @@ -20,7 +20,7 @@ */ declare(strict_types=1); -namespace Centreon\Infrastructure\Monitoring\Resource; +namespace Core\Resources\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Core\Tag\RealTime\Domain\Model\Tag; @@ -33,13 +33,13 @@ use Centreon\Domain\Monitoring\Resource as ResourceEntity; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector; -use Centreon\Domain\Monitoring\Interfaces\ResourceRepositoryInterface; +use Core\Resources\Application\Repository\ReadResourceRepositoryInterface; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException; use Core\Infrastructure\RealTime\Repository\Icon\DbIconFactory; use Core\Severity\RealTime\Domain\Model\Severity; -class DbReadResourceRepository extends AbstractRepositoryDRB implements ResourceRepositoryInterface +class DbReadResourceRepository extends AbstractRepositoryDRB implements ReadResourceRepositoryInterface { use LoggerTrait; @@ -98,19 +98,11 @@ class DbReadResourceRepository extends AbstractRepositoryDRB implements Resource /** * @param DatabaseConnection $db - */ - public function __construct(DatabaseConnection $db) - { - $this->db = $db; - } - - /** - * Initialized by the dependency injector. - * * @param SqlRequestParametersTranslator $sqlRequestTranslator */ - public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void + public function __construct(DatabaseConnection $db, SqlRequestParametersTranslator $sqlRequestTranslator) { + $this->db = $db; $this->sqlRequestTranslator = $sqlRequestTranslator; $this->sqlRequestTranslator ->getRequestParameters() @@ -121,7 +113,7 @@ public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlReque /** * @inheritDoc */ - public function setContact(ContactInterface $contact): ResourceRepositoryInterface + public function setContact(ContactInterface $contact): ReadResourceRepositoryInterface { $this->contact = $contact; return $this; @@ -130,7 +122,7 @@ public function setContact(ContactInterface $contact): ResourceRepositoryInterfa /** * @inheritDoc */ - public function filterByAccessGroups(?array $accessGroups): ResourceRepositoryInterface + public function filterByAccessGroups(?array $accessGroups): ReadResourceRepositoryInterface { $this->accessGroups = $accessGroups; return $this; @@ -163,6 +155,7 @@ public function findResources(ResourceFilter $filter): array parent_resource.status AS `parent_status`, parent_resource.alias AS `parent_alias`, parent_resource.status_ordered AS `parent_status_ordered`, + parent_resource.address AS `parent_fqdn`, severities.id AS `severity_id`, severities.level AS `severity_level`, severities.name AS `severity_name`, diff --git a/src/Centreon/Infrastructure/Monitoring/Resource/DbResourceFactory.php b/src/Core/Resources/Infrastructure/Repository/DbResourceFactory.php similarity index 98% rename from src/Centreon/Infrastructure/Monitoring/Resource/DbResourceFactory.php rename to src/Core/Resources/Infrastructure/Repository/DbResourceFactory.php index ee21ea04407..329b7343e7d 100644 --- a/src/Centreon/Infrastructure/Monitoring/Resource/DbResourceFactory.php +++ b/src/Core/Resources/Infrastructure/Repository/DbResourceFactory.php @@ -20,7 +20,7 @@ */ declare(strict_types=1); -namespace Centreon\Infrastructure\Monitoring\Resource; +namespace Core\Resources\Infrastructure\Repository; use Core\Domain\RealTime\Model\Icon; use Centreon\Domain\Monitoring\Notes; @@ -55,6 +55,7 @@ public static function createFromRecord(array $record): ResourceEntity ->setName($record['parent_name']) ->setAlias($record['parent_alias']) ->setType(ResourceEntity::TYPE_HOST) + ->setFqdn($record['parent_fqdn']) ->setStatus($parentStatus); } diff --git a/tests/e2e/cypress/commons.ts b/tests/e2e/cypress/commons.ts index 25e5d791bd2..f59a30cb207 100644 --- a/tests/e2e/cypress/commons.ts +++ b/tests/e2e/cypress/commons.ts @@ -36,7 +36,7 @@ let servicesFoundStepCount = 0; const checkThatFixtureServicesExistInDatabase = (): void => { cy.log('Checking services in database'); - const query = `SELECT COUNT(s.service_id) as count_services from services as s WHERE s.description LIKE '%service_test%' AND s.output LIKE '%submit_status_2%' AND s.enabled=1;`; + const query = `SELECT COUNT(s.service_id) as count_services from services as s WHERE s.description LIKE '%service_test_ack%' AND s.output LIKE '%submit_status_2%' AND s.enabled=1;`; const command = `docker exec -i ${Cypress.env( 'dockerName', )} mysql -ucentreon -pcentreon centreon_storage <<< "${query}"`; diff --git a/tests/e2e/cypress/fixtures/resources/clapi/service1/01-add.json b/tests/e2e/cypress/fixtures/resources/clapi/service1/01-add.json index 351497aadc3..d1d035fce0f 100644 --- a/tests/e2e/cypress/fixtures/resources/clapi/service1/01-add.json +++ b/tests/e2e/cypress/fixtures/resources/clapi/service1/01-add.json @@ -1,5 +1,5 @@ { "action": "ADD", "object": "SERVICE", - "values": "test_host;service_test;Ping-LAN;" + "values": "test_host;service_test_ack;SNMP-DISK-/;" } \ No newline at end of file diff --git a/tests/e2e/cypress/fixtures/resources/clapi/service1/02-set-max-check.json b/tests/e2e/cypress/fixtures/resources/clapi/service1/02-set-max-check.json index f0dfc1b6bb1..1ae08fa5353 100644 --- a/tests/e2e/cypress/fixtures/resources/clapi/service1/02-set-max-check.json +++ b/tests/e2e/cypress/fixtures/resources/clapi/service1/02-set-max-check.json @@ -1,5 +1,5 @@ { "action": "SETPARAM", "object": "SERVICE", - "values": "test_host;service_test;max_check_attempts;1" + "values": "test_host;service_test_ack;max_check_attempts;1" } \ No newline at end of file diff --git a/tests/e2e/cypress/fixtures/resources/clapi/service1/03-disable-active-check.json b/tests/e2e/cypress/fixtures/resources/clapi/service1/03-disable-active-check.json index 6bbe153d101..98c2aab2348 100644 --- a/tests/e2e/cypress/fixtures/resources/clapi/service1/03-disable-active-check.json +++ b/tests/e2e/cypress/fixtures/resources/clapi/service1/03-disable-active-check.json @@ -1,5 +1,5 @@ { "action": "SETPARAM", "object": "SERVICE", - "values": "test_host;service_test;active_checks_enabled;0" + "values": "test_host;service_test_ack;active_checks_enabled;0" } \ No newline at end of file diff --git a/tests/e2e/cypress/fixtures/resources/clapi/service1/04-enable-passive-check.json b/tests/e2e/cypress/fixtures/resources/clapi/service1/04-enable-passive-check.json index 1c6dc6237f7..a4d320a5bb5 100644 --- a/tests/e2e/cypress/fixtures/resources/clapi/service1/04-enable-passive-check.json +++ b/tests/e2e/cypress/fixtures/resources/clapi/service1/04-enable-passive-check.json @@ -1,5 +1,5 @@ { "action": "SETPARAM", "object": "SERVICE", - "values": "test_host;service_test;passive_checks_enabled;1" + "values": "test_host;service_test_ack;passive_checks_enabled;1" } \ No newline at end of file diff --git a/tests/e2e/cypress/fixtures/resources/clapi/submit-results.json b/tests/e2e/cypress/fixtures/resources/clapi/submit-results.json index 1f3c4f37f36..35e226ced32 100644 --- a/tests/e2e/cypress/fixtures/resources/clapi/submit-results.json +++ b/tests/e2e/cypress/fixtures/resources/clapi/submit-results.json @@ -3,7 +3,7 @@ { "updatetime": "", "host": "test_host", - "service": "service_test", + "service": "service_test_ack", "status": "2", "output": "submit_status_2", "perfdata": "" diff --git a/tests/e2e/cypress/integration/Resources-status/01-listing/index.ts b/tests/e2e/cypress/integration/Resources-status/01-listing/index.ts index 5b081f5330c..f91d7b22a96 100644 --- a/tests/e2e/cypress/integration/Resources-status/01-listing/index.ts +++ b/tests/e2e/cypress/integration/Resources-status/01-listing/index.ts @@ -23,7 +23,7 @@ Then('the unhandled problems filter is selected', (): void => { Then('only non-ok resources are displayed', () => { cy.contains('service_test_dt'); - cy.contains('service_test'); + cy.contains('service_test_ack'); cy.contains('service_test_ok').should('not.exist'); cy.contains('CRITICAL'); cy.contains('OK').should('not.exist'); diff --git a/tests/e2e/cypress/integration/Resources-status/02-actions/index.ts b/tests/e2e/cypress/integration/Resources-status/02-actions/index.ts index c49f07c81eb..8b07168eb06 100644 --- a/tests/e2e/cypress/integration/Resources-status/02-actions/index.ts +++ b/tests/e2e/cypress/integration/Resources-status/02-actions/index.ts @@ -9,7 +9,7 @@ import { } from '../common'; import { refreshListing } from '../../../support/centreonData'; -const serviceName = 'service_test'; +const serviceInAcknowledgementName = 'service_test_ack'; const serviceInDowntimeName = 'service_test_dt'; before(() => { @@ -17,7 +17,7 @@ before(() => { }); When('I select the acknowledge action on a problematic Resource', () => { - cy.contains(serviceName) + cy.contains(serviceInAcknowledgementName) .parents('div[role="row"]:first') .find('input[type="checkbox"]:first') .click(); @@ -36,7 +36,7 @@ Then('the problematic Resource is displayed as acknowledged', () => { cy.get(stateFilterContainer).click().get('[data-value="all"]').click(); cy.waitUntil(() => { return refreshListing() - .then(() => cy.contains(serviceName)) + .then(() => cy.contains(serviceInAcknowledgementName)) .parent() .parent() .parent() diff --git a/tests/php/Centreon/Domain/Monitoring/ResourceServiceTest.php b/tests/php/Centreon/Domain/Monitoring/ResourceServiceTest.php index 8b2f93a604e..56a32dd59b1 100644 --- a/tests/php/Centreon/Domain/Monitoring/ResourceServiceTest.php +++ b/tests/php/Centreon/Domain/Monitoring/ResourceServiceTest.php @@ -24,9 +24,9 @@ use Centreon\Domain\Monitoring\Resource; use Centreon\Domain\Monitoring\ResourceFilter; use Centreon\Domain\Monitoring\ResourceService; -use Centreon\Domain\Monitoring\Interfaces\ResourceRepositoryInterface; use Core\Security\Application\Repository\ReadAccessGroupRepositoryInterface; use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface; +use Core\Resources\Application\Repository\ReadResourceRepositoryInterface; it('find resources and build uuids', function () { $hostResource = (new Resource()) @@ -39,7 +39,7 @@ ->setName('service1') ->setParent($hostResource); - $resourceRepository = $this->createMock(ResourceRepositoryInterface::class); + $resourceRepository = $this->createMock(ReadResourceRepositoryInterface::class); $resourceRepository->expects($this->any()) ->method('findResources') ->willReturn([$hostResource, $serviceResource]); // values returned for the all next tests diff --git a/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProviderTest.php b/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProviderTest.php deleted file mode 100644 index 7fd230c71be..00000000000 --- a/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/HostProviderTest.php +++ /dev/null @@ -1,163 +0,0 @@ -databaseConnection = $this->createMock(DatabaseConnection::class); - $this->sqlRequestParametersTranslator = $this->createMock(SqlRequestParametersTranslator::class); - $this->requestParameters = new RequestParameters(); - $this->sqlRequestParametersTranslator->expects($this->any()) - ->method('getRequestParameters') - ->willReturn($this->requestParameters); - - $this->resourceFilter = (new ResourceFilter()); - - $this->hostProvider = new HostProvider($this->databaseConnection); - } - - /** - * test shouldBeSearched with resource name filter - */ - public function testShouldBeSearchedWithResourceName() - { - $this->hostProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'name' => 'test' - ])); - - $shouldBeSearched = $this->hostProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test shouldBeSearched with host name filter - */ - public function testShouldBeSearchedWithHostName() - { - $this->hostProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'h.name' => 'test' - ])); - - $shouldBeSearched = $this->hostProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test shouldBeSearched with multiple filter criterias - */ - public function testShouldBeSearchedWithMultipleCriterias() - { - $this->hostProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'h.name' => 'test', - 's.description' => 'test' - ])); - - $shouldBeSearched = $this->hostProvider->shouldBeSearched($this->resourceFilter); - - $this->assertFalse($shouldBeSearched); - } - - /** - * test shouldBeSearched with service description filter - */ - public function testShouldNotBeSearched() - { - $this->hostProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 's.description' => 'test' - ])); - - $shouldBeSearched = $this->hostProvider->shouldBeSearched($this->resourceFilter); - - $this->assertFalse($shouldBeSearched); - } - - /** - * test excludeResourcesWithoutMetrics with one host - */ - public function testExcludeResourcesWithoutMetrics() - { - $hostResource = (new Resource()) - ->setType('host') - ->setId(1) - ->setName('host1'); - $serviceResource = (new Resource()) - ->setType('service') - ->setId(1) - ->setName('service1') - ->setParent($hostResource); - $metaServiceResource = (new Resource()) - ->setType('metaservice') - ->setId(1) - ->setName('meta1'); - $resources = [$hostResource, $serviceResource, $metaServiceResource]; - - $filteredResources = $this->hostProvider->excludeResourcesWithoutMetrics($resources); - - $this->assertCount(2, $filteredResources); - - foreach ($filteredResources as $filteredResource) { - $this->assertNotEquals('host', $filteredResource->getType()); - } - } -} diff --git a/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProviderTest.php b/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProviderTest.php deleted file mode 100644 index 12754baf807..00000000000 --- a/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/MetaServiceProviderTest.php +++ /dev/null @@ -1,209 +0,0 @@ -databaseConnection = $this->createMock(DatabaseConnection::class); - $this->sqlRequestParametersTranslator = $this->createMock(SqlRequestParametersTranslator::class); - $this->requestParameters = new RequestParameters(); - $this->sqlRequestParametersTranslator->expects($this->any()) - ->method('getRequestParameters') - ->willReturn($this->requestParameters); - - $this->resourceFilter = (new ResourceFilter()); - - $this->metaServiceProvider = new MetaServiceProvider($this->databaseConnection); - } - - /** - * test shouldBeSearched with resource name filter - */ - public function testShouldBeSearchedWithResourceName() - { - $this->metaServiceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'name' => 'test' - ])); - - $shouldBeSearched = $this->metaServiceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test shouldBeSearched with host name filter - */ - public function testShouldBeSearchedWithHostName() - { - $this->metaServiceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'h.name' => 'test' - ])); - - $shouldBeSearched = $this->metaServiceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertFalse($shouldBeSearched); - } - - /** - * test shouldBeSearched with multiple filter criterias - */ - public function testShouldBeSearchedWithMultipleCriterias() - { - $this->metaServiceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'name' => 'test', - 's.description' => 'test' - ])); - - $shouldBeSearched = $this->metaServiceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertFalse($shouldBeSearched); - } - - /** - * test shouldBeSearched with service description filter - */ - public function testShouldNotBeSearched() - { - $this->metaServiceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 's.description' => 'test' - ])); - - $shouldBeSearched = $this->metaServiceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertFalse($shouldBeSearched); - } - - /** - * test excludeResourcesWithoutMetrics with a metaservice which has metrics - */ - public function testExcludeResourcesWithoutMetricsWithData() - { - $pdoStatement = $this->createMock(\PDOStatement::class); - $pdoStatement->expects($this->exactly(2)) - ->method('fetch') - ->will( - $this->onConsecutiveCalls( - [ - 'host_id' => 1, - 'service_id' => 1, - 'description' => 'meta_1', - ], - null - ) - ); - $this->databaseConnection->expects($this->any()) - ->method('prepare') - ->willReturn($pdoStatement); - - $hostResource = (new Resource()) - ->setType('host') - ->setId(1) - ->setName('host1'); - $serviceResource = (new Resource()) - ->setType('service') - ->setId(1) - ->setName('service1') - ->setParent($hostResource); - $metaServiceResource = (new Resource()) - ->setType('metaservice') - ->setId(1) - ->setName('meta1'); - $resources = [$hostResource, $serviceResource, $metaServiceResource]; - - $filteredResources = $this->metaServiceProvider->excludeResourcesWithoutMetrics($resources); - - $this->assertCount(3, $filteredResources); - } - - /** - * test excludeResourcesWithoutMetrics with a metaservice which does not have metrics - */ - public function testExcludeResourcesWithoutMetricsWithoutData() - { - $pdoStatement = $this->createMock(\PDOStatement::class); - $pdoStatement->expects($this->any()) - ->method('fetch') - ->willReturn(null); - $this->databaseConnection->expects($this->any()) - ->method('prepare') - ->willReturn($pdoStatement); - - $hostResource = (new Resource()) - ->setType('host') - ->setId(1) - ->setName('host1'); - $serviceResource = (new Resource()) - ->setType('service') - ->setId(1) - ->setName('service1') - ->setParent($hostResource); - $metaServiceResource = (new Resource()) - ->setType('metaservice') - ->setId(1) - ->setName('meta1'); - $resources = [$hostResource, $serviceResource, $metaServiceResource]; - - $filteredResources = $this->metaServiceProvider->excludeResourcesWithoutMetrics($resources); - - $this->assertCount(2, $filteredResources); - } -} diff --git a/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/ServiceProviderTest.php b/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/ServiceProviderTest.php deleted file mode 100644 index b71faee9eea..00000000000 --- a/tests/php/Centreon/Infrastructure/Monitoring/Resource/Provider/ServiceProviderTest.php +++ /dev/null @@ -1,208 +0,0 @@ -databaseConnection = $this->createMock(DatabaseConnection::class); - $this->sqlRequestParametersTranslator = $this->createMock(SqlRequestParametersTranslator::class); - $this->requestParameters = new RequestParameters(); - $this->sqlRequestParametersTranslator->expects($this->any()) - ->method('getRequestParameters') - ->willReturn($this->requestParameters); - - $this->resourceFilter = (new ResourceFilter()); - - $this->serviceProvider = new ServiceProvider($this->databaseConnection); - } - - /** - * test shouldBeSearched with resource name filter - */ - public function testShouldBeSearchedWithResourceName() - { - $this->serviceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'name' => 'test' - ])); - - $shouldBeSearched = $this->serviceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test shouldBeSearched with host name filter - */ - public function testShouldBeSearchedWithHostName() - { - $this->serviceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'h.name' => 'test' - ])); - - $shouldBeSearched = $this->serviceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test shouldBeSearched with multiple filter criterias - */ - public function testShouldBeSearchedWithMultipleCriterias() - { - $this->serviceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 'h.name' => 'test', - 's.description' => 'test' - ])); - - $shouldBeSearched = $this->serviceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test shouldBeSearched with service description filter - */ - public function testShouldNotBeSearched() - { - $this->serviceProvider->setSqlRequestTranslator($this->sqlRequestParametersTranslator); - $this->requestParameters->setSearch(json_encode([ - 's.description' => 'test' - ])); - - $shouldBeSearched = $this->serviceProvider->shouldBeSearched($this->resourceFilter); - - $this->assertTrue($shouldBeSearched); - } - - /** - * test excludeResourcesWithoutMetrics with a metaservice which has metrics - */ - public function testExcludeResourcesWithoutMetricsWithData() - { - $pdoStatement = $this->createMock(\PDOStatement::class); - $pdoStatement->expects($this->exactly(2)) - ->method('fetch') - ->will( - $this->onConsecutiveCalls( - [ - 'host_id' => 1, - 'service_id' => 1, - ], - null - ) - ); - $this->databaseConnection->expects($this->any()) - ->method('prepare') - ->willReturn($pdoStatement); - - $hostResource = (new Resource()) - ->setType('host') - ->setId(1) - ->setName('host1'); - $serviceResource = (new Resource()) - ->setType('service') - ->setId(1) - ->setName('service1') - ->setParent($hostResource); - $metaServiceResource = (new Resource()) - ->setType('metaservice') - ->setId(1) - ->setName('meta1'); - $resources = [$hostResource, $serviceResource, $metaServiceResource]; - - $filteredResources = $this->serviceProvider->excludeResourcesWithoutMetrics($resources); - - $this->assertCount(3, $filteredResources); - } - - /** - * test excludeResourcesWithoutMetrics with a metaservice which does not have metrics - */ - public function testExcludeResourcesWithoutMetricsWithoutData() - { - $pdoStatement = $this->createMock(\PDOStatement::class); - $pdoStatement->expects($this->any()) - ->method('fetch') - ->willReturn(null); - $this->databaseConnection->expects($this->any()) - ->method('prepare') - ->willReturn($pdoStatement); - - $hostResource = (new Resource()) - ->setType('host') - ->setId(1) - ->setName('host1'); - $serviceResource = (new Resource()) - ->setType('service') - ->setId(1) - ->setName('service1') - ->setParent($hostResource); - $metaServiceResource = (new Resource()) - ->setType('metaservice') - ->setId(1) - ->setName('meta1'); - $resources = [$hostResource, $serviceResource, $metaServiceResource]; - - $filteredResources = $this->serviceProvider->excludeResourcesWithoutMetrics($resources); - - $this->assertCount(2, $filteredResources); - } -} diff --git a/tests/php/Centreon/Infrastructure/Monitoring/Resource/DbResourceFactoryTest.php b/tests/php/Core/Resources/Infrastructure/Repository/DbResourceFactoryTest.php similarity index 98% rename from tests/php/Centreon/Infrastructure/Monitoring/Resource/DbResourceFactoryTest.php rename to tests/php/Core/Resources/Infrastructure/Repository/DbResourceFactoryTest.php index e39d46135e9..aee70ceb0d6 100644 --- a/tests/php/Centreon/Infrastructure/Monitoring/Resource/DbResourceFactoryTest.php +++ b/tests/php/Core/Resources/Infrastructure/Repository/DbResourceFactoryTest.php @@ -23,9 +23,9 @@ namespace Tests\Centreon\Infrastructure\Monitoring\Resource; -use Centreon\Domain\Monitoring\Resource as ResourceEntity; use Centreon\Domain\Monitoring\ResourceStatus; -use Centreon\Infrastructure\Monitoring\Resource\DbResourceFactory; +use Centreon\Domain\Monitoring\Resource as ResourceEntity; +use Core\Resources\Infrastructure\Repository\DbResourceFactory; beforeEach(function () { $this->record = [ @@ -40,6 +40,7 @@ 'parent_status' => '2', 'parent_alias' => 'Database', 'parent_status_ordered' => '2', + 'parent_fqdn' => '127.0.0.1', 'type' => '0', 'status' => '0', 'status_ordered' => '0', diff --git a/www/include/Administration/parameters/DB-Func.php b/www/include/Administration/parameters/DB-Func.php index c72b741ff1a..c918787c24a 100644 --- a/www/include/Administration/parameters/DB-Func.php +++ b/www/include/Administration/parameters/DB-Func.php @@ -149,44 +149,6 @@ function isSessionDurationValid(int $value = null) return ($value > 0 && $value <= SESSION_DURATION_LIMIT); } -/** - * rule to check if resource status optimized mode is allowed - * - * @param int $value - * @return bool - */ -function canUseResourceStatusOptimized($value) -{ - global $pearDB; - - $mode = $value['resource_status_mode']; - - $kernel = \App\Kernel::createForWeb(); - $legacyMode = $kernel->getContainer()->getparameter('resource.status.repository.legacy'); - - if ($mode === $legacyMode) { - return true; - } - - $statement = $pearDB->query( - "SELECT 1 - FROM cfg_centreonbroker cb - INNER JOIN cfg_centreonbroker_info cbi ON cbi.config_id = cb.config_id - AND config_group = 'output' - AND config_key = 'type' - AND config_value = 'unified_sql' - WHERE cb.daemon = 1 - AND cb.bbdo_version = '3.0.0' - LIMIT 1" - ); - - if ($statement->fetch()) { - return true; - } - - return false; -} - function updateGeneralOptInDB($gopt_id = null) { if (!$gopt_id) { @@ -727,41 +689,6 @@ function updateGeneralConfigData() $centreon->initOptGen($pearDB); } -/** - * Update Resource Status environment variable in PHP file. - * - * @throws \Exception - */ -function updateResourceStatusMode(): void -{ - global $form; - - $ret = $form->getSubmitValues(); - - $dotenvPath = __DIR__ . '/../../../../.env.local.php'; - $dotenvVars = is_file($dotenvPath) ? include $dotenvPath : []; - $dotenvVars['APP_RESOURCE_STATUS_REPOSITORY_MODE'] = !empty($ret['resource_status_mode']['resource_status_mode']) - ? $ret['resource_status_mode']['resource_status_mode'] - : 'legacy'; - $dotenvVars = var_export($dotenvVars, true); - $dotenvVars = << {$form.monitoring_dwt_fixed.label}{$form.monitoring_dwt_fixed.html}  {$form.monitoring_dwt_svc.label}{$form.monitoring_dwt_svc.html}  {$form.monitoring_dwt_duration.label}{$form.monitoring_dwt_duration.html} {$form.monitoring_dwt_duration_scale.html} - - -

{$resource_status_mod}

- - - - - - {$form.resource_status_mode.label} - - {$form.resource_status_mode.html} - {if isset($form.required)} {$form.required._note} diff --git a/www/include/Administration/parameters/engine/form.php b/www/include/Administration/parameters/engine/form.php index 840c9d87113..ec81b50a2fe 100644 --- a/www/include/Administration/parameters/engine/form.php +++ b/www/include/Administration/parameters/engine/form.php @@ -99,34 +99,6 @@ ); $form->addElement('select', 'monitoring_dwt_duration_scale', _("Scale of time"), $scaleChoices); -$kernel = \App\Kernel::createForWeb(); -$resourceStatusMode = $kernel->getContainer()->getparameter('resource.status.repository'); - -$resourceStatusModeElements = [ - $form->createElement( - 'radio', - 'resource_status_mode', - null, - _("Legacy"), - 'legacy', - ), - $form->createElement( - 'radio', - 'resource_status_mode', - null, - _("Optimized (beta)"), - 'optimized', - ), -]; -$form->addGroup($resourceStatusModeElements, 'resource_status_mode', _("Resource status mode"), ' '); -$form->setDefaults(['resource_status_mode' => $resourceStatusMode]); -$form->registerRule('canUseResourceStatusOptimized', 'callback', 'canUseResourceStatusOptimized'); -$form->addRule( - 'resource_status_mode', - _("Optimized mode is not possible, BBDOv3 and unified SQL output must be configured"), - 'canUseResourceStatusOptimized' -); - $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); @@ -175,7 +147,6 @@ try { // Update in DB updateNagiosConfigData($form->getSubmitValue("gopt_id")); - updateResourceStatusMode(); // Update in Centreon Object $oreon->initOptGen($pearDB); @@ -233,7 +204,6 @@ $tpl->assign("genOpt_monitoring_properties", "Monitoring properties"); $tpl->assign("acknowledgement_default_settings", _("Default acknowledgement settings")); $tpl->assign("downtime_default_settings", _("Default downtime settings")); -$tpl->assign("resource_status_mod", _("Resource Status mod")); $tpl->assign("seconds", _("seconds")); $tpl->assign('valid', $valid); diff --git a/www/include/Administration/parameters/engine/help.php b/www/include/Administration/parameters/engine/help.php index 43d24baef6d..f840d519d3f 100644 --- a/www/include/Administration/parameters/engine/help.php +++ b/www/include/Administration/parameters/engine/help.php @@ -107,11 +107,3 @@ 'help', 'When enabled, "Service Unknown" notification messages will be displayed.' ); -/** - * Monitoring - */ -$help['tip_resource_status_mode'] = dgettext( - 'help', - 'Mode used to retrieve information displayed in Resource Status page. The optimized mode will only be available ' - . ' and functional when using the BBDO 3.0.0 protocol for the collect engine.' -);