Browse Source
# Conflicts: # application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.javapull/16304/head
236 changed files with 20640 additions and 9237 deletions
@ -0,0 +1,78 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge; |
|||
|
|||
import lombok.RequiredArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.common.data.HasTenantId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.entity.EntityDaoRegistry; |
|||
import org.thingsboard.server.dao.entity.EntityService; |
|||
import org.thingsboard.server.exception.DataValidationException; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
/** |
|||
* Checks that entities referenced by edge messages belong to the edge's tenant. |
|||
*/ |
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class EdgeEntityTenantChecker { |
|||
|
|||
private final EntityService entityService; |
|||
private final EntityDaoRegistry entityDaoRegistry; |
|||
|
|||
/** |
|||
* Returns true if the entity exists and belongs to the tenant. |
|||
* Uses the entity services, so cached and tenant-scoped lookups are used where available. |
|||
*/ |
|||
public boolean isTenantEntity(TenantId tenantId, EntityId entityId) { |
|||
if (entityId == null) { |
|||
return false; |
|||
} |
|||
try { |
|||
return entityService.fetchEntity(tenantId, entityId) |
|||
.map(entity -> entity instanceof HasTenantId hasTenantId && tenantId.equals(hasTenantId.getTenantId())) |
|||
.orElse(false); |
|||
} catch (IllegalArgumentException e) { |
|||
log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* Loads the entity regardless of its tenant, so that an id of another tenant's entity is detected. |
|||
* Returns null if the entity doesn't exist, throws if it belongs to a different tenant. |
|||
*/ |
|||
@SuppressWarnings("unchecked") |
|||
public <T> T findTenantEntity(TenantId tenantId, EntityId entityId) { |
|||
Object entity = findEntity(tenantId, entityId); |
|||
if (entity instanceof HasTenantId hasTenantId && !tenantId.equals(hasTenantId.getTenantId())) { |
|||
throw new DataValidationException(entityId.getEntityType() + " " + entityId.getId() + " belongs to a different tenant!"); |
|||
} |
|||
return (T) entity; |
|||
} |
|||
|
|||
/** |
|||
* Returns the tenant of the entity regardless of the given tenant, or null if the entity doesn't exist. |
|||
*/ |
|||
public TenantId findEntityTenantId(TenantId tenantId, EntityId entityId) { |
|||
return findEntity(tenantId, entityId) instanceof HasTenantId hasTenantId ? hasTenantId.getTenantId() : null; |
|||
} |
|||
|
|||
private Object findEntity(TenantId tenantId, EntityId entityId) { |
|||
if (entityId == null) { |
|||
return null; |
|||
} |
|||
try { |
|||
return entityDaoRegistry.getDao(entityId.getEntityType()).findById(tenantId, entityId.getId()); |
|||
} catch (IllegalArgumentException e) { |
|||
log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge; |
|||
|
|||
import com.google.protobuf.Descriptors.FieldDescriptor; |
|||
import com.google.protobuf.Message; |
|||
|
|||
import java.util.Collection; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.StringJoiner; |
|||
import java.util.UUID; |
|||
import java.util.stream.Collectors; |
|||
|
|||
/** |
|||
* Describes edge protobuf messages without their payloads, so they can be logged or put into notifications |
|||
* without exposing entity JSON, credentials, tokens or secrets. |
|||
*/ |
|||
public final class EdgeMsgSummaryUtils { |
|||
|
|||
private static final String MSB = "MSB"; |
|||
private static final String LSB = "LSB"; |
|||
|
|||
private EdgeMsgSummaryUtils() { |
|||
} |
|||
|
|||
// e.g. DownlinkMsg[downlinkMsgId=12, deviceUpdateMsg x2, deviceCredentialsUpdateMsg x1]
|
|||
// e.g. DeviceUpdateMsg[msgType=ENTITY_UPDATED_RPC_MESSAGE, id=1d6f1e2c-...]
|
|||
public static String toSummary(Message msg) { |
|||
if (msg == null) { |
|||
return "null"; |
|||
} |
|||
Map<FieldDescriptor, Object> fields = msg.getAllFields(); |
|||
StringJoiner summary = new StringJoiner(", ", msg.getDescriptorForType().getName() + "[", "]"); |
|||
fields.forEach((field, value) -> { |
|||
String name = field.getName(); |
|||
if (field.isRepeated()) { |
|||
summary.add(name + " x" + ((List<?>) value).size()); |
|||
return; |
|||
} |
|||
switch (field.getJavaType()) { |
|||
case INT, LONG -> { |
|||
FieldDescriptor lsbField = name.endsWith(MSB) ? findPairField(msg, name, MSB, LSB) : null; |
|||
if (lsbField != null && value instanceof Long msb && msg.getField(lsbField) instanceof Long lsb) { |
|||
summary.add(name.substring(0, name.length() - MSB.length()) + "=" + new UUID(msb, lsb)); |
|||
} else if (!isPrintedWithPair(msg, fields, name)) { |
|||
summary.add(name + "=" + value); |
|||
} |
|||
} |
|||
case BOOLEAN, ENUM -> summary.add(name + "=" + value); |
|||
case MESSAGE -> summary.add(name); |
|||
// strings and bytes may hold entity JSON, credentials or secrets
|
|||
default -> { |
|||
} |
|||
} |
|||
}); |
|||
return summary.toString(); |
|||
} |
|||
|
|||
// LSB part of an id is printed together with its MSB part
|
|||
private static boolean isPrintedWithPair(Message msg, Map<FieldDescriptor, Object> fields, String name) { |
|||
if (!name.endsWith(LSB)) { |
|||
return false; |
|||
} |
|||
FieldDescriptor msbField = findPairField(msg, name, LSB, MSB); |
|||
return msbField != null && fields.containsKey(msbField); |
|||
} |
|||
|
|||
private static FieldDescriptor findPairField(Message msg, String name, String suffix, String pairSuffix) { |
|||
return msg.getDescriptorForType().findFieldByName(name.substring(0, name.length() - suffix.length()) + pairSuffix); |
|||
} |
|||
|
|||
public static String toSummary(Collection<? extends Message> msgs) { |
|||
return msgs.stream().map(EdgeMsgSummaryUtils::toSummary).collect(Collectors.joining(", ", "[", "]")); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,67 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.mail; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonInclude; |
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.rule.engine.api.TbEmail; |
|||
import org.thingsboard.server.common.data.ApiFeature; |
|||
import org.thingsboard.server.common.data.ApiUsageRecordState; |
|||
import org.thingsboard.server.common.data.ApiUsageStateValue; |
|||
|
|||
/** |
|||
* Describes a mail send that the Edge delegates to the Cloud. On the Edge, a mail send that depends |
|||
* on admin-configured (tenant/system) mail settings is packaged into this request and enqueued as a |
|||
* SEND_EMAIL cloud event. On the Cloud, {@code method} selects the matching {@code MailService} call |
|||
* so the Cloud resolves the config, renders the template and transmits via its own SMTP. |
|||
*/ |
|||
@Data |
|||
@Builder |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@JsonInclude(JsonInclude.Include.NON_NULL) |
|||
public class EdgeMailRequest { |
|||
|
|||
public enum MailMethod { |
|||
SEND_BASIC, // sendEmail(to, subject, message)
|
|||
SEND_TB_EMAIL, // send(TbEmail)
|
|||
ACTIVATION, // sendActivationEmail(activationLink, ttlMs, to)
|
|||
ACCOUNT_ACTIVATED, // sendAccountActivatedEmail(loginLink, to)
|
|||
RESET_PASSWORD, // sendResetPasswordEmail(passwordResetLink, ttlMs, to)
|
|||
PASSWORD_WAS_RESET,// sendPasswordWasResetEmail(loginLink, to)
|
|||
TWO_FA, // sendTwoFaVerificationEmail(to, verificationCode, expirationTimeSeconds)
|
|||
ACCOUNT_LOCKOUT, // sendAccountLockoutEmail(lockoutEmail, to, maxFailedLoginAttempts)
|
|||
API_USAGE_STATE, // sendApiFeatureStateEmail(apiFeature, stateValue, to, recordState)
|
|||
TEST_MAIL // sendTestMail(config, to)
|
|||
} |
|||
|
|||
private MailMethod method; |
|||
|
|||
private String to; |
|||
private String subject; |
|||
private String message; |
|||
|
|||
private TbEmail tbEmail; |
|||
|
|||
private String activationLink; |
|||
private String loginLink; |
|||
private String passwordResetLink; |
|||
private Long ttlMs; |
|||
|
|||
private String verificationCode; |
|||
private Integer expirationTimeSeconds; |
|||
|
|||
private String lockoutEmail; |
|||
private Integer maxFailedLoginAttempts; |
|||
|
|||
private ApiFeature apiFeature; |
|||
private ApiUsageStateValue stateValue; |
|||
private ApiUsageRecordState recordState; |
|||
|
|||
private JsonNode testConfig; |
|||
|
|||
} |
|||
@ -0,0 +1,63 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.notification; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonInclude; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
|
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
|
|||
/** |
|||
* Describes a notification delivery that the Edge delegates to the Cloud, for channels whose credentials |
|||
* live only on the Cloud (they are stored in the {@code notifications} admin settings that no longer sync |
|||
* to the Edge). {@code method} selects the channel: |
|||
* <ul> |
|||
* <li>{@code SEND_SLACK} - the Cloud resolves the Slack bot token and posts {@code message} (plus any |
|||
* {@code files}) to {@code conversationId}. The whole send is delegated.</li> |
|||
* <li>{@code SEND_MOBILE_PUSH} - the Edge keeps the notification record, device-token lookup and unread |
|||
* count locally and delegates only the FCM push: the Cloud resolves the Firebase credentials and pushes |
|||
* the already-built payload ({@code subject}/{@code body}/{@code data}/{@code badge}) to every |
|||
* {@code fcmToken}.</li> |
|||
* </ul> |
|||
*/ |
|||
@Data |
|||
@Builder |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@JsonInclude(JsonInclude.Include.NON_NULL) |
|||
public class EdgeNotificationRequest { |
|||
|
|||
public enum NotificationMethod { |
|||
SEND_SLACK, |
|||
SEND_MOBILE_PUSH |
|||
} |
|||
|
|||
private NotificationMethod method; |
|||
|
|||
// SEND_SLACK
|
|||
private String conversationId; |
|||
private String message; |
|||
private List<SlackFileData> files; |
|||
|
|||
// SEND_MOBILE_PUSH
|
|||
private Set<String> fcmTokens; |
|||
private String subject; |
|||
private String body; |
|||
private Map<String, String> data; |
|||
private Integer badge; |
|||
|
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public static class SlackFileData { |
|||
private String name; |
|||
private String type; |
|||
private byte[] data; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,38 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.sms; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonInclude; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.sms.config.TestSmsRequest; |
|||
|
|||
/** |
|||
* Describes an SMS send that the Edge delegates to the Cloud. On the Edge, a send that depends on |
|||
* admin-configured (tenant/system) SMS provider settings cannot be resolved locally, so the call is |
|||
* packaged into this request and enqueued as a SEND_SMS cloud event; on the Cloud, {@code method} |
|||
* selects the matching {@code SmsService} call so the Cloud resolves the config and transmits via its |
|||
* own provider. |
|||
*/ |
|||
@Data |
|||
@Builder |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@JsonInclude(JsonInclude.Include.NON_NULL) |
|||
public class EdgeSmsRequest { |
|||
|
|||
public enum SmsMethod { |
|||
SEND_SMS, // sendSms(customerId, numbersTo, message)
|
|||
SEND_TEST_SMS // sendTestSms(testSmsRequest)
|
|||
} |
|||
|
|||
private SmsMethod method; |
|||
|
|||
private String[] numbers; |
|||
private String message; |
|||
|
|||
private TestSmsRequest testSmsRequest; |
|||
|
|||
} |
|||
@ -1,66 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import com.google.protobuf.AbstractMessage; |
|||
import org.junit.Assert; |
|||
import org.junit.Test; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.AdminSettings; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsService; |
|||
import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; |
|||
|
|||
@DaoSqlTest |
|||
public class AdminSettingsEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@Autowired |
|||
private AdminSettingsService adminSettingsService; |
|||
|
|||
@Test |
|||
public void testAdminSettings() throws Exception { |
|||
loginSysAdmin(); |
|||
|
|||
// save
|
|||
AdminSettings adminSettings = new AdminSettings(); |
|||
adminSettings.setKey("edgeTest"); |
|||
ObjectNode jsonValue = JacksonUtil.newObjectNode(); |
|||
jsonValue.put("key1", "value1"); |
|||
adminSettings.setJsonValue(jsonValue); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
AdminSettings savedAdminSettings = doPost("/api/admin/settings", adminSettings, AdminSettings.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
AbstractMessage latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); |
|||
AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; |
|||
AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); |
|||
Assert.assertNotNull(adminSettingsMsg); |
|||
Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); |
|||
Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); |
|||
|
|||
// update
|
|||
ObjectNode updatedJsonValue = (ObjectNode) savedAdminSettings.getJsonValue(); |
|||
updatedJsonValue.put("key2", "value2"); |
|||
savedAdminSettings.setJsonValue(updatedJsonValue); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
doPost("/api/admin/settings", savedAdminSettings, AdminSettings.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); |
|||
adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; |
|||
adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); |
|||
Assert.assertNotNull(adminSettingsMsg); |
|||
Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); |
|||
Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); |
|||
Assert.assertEquals("value2", adminSettingsMsg.getJsonValue().get("key2").asText()); |
|||
|
|||
adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedAdminSettings.getTenantId(), "edgeTest"); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,197 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import org.junit.Test; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.MailService; |
|||
import org.thingsboard.rule.engine.api.TbEmail; |
|||
import org.thingsboard.server.common.data.ApiFeature; |
|||
import org.thingsboard.server.common.data.ApiUsageStateValue; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; |
|||
import org.thingsboard.server.service.mail.EdgeMailRequest; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.ArgumentMatchers.isNull; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
/** |
|||
* Verifies the send-email uplink: when the Edge delegates a mail send, the Cloud receives the |
|||
* SendEmailUplinkMsg and invokes its MailService (which resolves the config, renders and transmits). Here |
|||
* the EdgeImitator plays the Edge and sends the uplink; the Cloud's MailService is mocked so we can assert |
|||
* the delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of |
|||
* the connected edge). |
|||
*/ |
|||
@DaoSqlTest |
|||
public class SendEmailEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@MockitoBean |
|||
private MailService mailService; |
|||
|
|||
@Test |
|||
public void testSendBasicEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.SEND_BASIC) |
|||
.to("recipient@thingsboard.io") |
|||
.subject("Edge test subject") |
|||
.message("<b>Edge test body</b>") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("Edge test subject"), eq("<b>Edge test body</b>")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTbEmailFromEdgeProcessedByCloud() throws Exception { |
|||
TbEmail tbEmail = TbEmail.builder() |
|||
.from("noreply@thingsboard.io") |
|||
.to("recipient@thingsboard.io") |
|||
.subject("Rule chain email") |
|||
.body("Alarm!") |
|||
.html(false) |
|||
.build(); |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.SEND_TB_EMAIL) |
|||
.tbEmail(tbEmail) |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)).send(eq(tenantId), isNull(), any(TbEmail.class)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendActivationEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.ACTIVATION) |
|||
.activationLink("http://localhost/activate?token=abc") |
|||
.ttlMs(60000L) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendActivationEmail(eq("http://localhost/activate?token=abc"), eq(60000L), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendAccountActivatedEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.ACCOUNT_ACTIVATED) |
|||
.loginLink("http://localhost/login") |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendAccountActivatedEmail(eq("http://localhost/login"), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendResetPasswordEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.RESET_PASSWORD) |
|||
.passwordResetLink("http://localhost/reset?token=abc") |
|||
.ttlMs(60000L) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendResetPasswordEmail(eq("http://localhost/reset?token=abc"), eq(60000L), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendPasswordWasResetEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.PASSWORD_WAS_RESET) |
|||
.loginLink("http://localhost/login") |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendPasswordWasResetEmail(eq("http://localhost/login"), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTwoFaVerificationEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.TWO_FA) |
|||
.to("recipient@thingsboard.io") |
|||
.verificationCode("123456") |
|||
.expirationTimeSeconds(120) |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendTwoFaVerificationEmail(eq("recipient@thingsboard.io"), eq("123456"), eq(120)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendAccountLockoutEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.ACCOUNT_LOCKOUT) |
|||
.lockoutEmail("locked@thingsboard.io") |
|||
.to("recipient@thingsboard.io") |
|||
.maxFailedLoginAttempts(5) |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendAccountLockoutEmail(eq("locked@thingsboard.io"), eq("recipient@thingsboard.io"), eq(5)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendApiUsageStateEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.API_USAGE_STATE) |
|||
.apiFeature(ApiFeature.EMAIL) |
|||
.stateValue(ApiUsageStateValue.DISABLED) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendApiFeatureStateEmail(eq(ApiFeature.EMAIL), eq(ApiUsageStateValue.DISABLED), eq("recipient@thingsboard.io"), isNull()); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTestMailFromEdgeProcessedByCloud() throws Exception { |
|||
JsonNode testConfig = JacksonUtil.newObjectNode().put("smtpHost", "localhost"); |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.TEST_MAIL) |
|||
.testConfig(testConfig) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendTestMail(any(JsonNode.class), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
private void sendEmailUplink(EdgeMailRequest request) throws Exception { |
|||
SendEmailUplinkMsg sendEmailUplinkMsg = SendEmailUplinkMsg.newBuilder() |
|||
.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) |
|||
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) |
|||
.setRequest(JacksonUtil.toString(request)) |
|||
.build(); |
|||
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendEmailUplinkMsg(sendEmailUplinkMsg)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,112 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import org.junit.Test; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.notification.FirebaseService; |
|||
import org.thingsboard.rule.engine.api.notification.SlackService; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; |
|||
import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; |
|||
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.settings.SlackNotificationDeliveryMethodConfig; |
|||
import org.thingsboard.server.dao.notification.NotificationSettingsService; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; |
|||
import org.thingsboard.server.service.notification.EdgeNotificationRequest; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.anyString; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
/** |
|||
* Verifies the send-notification uplink: when the Edge delegates a Slack or mobile-push notification, the |
|||
* Cloud receives the SendNotificationUplinkMsg, resolves the channel credentials from its own notification |
|||
* settings and delivers. The EdgeImitator plays the Edge and sends the uplink; the Cloud's SlackService and |
|||
* FirebaseService are mocked so we can assert the delegated call arrives with the expected arguments. |
|||
*/ |
|||
@DaoSqlTest |
|||
public class SendNotificationEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@MockitoBean |
|||
private SlackService slackService; |
|||
|
|||
@MockitoBean |
|||
private FirebaseService firebaseService; |
|||
|
|||
@Autowired |
|||
private NotificationSettingsService notificationSettingsService; |
|||
|
|||
private void prepareNotificationSettings() { |
|||
// Slack is configured at tenant level.
|
|||
SlackNotificationDeliveryMethodConfig slack = new SlackNotificationDeliveryMethodConfig(); |
|||
slack.setBotToken("xoxb-edge-test-token"); |
|||
NotificationSettings tenantSettings = new NotificationSettings(); |
|||
Map<NotificationDeliveryMethod, NotificationDeliveryMethodConfig> tenantConfigs = new HashMap<>(); |
|||
tenantConfigs.put(NotificationDeliveryMethod.SLACK, slack); |
|||
tenantSettings.setDeliveryMethodsConfigs(tenantConfigs); |
|||
notificationSettingsService.saveNotificationSettings(tenantId, tenantSettings); |
|||
|
|||
// Mobile app credentials can only be configured at system level.
|
|||
MobileAppNotificationDeliveryMethodConfig mobile = new MobileAppNotificationDeliveryMethodConfig(); |
|||
mobile.setFirebaseServiceAccountCredentials("{\"type\":\"service_account\"}"); |
|||
NotificationSettings systemSettings = new NotificationSettings(); |
|||
Map<NotificationDeliveryMethod, NotificationDeliveryMethodConfig> systemConfigs = new HashMap<>(); |
|||
systemConfigs.put(NotificationDeliveryMethod.MOBILE_APP, mobile); |
|||
systemSettings.setDeliveryMethodsConfigs(systemConfigs); |
|||
notificationSettingsService.saveNotificationSettings(TenantId.SYS_TENANT_ID, systemSettings); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendSlackNotificationFromEdgeProcessedByCloud() throws Exception { |
|||
prepareNotificationSettings(); |
|||
EdgeNotificationRequest request = EdgeNotificationRequest.builder() |
|||
.method(EdgeNotificationRequest.NotificationMethod.SEND_SLACK) |
|||
.conversationId("C0123456789") |
|||
.message("Edge Slack notification") |
|||
.build(); |
|||
|
|||
sendNotificationUplink(request); |
|||
|
|||
verify(slackService, timeout(30000)) |
|||
.sendMessage(eq(tenantId), anyString(), eq("C0123456789"), eq("Edge Slack notification")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendMobilePushFromEdgeProcessedByCloud() throws Exception { |
|||
prepareNotificationSettings(); |
|||
EdgeNotificationRequest request = EdgeNotificationRequest.builder() |
|||
.method(EdgeNotificationRequest.NotificationMethod.SEND_MOBILE_PUSH) |
|||
.fcmTokens(Set.of("fcm-token-1")) |
|||
.subject("Edge subject") |
|||
.body("Edge body") |
|||
.badge(3) |
|||
.build(); |
|||
|
|||
sendNotificationUplink(request); |
|||
|
|||
verify(firebaseService, timeout(30000)) |
|||
.sendMessage(eq(tenantId), anyString(), eq("fcm-token-1"), eq("Edge subject"), eq("Edge body"), any(), eq(3)); |
|||
} |
|||
|
|||
private void sendNotificationUplink(EdgeNotificationRequest request) throws Exception { |
|||
SendNotificationUplinkMsg sendNotificationUplinkMsg = SendNotificationUplinkMsg.newBuilder() |
|||
.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) |
|||
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) |
|||
.setRequest(JacksonUtil.toString(request)) |
|||
.build(); |
|||
|
|||
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import org.junit.Test; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.SmsService; |
|||
import org.thingsboard.server.common.data.sms.config.TestSmsRequest; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; |
|||
import org.thingsboard.server.service.sms.EdgeSmsRequest; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.ArgumentMatchers.isNull; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
/** |
|||
* Verifies the send-sms uplink: when the Edge delegates an SMS send, the Cloud receives the |
|||
* SendSmsUplinkMsg and invokes its SmsService (which resolves the config and transmits). Here the |
|||
* EdgeImitator plays the Edge and sends the uplink; the Cloud's SmsService is mocked so we can assert the |
|||
* delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of the |
|||
* connected edge). |
|||
*/ |
|||
@DaoSqlTest |
|||
public class SendSmsEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@MockitoBean |
|||
private SmsService smsService; |
|||
|
|||
@Test |
|||
public void testSendSmsFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeSmsRequest request = EdgeSmsRequest.builder() |
|||
.method(EdgeSmsRequest.SmsMethod.SEND_SMS) |
|||
.numbers(new String[]{"+15551234567"}) |
|||
.message("Edge test message") |
|||
.build(); |
|||
|
|||
sendSmsUplink(request); |
|||
|
|||
verify(smsService, timeout(30000)) |
|||
.sendSms(eq(tenantId), isNull(), any(String[].class), eq("Edge test message")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTestSmsFromEdgeProcessedByCloud() throws Exception { |
|||
TestSmsRequest testSmsRequest = new TestSmsRequest(); |
|||
testSmsRequest.setNumberTo("+15551234567"); |
|||
testSmsRequest.setMessage("Test message"); |
|||
EdgeSmsRequest request = EdgeSmsRequest.builder() |
|||
.method(EdgeSmsRequest.SmsMethod.SEND_TEST_SMS) |
|||
.testSmsRequest(testSmsRequest) |
|||
.build(); |
|||
|
|||
sendSmsUplink(request); |
|||
|
|||
verify(smsService, timeout(30000)).sendTestSms(any(TestSmsRequest.class)); |
|||
} |
|||
|
|||
private void sendSmsUplink(EdgeSmsRequest request) throws Exception { |
|||
SendSmsUplinkMsg sendSmsUplinkMsg = SendSmsUplinkMsg.newBuilder() |
|||
.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) |
|||
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) |
|||
.setRequest(JacksonUtil.toString(request)) |
|||
.build(); |
|||
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendSmsUplinkMsg(sendSmsUplinkMsg)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,99 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.cf; |
|||
|
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.ArgumentCaptor; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.TimeseriesSaveRequest; |
|||
import org.thingsboard.server.cluster.TbClusterService; |
|||
import org.thingsboard.server.common.data.cf.configuration.OutputType; |
|||
import org.thingsboard.server.common.data.cf.configuration.TimeSeriesImmediateOutputStrategy; |
|||
import org.thingsboard.server.common.data.id.DeviceId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.msg.queue.TbCallback; |
|||
import org.thingsboard.server.dao.attributes.AttributesService; |
|||
import org.thingsboard.server.dao.relation.RelationService; |
|||
import org.thingsboard.server.dao.timeseries.TimeseriesService; |
|||
import org.thingsboard.server.dao.usagerecord.ApiLimitService; |
|||
import org.thingsboard.server.queue.discovery.PartitionService; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.Collections; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.TimeUnit; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
public class DefaultCalculatedFieldProcessingServiceTest { |
|||
|
|||
private final TenantId tenantId = TenantId.fromUUID(UUID.fromString("e7f46b23-0c7d-42f5-9b06-fc35ab17af8a")); |
|||
private final DeviceId deviceId = new DeviceId(UUID.fromString("ccd71696-0586-422d-940e-755a41ec3b0d")); |
|||
|
|||
@Mock |
|||
private AttributesService attributesService; |
|||
@Mock |
|||
private TimeseriesService timeseriesService; |
|||
@Mock |
|||
private ApiLimitService apiLimitService; |
|||
@Mock |
|||
private RelationService relationService; |
|||
@Mock |
|||
private OwnerService ownerService; |
|||
@Mock |
|||
private TbClusterService clusterService; |
|||
@Mock |
|||
private TelemetrySubscriptionService tsSubService; |
|||
@Mock |
|||
private PartitionService partitionService; |
|||
|
|||
private DefaultCalculatedFieldProcessingService service; |
|||
|
|||
@BeforeEach |
|||
public void setUp() { |
|||
service = new DefaultCalculatedFieldProcessingService(attributesService, timeseriesService, apiLimitService, |
|||
relationService, ownerService, clusterService, tsSubService, partitionService); |
|||
} |
|||
|
|||
@Test |
|||
public void givenTimeSeriesOutputWithoutTtl_whenProcessResult_thenTenantProfileDefaultStorageTtlIsUsed() { |
|||
when(apiLimitService.getLimit(eq(tenantId), any())).thenReturn(30L); |
|||
|
|||
service.processResult(tenantId, deviceId, "cf", buildTimeSeriesResult(0L), Collections.emptyList(), TbCallback.EMPTY); |
|||
|
|||
assertThat(captureSaveRequest().getTtl()).isEqualTo(TimeUnit.DAYS.toSeconds(30)); |
|||
} |
|||
|
|||
@Test |
|||
public void givenTimeSeriesOutputWithCustomTtl_whenProcessResult_thenCustomTtlIsUsed() { |
|||
service.processResult(tenantId, deviceId, "cf", buildTimeSeriesResult(3600L), Collections.emptyList(), TbCallback.EMPTY); |
|||
|
|||
assertThat(captureSaveRequest().getTtl()).isEqualTo(3600L); |
|||
verify(apiLimitService, never()).getLimit(any(), any()); |
|||
} |
|||
|
|||
private TelemetryCalculatedFieldResult buildTimeSeriesResult(long ttl) { |
|||
return TelemetryCalculatedFieldResult.builder() |
|||
.type(OutputType.TIME_SERIES) |
|||
.outputStrategy(new TimeSeriesImmediateOutputStrategy(ttl, true, true, true, true)) |
|||
.result(JacksonUtil.newObjectNode().put("result", 42)) |
|||
.build(); |
|||
} |
|||
|
|||
private TimeseriesSaveRequest captureSaveRequest() { |
|||
ArgumentCaptor<TimeseriesSaveRequest> captor = ArgumentCaptor.forClass(TimeseriesSaveRequest.class); |
|||
verify(tsSubService).saveTimeseries(captor.capture()); |
|||
return captor.getValue(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,62 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge; |
|||
|
|||
import org.junit.jupiter.api.Assertions; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.thingsboard.server.gen.edge.v1.DeviceCredentialsUpdateMsg; |
|||
import org.thingsboard.server.gen.edge.v1.DeviceUpdateMsg; |
|||
import org.thingsboard.server.gen.edge.v1.DownlinkMsg; |
|||
import org.thingsboard.server.gen.edge.v1.UpdateMsgType; |
|||
import org.thingsboard.server.gen.edge.v1.UplinkMsg; |
|||
|
|||
import java.util.List; |
|||
import java.util.UUID; |
|||
|
|||
public class EdgeMsgSummaryUtilsTest { |
|||
|
|||
private static final String SECRET = "secret-access-token"; |
|||
|
|||
@Test |
|||
public void testDownlinkMsgSummaryHasNoPayload() { |
|||
DownlinkMsg downlinkMsg = DownlinkMsg.newBuilder() |
|||
.setDownlinkMsgId(12) |
|||
.addDeviceUpdateMsg(DeviceUpdateMsg.newBuilder().setEntity("{\"name\":\"Device\"}").build()) |
|||
.addDeviceUpdateMsg(DeviceUpdateMsg.newBuilder().setEntity("{\"name\":\"Device 2\"}").build()) |
|||
.addDeviceCredentialsUpdateMsg(DeviceCredentialsUpdateMsg.newBuilder().setEntity("{\"credentialsId\":\"" + SECRET + "\"}").build()) |
|||
.build(); |
|||
|
|||
String summary = EdgeMsgSummaryUtils.toSummary(downlinkMsg); |
|||
|
|||
Assertions.assertEquals("DownlinkMsg[downlinkMsgId=12, deviceUpdateMsg x2, deviceCredentialsUpdateMsg x1]", summary); |
|||
} |
|||
|
|||
@Test |
|||
public void testUplinkMsgsSummaryHasNoPayload() { |
|||
UplinkMsg uplinkMsg = UplinkMsg.newBuilder() |
|||
.setUplinkMsgId(3) |
|||
.addDeviceCredentialsUpdateMsg(DeviceCredentialsUpdateMsg.newBuilder().setEntity("{\"credentialsId\":\"" + SECRET + "\"}").build()) |
|||
.build(); |
|||
|
|||
String summary = EdgeMsgSummaryUtils.toSummary(List.of(uplinkMsg, uplinkMsg)); |
|||
|
|||
Assertions.assertEquals("[UplinkMsg[uplinkMsgId=3, deviceCredentialsUpdateMsg x1], UplinkMsg[uplinkMsgId=3, deviceCredentialsUpdateMsg x1]]", summary); |
|||
Assertions.assertFalse(summary.contains(SECRET)); |
|||
} |
|||
|
|||
@Test |
|||
public void testEntityMsgSummaryHasTypeAndIdWithoutPayload() { |
|||
UUID deviceUuid = UUID.randomUUID(); |
|||
DeviceUpdateMsg deviceUpdateMsg = DeviceUpdateMsg.newBuilder() |
|||
.setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE) |
|||
.setIdMSB(deviceUuid.getMostSignificantBits()) |
|||
.setIdLSB(deviceUuid.getLeastSignificantBits()) |
|||
.setEntity("{\"name\":\"" + SECRET + "\"}") |
|||
.build(); |
|||
|
|||
String summary = EdgeMsgSummaryUtils.toSummary(deviceUpdateMsg); |
|||
|
|||
Assertions.assertEquals("DeviceUpdateMsg[msgType=ENTITY_UPDATED_RPC_MESSAGE, id=" + deviceUuid + "]", summary); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,325 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge.rpc; |
|||
|
|||
import com.google.common.util.concurrent.Futures; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; |
|||
import org.thingsboard.server.cache.TbTransactionalCache; |
|||
import org.thingsboard.server.cluster.TbClusterService; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; |
|||
import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; |
|||
import org.thingsboard.server.queue.TbQueueConsumer; |
|||
import org.thingsboard.server.queue.common.TbProtoQueueMsg; |
|||
import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; |
|||
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; |
|||
import org.thingsboard.server.service.edge.EdgeContextComponent; |
|||
import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.ConcurrentMap; |
|||
import java.util.concurrent.Executors; |
|||
import java.util.concurrent.ScheduledExecutorService; |
|||
import java.util.concurrent.ScheduledFuture; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.doAnswer; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
/** |
|||
* Covers the reconnect race between a session that is being torn down and the session that has already |
|||
* taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new |
|||
* events flag of the session that replaced it. |
|||
*/ |
|||
class EdgeGrpcServiceReconnectTest { |
|||
|
|||
// long enough that an armed check never actually fires during a test
|
|||
private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L; |
|||
private static final String THIS_NODE = "test-core"; |
|||
|
|||
private EdgeGrpcService service; |
|||
private ScheduledExecutorService edgeEventProcessingExecutorService; |
|||
private TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache; |
|||
|
|||
private TenantId tenantId; |
|||
private EdgeId edgeId; |
|||
private Edge edge; |
|||
|
|||
@BeforeEach |
|||
@SuppressWarnings("unchecked") |
|||
void setUp() { |
|||
tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
edgeId = new EdgeId(UUID.randomUUID()); |
|||
edge = new Edge(edgeId); |
|||
edge.setTenantId(tenantId); |
|||
edge.setName("test-edge"); |
|||
|
|||
EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings(); |
|||
ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS); |
|||
|
|||
GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class); |
|||
// run future callbacks inline so the re-arm is observable without waiting on a pool
|
|||
doAnswer(invocation -> { |
|||
invocation.getArgument(0, Runnable.class).run(); |
|||
return null; |
|||
}).when(grpcCallbackExecutorService).execute(any()); |
|||
|
|||
EdgeContextComponent ctx = mock(EdgeContextComponent.class); |
|||
when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings); |
|||
when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService); |
|||
when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class)); |
|||
|
|||
TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
|
|||
edgeIdServiceIdCache = mock(TbTransactionalCache.class); |
|||
// this node is the recorded owner of the edge, which is what a live local session implies
|
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); |
|||
edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor(); |
|||
|
|||
service = new EdgeGrpcService(); |
|||
ReflectionTestUtils.setField(service, "ctx", ctx); |
|||
ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class)); |
|||
ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class)); |
|||
ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider); |
|||
ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache); |
|||
ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); |
|||
} |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
edgeEventProcessingExecutorService.shutdownNow(); |
|||
} |
|||
|
|||
@Test |
|||
void checkIsArmedForTheCurrentSession() { |
|||
EdgeGrpcSession session = newSession(); |
|||
sessions().put(edgeId, session); |
|||
|
|||
scheduleEdgeEventsCheck(session); |
|||
|
|||
ScheduledFuture<?> armed = edgeEventChecks().get(edgeId); |
|||
assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull(); |
|||
assertThat(armed.isCancelled()).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void checkIsNotArmedForASupersededSession() { |
|||
EdgeGrpcSession current = newSession(); |
|||
EdgeGrpcSession superseded = newSession(); |
|||
sessions().put(edgeId, current); |
|||
scheduleEdgeEventsCheck(current); |
|||
ScheduledFuture<?> armedByCurrent = edgeEventChecks().get(edgeId); |
|||
|
|||
scheduleEdgeEventsCheck(superseded); |
|||
|
|||
assertThat((Object) edgeEventChecks().get(edgeId)) |
|||
.as("the superseded session must neither cancel nor replace the current session's check") |
|||
.isSameAs(armedByCurrent); |
|||
assertThat(armedByCurrent.isCancelled()).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() { |
|||
EdgeGrpcSession session = newSession(); |
|||
onEdgeConnect(session); |
|||
ScheduledFuture<?> armedCheck = edgeEventChecks().get(edgeId); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
assertThat(sessions()).doesNotContainKey(edgeId); |
|||
assertThat(sessionsById()).doesNotContainKey(session.getSessionId()); |
|||
assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue(); |
|||
verify(edgeIdServiceIdCache).evict(edgeId); |
|||
verify(session).destroy(); |
|||
} |
|||
|
|||
@Test |
|||
void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() { |
|||
EdgeGrpcSession first = newSession(); |
|||
onEdgeConnect(first); |
|||
// the edge reconnects before the gRPC stream of the first session is closed
|
|||
EdgeGrpcSession second = newSession(); |
|||
onEdgeConnect(second); |
|||
ScheduledFuture<?> armedBySecond = edgeEventChecks().get(edgeId); |
|||
|
|||
onEdgeDisconnect(first); |
|||
|
|||
assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second); |
|||
assertThat(sessionsById()).containsKey(second.getSessionId()); |
|||
assertThat((Object) edgeEventChecks().get(edgeId)) |
|||
.as("the check armed by the reconnected session survives the teardown of the one it replaced") |
|||
.isSameAs(armedBySecond); |
|||
assertThat(armedBySecond.isCancelled()).isFalse(); |
|||
verify(edgeIdServiceIdCache, never()).evict(edgeId); |
|||
} |
|||
|
|||
@Test |
|||
void disconnectDoesNotClearTheNewEventsFlag() { |
|||
EdgeGrpcSession session = newSession(); |
|||
onEdgeConnect(session); |
|||
assertThat(newEvents()).containsEntry(edgeId, true); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
assertThat(newEvents()) |
|||
.as("clearing the flag here would wipe the one a reconnecting session has just raised") |
|||
.containsEntry(edgeId, true); |
|||
} |
|||
|
|||
@Test |
|||
void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception { |
|||
EdgeGrpcSession session = newSession(); |
|||
when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false)); |
|||
sessions().put(edgeId, session); |
|||
newEvents().put(edgeId, true); |
|||
migrationProcessed().put(edgeId, Boolean.TRUE); |
|||
|
|||
processEvents(session); |
|||
|
|||
assertThat(newEvents()).containsEntry(edgeId, false); |
|||
verify(session).processHighPriorityEvents(); |
|||
verify(session).processEdgeEvents(); |
|||
assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull(); |
|||
} |
|||
|
|||
@Test |
|||
void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception { |
|||
EdgeGrpcSession superseded = newSession(); |
|||
EdgeGrpcSession current = newSession(); |
|||
sessions().put(edgeId, current); |
|||
newEvents().put(edgeId, true); |
|||
migrationProcessed().put(edgeId, Boolean.TRUE); |
|||
|
|||
// cancel(true) cannot stop a check that has already started, so it runs against the old session
|
|||
processEvents(superseded); |
|||
|
|||
assertThat(newEvents()) |
|||
.as("consuming the flag here would leave the reconnected session with nothing to fetch") |
|||
.containsEntry(edgeId, true); |
|||
verify(superseded, never()).processHighPriorityEvents(); |
|||
verify(superseded, never()).processEdgeEvents(); |
|||
assertThat(edgeEventChecks()).doesNotContainKey(edgeId); |
|||
} |
|||
|
|||
@Test |
|||
void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() { |
|||
KafkaEdgeGrpcSession zombie = newZombieSession(); |
|||
when(zombie.destroy()).thenReturn(true); |
|||
sessions().put(edgeId, zombie); |
|||
scheduleEdgeEventsCheck(zombie); |
|||
ScheduledFuture<?> armedByZombie = edgeEventChecks().get(edgeId); |
|||
|
|||
cleanupZombieSessions(); |
|||
|
|||
assertThat(sessions()).doesNotContainKey(edgeId); |
|||
assertThat(armedByZombie.isCancelled()) |
|||
.as("the removed zombie must not leave an armed check behind") |
|||
.isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() { |
|||
KafkaEdgeGrpcSession zombie = newZombieSession(); |
|||
EdgeGrpcSession reconnected = newSession(); |
|||
sessions().put(edgeId, zombie); |
|||
// the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up
|
|||
when(zombie.destroy()).thenAnswer(invocation -> { |
|||
sessions().put(edgeId, reconnected); |
|||
scheduleEdgeEventsCheck(reconnected); |
|||
return true; |
|||
}); |
|||
|
|||
cleanupZombieSessions(); |
|||
|
|||
assertThat(sessions().get(edgeId)).isSameAs(reconnected); |
|||
ScheduledFuture<?> armedByReconnected = edgeEventChecks().get(edgeId); |
|||
assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull(); |
|||
assertThat(armedByReconnected.isCancelled()).isFalse(); |
|||
} |
|||
|
|||
private EdgeGrpcSession newSession() { |
|||
EdgeGrpcSession session = mock(EdgeGrpcSession.class); |
|||
stubSession(session); |
|||
return session; |
|||
} |
|||
|
|||
private KafkaEdgeGrpcSession newZombieSession() { |
|||
KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class); |
|||
stubSession(session); |
|||
@SuppressWarnings("unchecked") |
|||
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class); |
|||
@SuppressWarnings("unchecked") |
|||
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class); |
|||
when(consumerManager.getConsumer()).thenReturn(consumer); |
|||
when(consumer.isStopped()).thenReturn(false); |
|||
when(session.getConsumer()).thenReturn(consumerManager); |
|||
return session; |
|||
} |
|||
|
|||
private void stubSession(EdgeGrpcSession session) { |
|||
when(session.getEdge()).thenReturn(edge); |
|||
when(session.getTenantId()).thenReturn(tenantId); |
|||
when(session.getSessionId()).thenReturn(UUID.randomUUID()); |
|||
when(session.isConnected()).thenReturn(false); |
|||
when(session.destroy()).thenReturn(true); |
|||
} |
|||
|
|||
private void onEdgeConnect(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session); |
|||
} |
|||
|
|||
private void onEdgeDisconnect(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId()); |
|||
} |
|||
|
|||
private void scheduleEdgeEventsCheck(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session); |
|||
} |
|||
|
|||
private void processEvents(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId); |
|||
} |
|||
|
|||
private void cleanupZombieSessions() { |
|||
ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); |
|||
} |
|||
|
|||
private ConcurrentMap<EdgeId, EdgeGrpcSession> sessions() { |
|||
return field("sessions"); |
|||
} |
|||
|
|||
private ConcurrentMap<UUID, EdgeGrpcSession> sessionsById() { |
|||
return field("sessionsById"); |
|||
} |
|||
|
|||
private ConcurrentMap<EdgeId, ScheduledFuture<?>> edgeEventChecks() { |
|||
return field("sessionEdgeEventChecks"); |
|||
} |
|||
|
|||
private Map<EdgeId, Boolean> newEvents() { |
|||
return field("sessionNewEvents"); |
|||
} |
|||
|
|||
private ConcurrentMap<EdgeId, Boolean> migrationProcessed() { |
|||
return field("edgeEventsMigrationProcessed"); |
|||
} |
|||
|
|||
@SuppressWarnings("unchecked") |
|||
private <T> T field(String name) { |
|||
return (T) ReflectionTestUtils.getField(service, name); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,112 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge.rpc.processor.settings; |
|||
|
|||
import org.junit.jupiter.api.Assertions; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.ValueSource; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.AdminSettings; |
|||
import org.thingsboard.server.common.data.edge.EdgeEvent; |
|||
import org.thingsboard.server.common.data.id.AdminSettingsId; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsService; |
|||
import org.thingsboard.server.gen.edge.v1.DownlinkMsg; |
|||
import org.thingsboard.server.gen.edge.v1.EdgeVersion; |
|||
import org.thingsboard.server.service.edge.EdgeContextComponent; |
|||
|
|||
import java.util.UUID; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.lenient; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
public class AdminSettingsEdgeProcessorTest { |
|||
|
|||
@Mock |
|||
private EdgeContextComponent edgeCtx; |
|||
@Mock |
|||
private AdminSettingsService adminSettingsService; |
|||
|
|||
private final TenantId tenantId = new TenantId(UUID.randomUUID()); |
|||
private AdminSettingsEdgeProcessor processor; |
|||
|
|||
@BeforeEach |
|||
public void setUp() { |
|||
processor = new AdminSettingsEdgeProcessor(); |
|||
ReflectionTestUtils.setField(processor, "edgeCtx", edgeCtx); |
|||
lenient().when(edgeCtx.getAdminSettingsService()).thenReturn(adminSettingsService); |
|||
} |
|||
|
|||
@Test |
|||
public void testTenantScopedAllowListedKeyIsSyncedToEdge() { |
|||
AdminSettings general = adminSettings(tenantId, "general"); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(general); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNotNull(downlink); |
|||
Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount()); |
|||
AdminSettings synced = JacksonUtil.fromString(downlink.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true); |
|||
Assertions.assertNotNull(synced); |
|||
Assertions.assertEquals("general", synced.getKey()); |
|||
} |
|||
|
|||
@Test |
|||
public void testTenantScopedNonAllowListedKeyIsNotSyncedToEdge() { |
|||
AdminSettings mail = adminSettings(tenantId, "mail"); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(mail); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNull(downlink); |
|||
} |
|||
|
|||
@Test |
|||
public void testSystemScopedAllowListedKeyIsSyncedToEdge() { |
|||
AdminSettings connectivity = adminSettings(TenantId.SYS_TENANT_ID, "connectivity"); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(connectivity); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNotNull(downlink); |
|||
Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount()); |
|||
} |
|||
|
|||
@ParameterizedTest |
|||
@ValueSource(strings = {"mail", "jwt", "sms", "notifications"}) |
|||
public void testSystemScopedNonAllowListedKeyIsNotSyncedToEdge(String key) { |
|||
AdminSettings settings = adminSettings(TenantId.SYS_TENANT_ID, key); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(settings); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNull(downlink); |
|||
} |
|||
|
|||
private EdgeEvent edgeEvent(TenantId eventTenantId) { |
|||
EdgeEvent edgeEvent = new EdgeEvent(); |
|||
edgeEvent.setTenantId(eventTenantId); |
|||
edgeEvent.setEdgeId(new EdgeId(UUID.randomUUID())); |
|||
edgeEvent.setEntityId(UUID.randomUUID()); |
|||
return edgeEvent; |
|||
} |
|||
|
|||
private AdminSettings adminSettings(TenantId settingsTenantId, String key) { |
|||
AdminSettings adminSettings = new AdminSettings(); |
|||
adminSettings.setId(new AdminSettingsId(UUID.randomUUID())); |
|||
adminSettings.setTenantId(settingsTenantId); |
|||
adminSettings.setKey(key); |
|||
adminSettings.setJsonValue(JacksonUtil.newObjectNode()); |
|||
return adminSettings; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.install; |
|||
|
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.CsvSource; |
|||
import org.springframework.boot.info.BuildProperties; |
|||
|
|||
import java.util.Optional; |
|||
import java.util.Properties; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
|
|||
class ProjectInfoTest { |
|||
|
|||
@ParameterizedTest |
|||
@CsvSource({ |
|||
"4.2.2, 4.2.2", |
|||
"4.2.2-SNAPSHOT, 4.2.2", |
|||
"4.2.2PE-SNAPSHOT, 4.2.2", |
|||
"4.2.2.8PE, 4.2.2.8", |
|||
"4.2.2PAAS.cbeee8ba6f2, 4.2.2", |
|||
"4.2.2-RC1, 4.2.2" |
|||
}) |
|||
void keepsOnlyTheLeadingNumericVersion(String buildVersion, String expected) { |
|||
Properties properties = new Properties(); |
|||
properties.setProperty("version", buildVersion); |
|||
|
|||
assertThat(new ProjectInfo(Optional.of(new BuildProperties(properties))).getProjectVersion()).isEqualTo(expected); |
|||
} |
|||
|
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue