Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alert evaluation bugfix + add average selector to alerts #7098

Closed
wants to merge 3 commits into from
Closed
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
2 changes: 1 addition & 1 deletion client/app/components/proptypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const Query = PropTypes.shape({

export const AlertOptions = PropTypes.shape({
column: PropTypes.string,
selector: PropTypes.oneOf(["first", "min", "max"]),
selector: PropTypes.oneOf(["first", "min", "max", "avg"]),
op: PropTypes.oneOf([">", ">=", "<", "<=", "==", "!="]),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
custom_subject: PropTypes.string,
Expand Down
24 changes: 22 additions & 2 deletions client/app/pages/alert/components/Criteria.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ export default function Criteria({ columnNames, resultValues, alertOptions, onCh
return null;
})();

const average = (array) => {
return array.reduce((a, b) => a + b, 0) / array.length;
};

let columnHint;

if (alertOptions.selector === "first") {
Expand All @@ -67,7 +71,9 @@ export default function Criteria({ columnNames, resultValues, alertOptions, onCh
<small className="alert-criteria-hint">
Max column value is{" "}
<code className="p-0">
{toString(Math.max(...resultValues.map((o) => o[alertOptions.column]))) || "unknown"}
{toString(
Math.max(...resultValues.map((o) => Number(o[alertOptions.column])).filter((value) => !isNaN(value)))
) || "unknown"}
</code>
</small>
);
Expand All @@ -76,7 +82,18 @@ export default function Criteria({ columnNames, resultValues, alertOptions, onCh
<small className="alert-criteria-hint">
Min column value is{" "}
<code className="p-0">
{toString(Math.min(...resultValues.map((o) => o[alertOptions.column]))) || "unknown"}
{toString(
Math.min(...resultValues.map((o) => Number(o[alertOptions.column])).filter((value) => !isNaN(value)))
) || "unknown"}
</code>
</small>
);
} else if (alertOptions.selector === "avg") {
columnHint = (
<small className="alert-criteria-hint">
Average column value is{" "}
<code className="p-0">
{toString(average(resultValues.map((o) => Number(o[alertOptions.column])))) || "unknown"}
</code>
</small>
);
Expand All @@ -103,6 +120,9 @@ export default function Criteria({ columnNames, resultValues, alertOptions, onCh
<Select.Option value="max" label="max">
max
</Select.Option>
<Select.Option value="avg" label="avg">
avg
</Select.Option>
</Select>
) : (
<DisabledInput minWidth={60}>{alertOptions.selector}</DisabledInput>
Expand Down
36 changes: 23 additions & 13 deletions redash/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,8 @@ def next_state(op, value, threshold):

if op(value, threshold):
new_state = Alert.TRIGGERED_STATE
elif not value_is_number and op not in [OPERATORS.get("!="), OPERATORS.get("=="), OPERATORS.get("equals")]:
new_state = Alert.UNKNOWN_STATE
else:
new_state = Alert.OK_STATE

Expand Down Expand Up @@ -967,18 +969,27 @@ def evaluate(self):
else:
selector = self.options["selector"]

if selector == "max":
max_val = float("-inf")
for i in range(0, len(data["rows"])):
max_val = max(max_val, data["rows"][i][self.options["column"]])
value = max_val
elif selector == "min":
min_val = float("inf")
for i in range(0, len(data["rows"])):
min_val = min(min_val, data["rows"][i][self.options["column"]])
value = min_val
else:
value = data["rows"][0][self.options["column"]]
try:
if selector == "max":
max_val = float("-inf")
for i in range(len(data["rows"])):
max_val = max(max_val, float(data["rows"][i][self.options["column"]]))
value = max_val
elif selector == "min":
min_val = float("inf")
for i in range(len(data["rows"])):
min_val = min(min_val, float(data["rows"][i][self.options["column"]]))
value = min_val
elif selector == "avg":
total_sum = 0
for i in range(len(data["rows"])):
total_sum += float(data["rows"][i][self.options["column"]])
value = total_sum / len(data["rows"])
else:
value = data["rows"][0][self.options["column"]]

except ValueError:
return self.UNKNOWN_STATE

threshold = self.options["value"]

Expand Down Expand Up @@ -1007,7 +1018,6 @@ def render_template(self, template):
result_table = [] # A two-dimensional array which can rendered as a table in Mustache
for row in data["rows"]:
result_table.append([row[col["name"]] for col in data["columns"]])
print("OPTIONS", self.options)
context = {
"ALERT_NAME": self.name,
"ALERT_URL": "{host}/alerts/{alert_id}".format(host=host, alert_id=self.id),
Expand Down
51 changes: 43 additions & 8 deletions tests/models/test_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,23 +71,58 @@ def test_evaluate_return_unknown_when_empty_results(self):
alert = self.create_alert(results)
self.assertEqual(alert.evaluate(), Alert.UNKNOWN_STATE)

def test_evaluates_correctly_with_max_selector(self):
results = {"rows": [{"foo": 1}, {"foo": 2}], "columns": [{"name": "foo", "type": "STRING"}]}
def test_evaluates_correctly_with_first_selector(self):
results = {"rows": [{"foo": 1}, {"foo": 2}], "columns": [{"name": "foo", "type": "INTEGER"}]}
alert = self.create_alert(results)
alert.options["selector"] = "max"
self.assertEqual(alert.evaluate(), Alert.OK_STATE)
alert.options["selector"] = "first"
self.assertEqual(alert.evaluate(), Alert.TRIGGERED_STATE)
results = {
"rows": [{"foo": "test"}, {"foo": "test"}, {"foo": "test"}],
"columns": [{"name": "foo", "type": "STRING"}],
}
alert = self.create_alert(results)
alert.options["selector"] = "first"
alert.options["op"] = "<"
self.assertEqual(alert.evaluate(), Alert.UNKNOWN_STATE)

def test_evaluates_correctly_with_min_selector(self):
results = {"rows": [{"foo": 2}, {"foo": 1}], "columns": [{"name": "foo", "type": "STRING"}]}
results = {"rows": [{"foo": 2}, {"foo": 1}], "columns": [{"name": "foo", "type": "INTEGER"}]}
alert = self.create_alert(results)
alert.options["selector"] = "min"
self.assertEqual(alert.evaluate(), Alert.TRIGGERED_STATE)
results = {
"rows": [{"foo": "test"}, {"foo": "test"}, {"foo": "test"}],
"columns": [{"name": "foo", "type": "STRING"}],
}
alert = self.create_alert(results)
alert.options["selector"] = "min"
self.assertEqual(alert.evaluate(), Alert.UNKNOWN_STATE)

def test_evaluates_correctly_with_first_selector(self):
results = {"rows": [{"foo": 1}, {"foo": 2}], "columns": [{"name": "foo", "type": "STRING"}]}
def test_evaluates_correctly_with_max_selector(self):
results = {"rows": [{"foo": 1}, {"foo": 2}], "columns": [{"name": "foo", "type": "INTEGER"}]}
alert = self.create_alert(results)
alert.options["selector"] = "first"
alert.options["selector"] = "max"
self.assertEqual(alert.evaluate(), Alert.OK_STATE)
results = {
"rows": [{"foo": "test"}, {"foo": "test"}, {"foo": "test"}],
"columns": [{"name": "foo", "type": "STRING"}],
}
alert = self.create_alert(results)
alert.options["selector"] = "max"
self.assertEqual(alert.evaluate(), Alert.UNKNOWN_STATE)

def test_evaluates_correctly_with_avg_selector(self):
results = {"rows": [{"foo": 0}, {"foo": 1}, {"foo": 2}], "columns": [{"name": "foo", "type": "INTEGER"}]}
alert = self.create_alert(results)
alert.options["selector"] = "avg"
self.assertEqual(alert.evaluate(), Alert.TRIGGERED_STATE)
results = {
"rows": [{"foo": "test"}, {"foo": "test"}, {"foo": "test"}],
"columns": [{"name": "foo", "type": "STRING"}],
}
alert = self.create_alert(results)
alert.options["selector"] = "avg"
self.assertEqual(alert.evaluate(), Alert.UNKNOWN_STATE)


class TestNextState(TestCase):
Expand Down
Loading