Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 83 additions & 48 deletions application/controllers/EventRuleController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,34 @@

use Icinga\Application\Hook;
use Icinga\Application\Logger;
use Icinga\Exception\ConfigurationError;
use Icinga\Exception\Http\HttpNotFoundException;
use Icinga\Module\Notifications\Common\Auth;
use Icinga\Module\Notifications\Common\Database;
use Icinga\Module\Notifications\Common\Links;
use Icinga\Module\Notifications\Forms\EventRuleConfigElements\NotificationConfigProvider;
use Icinga\Module\Notifications\Forms\EventRuleConfigForm;
use Icinga\Module\Notifications\Forms\EventRuleForm;
use Icinga\Module\Notifications\Hook\V1\SourceHook;
use Icinga\Module\Notifications\Hook\V2\SourceHook;
use Icinga\Module\Notifications\Model\Rule;
use Icinga\Module\Notifications\Model\Source;
use Icinga\Module\Notifications\Util\RuleSerializer;
use Icinga\Module\Notifications\Web\Control\SearchBar\ExtraTagSuggestions;
use Icinga\Module\Notifications\Web\Control\SearchEditor\RuleFilterSuggestions;
use Icinga\Web\Notification;
use Icinga\Web\Session;
use ipl\Html\Contract\Form;
use ipl\Html\Html;
use ipl\Stdlib\Filter;
use ipl\Stdlib\Filter\Condition;
use ipl\Web\Compat\CompatController;
use ipl\Web\Compat\CompatForm;
use ipl\Web\Control\SearchBar\SearchException;
use ipl\Web\Control\SearchEditor;
use ipl\Web\Filter\QueryString;
use ipl\Web\Url;
use ipl\Web\Widget\Icon;
use ipl\Web\Widget\Link;
use JsonException;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;

Expand Down Expand Up @@ -195,7 +202,64 @@ public function searchEditorAction(): void
{
$ruleId = (int) $this->params->getRequired('id');
$filter = $this->params->get('object_filter', $this->session->get('object_filter'));
$hook = $this->resolveSourceHook($ruleId);

$parsedFilter = null;
if ($filter) {
try {
$parsedFilter = json_decode($filter, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
Logger::error('Failed to parse rule filter configuration: %s (Error: %s)', $filter, $e);
throw new ConfigurationError($this->translate(
'Failed to parse rule filter configuration. Please contact your system administrator.'
));
}
}

$editor = (new SearchEditor())
->setQueryString($parsedFilter['qs'] ?? '')
->setSuggestionUrl(
Url::fromPath(
'notifications/event-rule/suggest',
['id' => $ruleId, '_disableLayout' => true, 'showCompact' => true]
)
)
->setAction(Url::fromRequest()->with('object_filter', $filter)->getAbsoluteUrl())
->on(
SearchEditor::ON_VALIDATE_COLUMN,
function (Condition $condition) use ($hook) {
if (! $hook->isValidCondition($condition)) {
throw new SearchException($this->translate('Is not a valid column'));
}
}
)
->on(Form::ON_SUBMIT, function (SearchEditor $form) use ($ruleId, $hook) {
$filter = $form->getFilter();

$this->session->set(
'object_filter',
(new RuleSerializer($filter, $hook->getJsonPaths($this->collectColumns($filter))))->getJson()
);
$this->redirectNow(Links::eventRule($ruleId)->setParam('_filterOnly'));
});

$editor->getParser()->on(QueryString::ON_CONDITION, $hook->enrichCondition(...));
$editor->handleRequest($this->getServerRequest());

$this->getDocument()->addHtml($editor);

$this->setTitle($this->translate('Adjust Filter'));
}

public function suggestAction(): void
{
$hook = $this->resolveSourceHook((int) $this->params->getRequired('id'));
$suggestions = (new RuleFilterSuggestions($hook))->forRequest($this->getServerRequest());
$this->getDocument()->addHtml($suggestions);
}

protected function resolveSourceHook(int $ruleId): SourceHook
{
$source = null;
if ($ruleId !== -1) {
$source = Rule::on(Database::get())
Expand All @@ -217,7 +281,7 @@ public function searchEditorAction(): void
}

$hook = null;
foreach (Hook::all('Notifications/v1/Source') as $h) {
foreach (Hook::all('Notifications/v2/Source') as $h) {
/** @var SourceHook $h */
try {
if ($h->getSourceType() === $source->type) {
Expand All @@ -237,51 +301,7 @@ public function searchEditorAction(): void
), $source->type));
}

if (! $filter) {
$targets = $hook->getRuleFilterTargets($source->id);
if (count($targets) === 1 && ! is_array(reset($targets))) {
$filter = key($targets);
} else {
$target = null;
$form = (new CompatForm())
->applyDefaultElementDecorators()
->setAction(Url::fromRequest()->getAbsoluteUrl())
->addElement('select', 'target', [
'required' => true,
'label' => $this->translate('Filter Target'),
'options' => ['' => ' - ' . $this->translate('Please choose') . ' - '] + $targets,
'disabledOptions' => ['']
])
->addElement('submit', 'btn_submit', [
// translators: shown on a submit button to proceed to the next step of a form wizard
'label' => $this->translate('Next')
])
->on(Form::ON_SUBMIT, function (CompatForm $form) use (&$target) {
$target = $form->getValue('target');
})
->handleRequest($this->getServerRequest());

if ($target !== null) {
$filter = $target;
} else {
$this->addContent($form);
}
}
}

if ($filter) {
$form = $hook->getRuleFilterEditor($filter)
->setAction(Url::fromRequest()->with('object_filter', $filter)->getAbsoluteUrl())
->on(Form::ON_SUBMIT, function (Form $form) use ($ruleId, $hook) {
$this->session->set('object_filter', $hook->serializeRuleFilter($form));
$this->redirectNow(Links::eventRule($ruleId)->setParam('_filterOnly'));
})
->handleRequest($this->getServerRequest());

$this->getDocument()->addHtml($form);
}

$this->setTitle($this->translate('Adjust Filter'));
return $hook;
}

public function editAction(): void
Expand Down Expand Up @@ -338,4 +358,19 @@ private function fetchRule(int $ruleId): Rule

return $rule;
}

private function collectColumns(Filter\Rule $rule): array
{
if ($rule instanceof Filter\Chain) {
$result = [];
foreach ($rule as $element) {
$result = array_merge($result, $this->collectColumns($element));
}

return array_unique($result);
} else {
/** @var $rule Condition */
return [$rule->getColumn()];
}
}
}
4 changes: 2 additions & 2 deletions application/forms/SourceForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
use Icinga\Application\Hook;
use Icinga\Application\Logger;
use Icinga\Exception\Http\HttpNotFoundException;
use Icinga\Module\Notifications\Hook\V1\SourceHook;
use Icinga\Module\Notifications\Hook\V2\SourceHook;
use Icinga\Module\Notifications\Model\Source;
use ipl\Html\Attributes;
use ipl\Html\HtmlDocument;
Expand Down Expand Up @@ -57,7 +57,7 @@ protected function assemble(): void
self::TYPE_GENERIC => $this->translate('Generic')
];

foreach (Hook::all('Notifications/v1/Source') as $hook) {
foreach (Hook::all('Notifications/v2/Source') as $hook) {
/** @var SourceHook $hook */
try {
$type = $hook->getSourceType();
Expand Down
82 changes: 82 additions & 0 deletions library/Notifications/Hook/V2/SourceHook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

// SPDX-FileCopyrightText: 2026 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-3.0-or-later

namespace Icinga\Module\Notifications\Hook\V2;

use ipl\Stdlib\Filter\Chain;
use ipl\Stdlib\Filter\Condition;
use ipl\Web\Widget\Icon;
use Traversable;

interface SourceHook
{
/**
* Get the type of source this integration is responsible for
*
* @return string
*/
public function getSourceType(): string;

/**
* Get the label of the source this integration is responsible for
*
* @return string
*/
public function getSourceLabel(): string;

/**
* Get the icon of the source this integration is responsible for
*
* @return Icon
*/
public function getSourceIcon(): Icon;

/**
* Get whether the condition is valid
*
* @param Condition $condition
*
* @return bool
*/
public function isValidCondition(Condition $condition): bool;

/**
* Enrich the given condition with metadata like the columnLabel
*
* @param Condition $condition
*
* @return void
*/
public function enrichCondition(Condition $condition): void;

/**
* All JsonPaths for all given columns
*
* @param array<string> $columns
*
* @return array<array<string>>
*/
public function getJsonPaths(array $columns): array;

/**
* Get suggestions for a value field
*
* @param string $column
* @param string $searchTerm
* @param Chain $searchFilter
*
* @return Traversable Values to be suggested as `search` => `label`
*/
public function getValueSuggestions(string $column, string $searchTerm, Chain $searchFilter): Traversable;

/**
* Get suggestions for a column field
*
* @param string $searchTerm
*
* @return Traversable Columns to be suggested as `search` => `label`
*/
public function getColumnSuggestions(string $searchTerm): Traversable;
}
4 changes: 2 additions & 2 deletions library/Notifications/Model/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use DateTime;
use Icinga\Application\Hook;
use Icinga\Application\Logger;
use Icinga\Module\Notifications\Hook\V1\SourceHook;
use Icinga\Module\Notifications\Hook\V2\SourceHook;
use ipl\Orm\Behavior\BoolCast;
use ipl\Orm\Behavior\MillisecondTimestamp;
use ipl\Orm\Behaviors;
Expand Down Expand Up @@ -103,7 +103,7 @@ public function getIcon(): Icon
// Fallback, in case an integration is inactive or missing
$icon = new Icon('share-nodes');

foreach (Hook::all('Notifications/v1/Source') as $hook) {
foreach (Hook::all('Notifications/v2/Source') as $hook) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's a way to get rid of this loop and getSourceType() in the interface. Right now there can only be a single hook anyway, and that's where Hook::first() comes into play.

Please try to incorporate the source type in the name of the hook for v2. In case of icinga, that'd be: Notifications/v2/IcingaSource

The hook can then be loaded this way:

$hook = Hook::first(sprintf('Notifications/v2/%sSource', \ipl\Stdlib\Str::camel($this->type));

Please note that this fundamentally changes how sources are configured. This way the available integrations cannot be known beforehand (before an event came in) so the type field must be a free text field. This collides with #450 somewhat, but that's already in progress and based on this anyway.

Once #461 is a thing, the source configuration is mainly for generic sources as well. So it doesn't hurt either.

/** @var SourceHook $hook */
try {
if ($hook->getSourceType() === $this->type) {
Expand Down
Loading
Loading