Browse Source

Merge pull request #16118 from zzzeebra/fix/alarm-duration-schedule-start

Fixed alarm not being created when schedule window opens for rules with duration condition
pull/16663/head
Viacheslav Klimov 3 weeks ago
committed by GitHub
parent
commit
c5b0cbdd01
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 7
      application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
  2. 42
      application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
  3. 130
      application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java

7
application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java

@ -72,10 +72,10 @@ public class AlarmRuleState {
public AlarmEvalResult reeval(long ts, CalculatedFieldCtx ctx) { // on scheduled duration check or periodic re-eval for rules with schedule
boolean active = isActive(ts);
boolean activeChanged = this.active == null || active != this.active;
this.active = active;
switch (condition.getType()) {
case SIMPLE, REPEATING -> {
boolean activeChanged = this.active == null || active != this.active;
this.active = active;
if (!active) {
return AlarmEvalResult.EMPTY;
}
@ -94,6 +94,9 @@ public class AlarmRuleState {
if (!active) {
return AlarmEvalResult.FALSE;
}
if (firstEventTs <= 0 && condition.hasSchedule() && activeChanged) {
return doEval(false, ctx);
}
long requiredDuration = getRequiredDurationInMs();
if (requiredDuration > 0 && firstEventTs > 0 && ts > firstEventTs) {
duration = ts - firstEventTs;

42
application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java

@ -905,6 +905,48 @@ public class AlarmRulesTest extends AbstractControllerTest {
});
}
@Test
public void testCreateAlarm_durationCondition_scheduleStarted() throws Exception {
Argument motionDetectedArgument = new Argument();
motionDetectedArgument.setRefEntityKey(new ReferencedEntityKey("motionDetected", ArgumentType.TS_LATEST, null));
motionDetectedArgument.setDefaultValue("false");
Map<String, Argument> arguments = Map.of(
"motionDetected", motionDetectedArgument
);
SpecificTimeSchedule schedule = new SpecificTimeSchedule();
schedule.setTimezone(ZoneId.systemDefault().getId());
schedule.setDaysOfWeek(Set.of(1, 2, 3, 4, 5, 6, 7));
long startsOn = Duration.between(LocalDate.now().atStartOfDay(), LocalDateTime.now())
.plus(15, ChronoUnit.SECONDS).toMillis();
schedule.setStartsOn(startsOn);
Map<AlarmSeverity, Condition> createRules = Map.of(
AlarmSeverity.CRITICAL, new Condition("return motionDetected == true;", null, null,
new AlarmConditionValue<>(1000L, null),
new AlarmConditionValue<>(schedule, null))
);
AlarmRuleDefinition alarmRule = createAlarmRule(deviceId, "Motion detected alarm",
arguments, createRules, null);
postTelemetry(deviceId, "{\"motionDetected\":true}");
Thread.sleep(10000);
assertThat(getLatestAlarmResult(alarmRule.getId())).isNull();
// no new telemetry after the schedule window opens, so the stored value must be used
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
CalculatedFieldDebugEvent debugEvent = getDebugEvents(alarmRule.getId(), 5).stream()
.filter(event -> event.getResult() != null)
.findFirst().orElse(null);
assertThat(debugEvent).isNotNull();
TbAlarmResult alarmResult = JacksonUtil.fromString(debugEvent.getResult(), TbAlarmResult.class);
assertThat(alarmResult.isCreated()).isTrue();
assertThat(alarmResult.getAlarm().getSeverity()).isEqualTo(AlarmSeverity.CRITICAL);
assertThat(alarmResult.getAlarm().getStatus()).isEqualTo(AlarmStatus.ACTIVE_UNACK);
});
}
@Test
public void testManualClearAlarm() throws Exception {
Argument temperatureArgument = new Argument();

130
application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java

@ -0,0 +1,130 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.cf.ctx.state.alarm;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.thingsboard.server.common.data.alarm.AlarmSeverity;
import org.thingsboard.server.common.data.alarm.rule.AlarmRule;
import org.thingsboard.server.common.data.alarm.rule.condition.AlarmConditionValue;
import org.thingsboard.server.common.data.alarm.rule.condition.DurationAlarmCondition;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.AlarmConditionFilter;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.SimpleAlarmConditionExpression;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.predicate.NumericFilterPredicate;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.predicate.NumericFilterPredicate.NumericOperation;
import org.thingsboard.server.common.data.alarm.rule.condition.schedule.SpecificTimeSchedule;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.kv.DoubleDataEntry;
import org.thingsboard.server.common.data.query.EntityKeyValueType;
import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldCtx;
import org.thingsboard.server.service.cf.ctx.state.SingleValueArgumentEntry;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AlarmRuleStateTest {
private static final DeviceId DEVICE_ID = new DeviceId(UUID.fromString("5512071d-5abc-411d-a907-4cdb6539c2eb"));
// Schedule window: every day from 10:00 to 24:00 UTC
private static final long DAY_START_TS = Instant.parse("2024-01-15T00:00:00Z").toEpochMilli();
private static final long WINDOW_STARTS_ON_MS = TimeUnit.HOURS.toMillis(10);
private static final long TELEMETRY_TS = DAY_START_TS + TimeUnit.HOURS.toMillis(8);
private static final long WINDOW_OPENED_TS = DAY_START_TS + WINDOW_STARTS_ON_MS + TimeUnit.SECONDS.toMillis(1);
private static final long SHORT_DURATION_MS = TimeUnit.MINUTES.toMillis(1);
// AlarmRuleState.evalDuration() measures the duration against the wall clock, so to have a duration
// that has not elapsed yet for a telemetry ts fixed in the past, it has to be far longer than the time since then.
private static final long LONG_DURATION_MS = TimeUnit.DAYS.toMillis(365 * 1000);
private final CalculatedFieldCtx ctx = mock(CalculatedFieldCtx.class);
private AlarmCalculatedFieldState state;
@BeforeEach
void setUp() {
AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration();
configuration.setCreateRules(Map.of());
CalculatedField calculatedField = new CalculatedField();
calculatedField.setName("Test alarm");
calculatedField.setConfiguration(configuration);
when(ctx.getCalculatedField()).thenReturn(calculatedField);
when(ctx.getArgNames()).thenReturn(List.of("temperature"));
state = new AlarmCalculatedFieldState(DEVICE_ID);
state.setCtx(ctx, null);
// stored telemetry that satisfies the condition, received while the schedule window was closed
state.update(Map.of("temperature", new SingleValueArgumentEntry(TELEMETRY_TS, new DoubleDataEntry("temperature", 30.0), 1L)), ctx);
}
@Test
void testReevalDurationWithoutSchedule_doesNotStartTimerFromStoredValue() {
// re-evaluated without a new event because another rule of the same calculated field has a schedule
AlarmRuleState ruleState = createRuleState(SHORT_DURATION_MS, false);
AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx);
assertThat(result.getStatus()).isNull();
assertThat(ruleState.getFirstEventTs()).isZero();
}
@Test
void testReevalDurationWithSchedule_whenWindowOpensAndDurationElapsed_thenTrue() {
AlarmRuleState ruleState = createRuleState(SHORT_DURATION_MS, true);
AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx);
assertThat(result.getStatus()).isEqualTo(AlarmEvalResult.Status.TRUE);
assertThat(ruleState.getFirstEventTs()).isEqualTo(TELEMETRY_TS);
}
@Test
void testReevalDurationWithSchedule_whenWindowOpensAndDurationNotElapsed_thenTimerStarted() {
// leftDuration of the result is what AlarmCalculatedFieldState uses to schedule the next duration check
AlarmRuleState ruleState = createRuleState(LONG_DURATION_MS, true);
AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx);
assertThat(result.getStatus()).isEqualTo(AlarmEvalResult.Status.NOT_YET_TRUE);
assertThat(result.getLeftDuration()).isPositive();
assertThat(ruleState.getFirstEventTs()).isEqualTo(TELEMETRY_TS);
}
private AlarmRuleState createRuleState(long durationMs, boolean withSchedule) {
DurationAlarmCondition condition = new DurationAlarmCondition();
condition.setExpression(createTemperatureGreaterThanExpression(25.0));
condition.setUnit(TimeUnit.MILLISECONDS);
condition.setValue(new AlarmConditionValue<>(durationMs, null));
if (withSchedule) {
SpecificTimeSchedule schedule = new SpecificTimeSchedule();
schedule.setTimezone("UTC");
schedule.setDaysOfWeek(Set.of(1, 2, 3, 4, 5, 6, 7));
schedule.setStartsOn(WINDOW_STARTS_ON_MS);
condition.setSchedule(new AlarmConditionValue<>(schedule, null));
}
AlarmRule rule = new AlarmRule();
rule.setCondition(condition);
return new AlarmRuleState(AlarmSeverity.CRITICAL, rule, state);
}
private SimpleAlarmConditionExpression createTemperatureGreaterThanExpression(double threshold) {
AlarmConditionFilter filter = new AlarmConditionFilter();
filter.setArgument("temperature");
filter.setValueType(EntityKeyValueType.NUMERIC);
filter.setPredicates(List.of(new NumericFilterPredicate(NumericOperation.GREATER, new AlarmConditionValue<>(threshold, null))));
SimpleAlarmConditionExpression expression = new SimpleAlarmConditionExpression();
expression.setFilters(List.of(filter));
return expression;
}
}
Loading…
Cancel
Save