Browse Source

Merge branch 'hotfix-4.4' into lts-4.4

pull/16663/head
Viacheslav Klimov 3 weeks ago
parent
commit
306e26561b
Failed to extract signature
  1. 17
      application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java
  2. 73
      application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java

17
application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java

@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.notification.rule.DefaultNotificationR
import org.thingsboard.server.common.data.notification.rule.NotificationRule;
import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo;
import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerConfig;
import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType;
import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig;
import org.thingsboard.server.common.data.notification.settings.NotificationSettings;
import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
@ -43,14 +44,17 @@ import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.notification.NotificationTemplateService;
import org.thingsboard.server.dao.secret.SecretService;
import org.thingsboard.server.dao.sqlts.insert.sql.SqlPartitioningRepository;
import org.thingsboard.server.service.notification.rule.cache.DefaultNotificationRulesCache;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public abstract class AbstractNotificationApiTest extends AbstractControllerTest {
@ -64,6 +68,8 @@ public abstract class AbstractNotificationApiTest extends AbstractControllerTest
@Autowired
protected NotificationRuleService notificationRuleService;
@Autowired
protected DefaultNotificationRulesCache notificationRulesCache;
@Autowired
protected NotificationTemplateService notificationTemplateService;
@Autowired
protected NotificationTargetService notificationTargetService;
@ -192,7 +198,16 @@ public abstract class AbstractNotificationApiTest extends AbstractControllerTest
}
protected NotificationRule saveNotificationRule(NotificationRule notificationRule) {
return doPost("/api/notification/rule", notificationRule, NotificationRule.class);
NotificationRule savedRule = doPost("/api/notification/rule", notificationRule, NotificationRule.class);
awaitNotificationRulesCacheUpdate(savedRule.getTenantId(), savedRule.getTriggerType());
return savedRule;
}
// saving a rule evicts the rules cache asynchronously
protected void awaitNotificationRulesCacheUpdate(TenantId tenantId, NotificationRuleTriggerType triggerType) {
await().atMost(TIMEOUT, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> Set.copyOf(notificationRulesCache.getEnabled(tenantId, triggerType))
.equals(Set.copyOf(notificationRuleService.findEnabledNotificationRulesByTenantIdAndTriggerType(tenantId, triggerType))));
}
protected PageData<NotificationRuleInfo> findNotificationRules() throws Exception {

73
application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java

@ -13,6 +13,7 @@ import org.mockito.MockedStatic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.data.util.Pair;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.context.TestPropertySource;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.SystemUtil;
@ -54,6 +55,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestInfo;
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.notification.info.AlarmNotificationInfo;
import org.thingsboard.server.common.data.notification.info.RateLimitsNotificationInfo;
import org.thingsboard.server.common.data.notification.info.ResourcesShortageNotificationInfo;
import org.thingsboard.server.common.data.notification.rule.DefaultNotificationRuleRecipientsConfig;
import org.thingsboard.server.common.data.notification.rule.EscalatedNotificationRuleRecipientsConfig;
import org.thingsboard.server.common.data.notification.rule.NotificationRule;
@ -89,12 +91,10 @@ import org.thingsboard.server.dao.notification.NotificationRequestService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.queue.notification.DefaultNotificationDeduplicationService;
import org.thingsboard.server.service.notification.rule.cache.DefaultNotificationRulesCache;
import org.thingsboard.server.service.state.DeviceStateService;
import org.thingsboard.server.service.system.DefaultSystemInfoService;
import org.thingsboard.server.service.telemetry.AlarmSubscriptionService;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -122,7 +122,9 @@ import static org.thingsboard.server.common.data.notification.rule.trigger.confi
@TestPropertySource(properties = {
"transport.http.enabled=true",
"notification_system.rules.deduplication_durations=RATE_LIMITS:10000",
"edges.enabled=true"
"edges.enabled=true",
// the real system info job reports resource shortages only once, at startup
"metrics.system_info.persist_frequency=3600"
})
public class NotificationRuleApiTest extends AbstractNotificationApiTest {
@ -139,8 +141,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
@Autowired
private NotificationRuleProcessor notificationRuleProcessor;
@Autowired
private DefaultNotificationRulesCache notificationRulesCache;
@Autowired
private DeviceStateService deviceStateService;
@Before
@ -271,7 +271,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
Device device = createDevice("Device with alarm", "233");
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
defaultNotifications.create(tenantId, DefaultNotifications.newAlarm, target.getId());
notificationRulesCache.evict(tenantId);
awaitNotificationRulesCacheUpdate(tenantId, NotificationRuleTriggerType.ALARM);
Alarm alarm = new Alarm();
alarm.setSeverity(AlarmSeverity.CRITICAL);
@ -448,7 +448,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededRateLimitsForSysadmin, sysadmins.getId());
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededRateLimits, affectedTenantAdmins.getId());
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededPerEntityRateLimits, affectedTenantAdmins.getId());
notificationRulesCache.evict(TenantId.SYS_TENANT_ID);
awaitNotificationRulesCacheUpdate(TenantId.SYS_TENANT_ID, NotificationRuleTriggerType.RATE_LIMITS);
int n = 10;
updateDefaultTenantProfileConfig(profileConfiguration -> {
@ -787,14 +787,8 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", createNotificationTarget(tenantAdminUserId).getId());
loginTenantAdmin();
// Mock SystemUtil to return 15% memory usage (exceeds 1% threshold)
try (MockedStatic<SystemUtil> mockedSystemUtil = mockStatic(SystemUtil.class)) {
mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(15));
Method method = DefaultSystemInfoService.class.getDeclaredMethod("saveCurrentMonolithSystemInfo");
method.setAccessible(true);
method.invoke(systemInfoService);
}
// 15% RAM exceeds the 1% threshold, CPU and storage stay below 100%
saveMonolithSystemInfo(15);
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1);
Notification notification = getMyNotifications(false, 100).get(0);
@ -813,29 +807,32 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
.build();
createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", sysadmins.getId());
assertThat(getMyNotifications(false, 100)).size().isZero();
// the real system info job reports RAM under this node's service id, so count only this test's
String serviceId = "test-service-" + UUID.randomUUID();
for (int i = 0; i < 10; i++) {
notificationRuleProcessor.process(ResourcesShortageTrigger.builder()
.resource(Resource.RAM)
.usage(15L)
.serviceType("serviceType")
.serviceId("serviceId")
.serviceId(serviceId)
.build());
TimeUnit.MILLISECONDS.sleep(300);
}
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1);
Notification notification = getMyNotifications(false, 100).get(0);
List<Notification> notifications = await().atMost(TIMEOUT, TimeUnit.SECONDS)
.until(() -> getResourcesShortageNotifications(serviceId), list -> list.size() == 1);
Notification notification = notifications.get(0);
assertThat(notification.getSubject()).isEqualTo("Warning: RAM shortage");
assertThat(notification.getText()).isEqualTo("RAM shortage");
// deduplication is 1 minute, no new message is exp
// deduplication is 1 hour, no new message is expected
notificationRuleProcessor.process(ResourcesShortageTrigger.builder()
.resource(Resource.RAM)
.usage(5L)
.serviceType("serviceType")
.serviceId("serviceId")
.serviceId(serviceId)
.build());
await("").atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> assertThat(getMyNotifications(false, 100)).size().isOne());
await().during(3, TimeUnit.SECONDS).atMost(TIMEOUT, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getResourcesShortageNotifications(serviceId)).hasSize(1));
}
@Test
@ -850,16 +847,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
NotificationRule rule = createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", sysadmins.getId());
// Mock SystemUtil to return 15% usages (not exceeds 99% threshold)
Method method;
try (MockedStatic<SystemUtil> mockedSystemUtil = mockStatic(SystemUtil.class)) {
mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(15));
mockedSystemUtil.when(SystemUtil::getCpuUsage).thenReturn(Optional.of(15));
mockedSystemUtil.when(SystemUtil::getDiscSpaceUsage).thenReturn(Optional.of(15));
method = DefaultSystemInfoService.class.getDeclaredMethod("saveCurrentMonolithSystemInfo");
method.setAccessible(true);
method.invoke(systemInfoService);
}
saveMonolithSystemInfo(15);
TimeUnit.SECONDS.sleep(5);
assertThat(getMyNotifications(false, 100)).size().isZero();
@ -872,7 +860,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
rule.setTriggerConfig(triggerConfig);
saveNotificationRule(rule);
method.invoke(systemInfoService);
saveMonolithSystemInfo(15);
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1);
Notification notification = getMyNotifications(false, 100).get(0);
@ -886,7 +874,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE));
triggerConfig.setCreated(true);
NotificationRule rule = createNotificationRule(triggerConfig, "Created", "Created", createNotificationTarget(tenantAdminUserId).getId());
notificationRulesCache.evict(tenantId);
assertThat(getMyNotifications(false, 100)).size().isZero();
createDevice("Device 1", "default", "111");
@ -897,7 +884,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
rule.setEnabled(false);
saveNotificationRule(rule);
notificationRulesCache.evict(tenantId);
createDevice("Device 2", "default", "222");
TimeUnit.SECONDS.sleep(5);
@ -905,7 +891,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
rule.setEnabled(true);
saveNotificationRule(rule);
notificationRulesCache.evict(tenantId);
createDevice("Device 3", "default", "333");
await().atMost(TIMEOUT, TimeUnit.SECONDS)
@ -936,6 +921,22 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
}, (notification, r) -> check.accept(notification));
}
private void saveMonolithSystemInfo(int usagePercent) {
try (MockedStatic<SystemUtil> mockedSystemUtil = mockStatic(SystemUtil.class)) {
mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(usagePercent));
mockedSystemUtil.when(SystemUtil::getCpuUsage).thenReturn(Optional.of(usagePercent));
mockedSystemUtil.when(SystemUtil::getDiscSpaceUsage).thenReturn(Optional.of(usagePercent));
ReflectionTestUtils.invokeMethod(systemInfoService, "saveCurrentMonolithSystemInfo");
}
}
private List<Notification> getResourcesShortageNotifications(String serviceId) throws Exception {
return getMyNotifications(false, 100).stream()
.filter(notification -> notification.getInfo() instanceof ResourcesShortageNotificationInfo info
&& serviceId.equals(info.getServiceId()))
.toList();
}
private PageData<NotificationRequestInfo> findNotificationRequests(EntityType originatorType) {
return notificationRequestService.findNotificationRequestsInfosByTenantIdAndOriginatorType(tenantId, originatorType, new PageLink(100));
}

Loading…
Cancel
Save