Search in sources :

Example 1 with SessionInfoProto

use of org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto in project thingsboard by thingsboard.

the class DefaultLwM2mUplinkMsgHandler method onRegistered.

/**
 * Start registration device
 * Create session: Map<String <registrationId >, LwM2MClient>
 * 1. replaceNewRegistration -> (solving the problem of incorrect termination of the previous session with this endpoint)
 * 1.1 When we initialize the registration, we register the session by endpoint.
 * 1.2 If the server has incomplete requests (canceling the registration of the previous session),
 * delete the previous session only by the previous registration.getId
 * 1.2 Add Model (Entity) for client (from registration & observe) by registration.getId
 * 1.2 Remove from sessions Model by enpPoint
 * Next ->  Create new LwM2MClient for current session -> setModelClient...
 *
 * @param registration         - Registration LwM2M Client
 * @param previousObservations - may be null
 */
public void onRegistered(Registration registration, Collection<Observation> previousObservations) {
    executor.submit(() -> {
        LwM2mClient lwM2MClient = this.clientContext.getClientByEndpoint(registration.getEndpoint());
        try {
            log.debug("[{}] [{{}] Client: create after Registration", registration.getEndpoint(), registration.getId());
            Optional<SessionInfoProto> oldSessionInfo = this.clientContext.register(lwM2MClient, registration);
            if (oldSessionInfo.isPresent()) {
                log.info("[{}] Closing old session: {}", registration.getEndpoint(), new UUID(oldSessionInfo.get().getSessionIdMSB(), oldSessionInfo.get().getSessionIdLSB()));
                sessionManager.deregister(oldSessionInfo.get());
            }
            logService.log(lwM2MClient, LOG_LWM2M_INFO + ": Client registered with registration id: " + registration.getId() + " version: " + registration.getLwM2mVersion() + " and modes: " + registration.getQueueMode() + ", " + registration.getBindingMode());
            sessionManager.register(lwM2MClient.getSession());
            this.initClientTelemetry(lwM2MClient);
            this.initAttributes(lwM2MClient, true);
            otaService.init(lwM2MClient);
            lwM2MClient.getRetryAttempts().set(0);
        } catch (LwM2MClientStateException stateException) {
            if (LwM2MClientState.UNREGISTERED.equals(stateException.getState())) {
                log.info("[{}] retry registration due to race condition: [{}].", registration.getEndpoint(), stateException.getState());
                // Race condition detected and the client was in progress of unregistration while new registration arrived. Let's try again.
                if (lwM2MClient.getRetryAttempts().incrementAndGet() <= 5) {
                    context.getScheduler().schedule(() -> onRegistered(registration, previousObservations), 1, TimeUnit.SECONDS);
                } else {
                    logService.log(lwM2MClient, LOG_LWM2M_WARN + ": Client registration failed due to retry attempts: " + lwM2MClient.getRetryAttempts().get());
                }
            } else {
                logService.log(lwM2MClient, LOG_LWM2M_WARN + ": Client registration failed due to invalid state: " + stateException.getState());
            }
        } catch (Throwable t) {
            log.error("[{}] endpoint [{}] error Unable registration.", registration.getEndpoint(), t);
            logService.log(lwM2MClient, LOG_LWM2M_WARN + ": Client registration failed due to: " + t.getMessage());
        }
    });
}
Also used : SessionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto) LwM2MClientStateException(org.thingsboard.server.transport.lwm2m.server.client.LwM2MClientStateException) UUID(java.util.UUID) LwM2mClient(org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient)

Example 2 with SessionInfoProto

use of org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method restoreSessions.

void restoreSessions() {
    if (systemContext.isLocalCacheType()) {
        return;
    }
    log.debug("[{}] Restoring sessions from cache", deviceId);
    DeviceSessionsCacheEntry sessionsDump = null;
    try {
        sessionsDump = DeviceSessionsCacheEntry.parseFrom(systemContext.getDeviceSessionCacheService().get(deviceId));
    } catch (InvalidProtocolBufferException e) {
        log.warn("[{}] Failed to decode device sessions from cache", deviceId);
        return;
    }
    if (sessionsDump.getSessionsCount() == 0) {
        log.debug("[{}] No session information found", deviceId);
        return;
    }
    // TODO: Take latest max allowed sessions size from cache
    for (SessionSubscriptionInfoProto sessionSubscriptionInfoProto : sessionsDump.getSessionsList()) {
        SessionInfoProto sessionInfoProto = sessionSubscriptionInfoProto.getSessionInfo();
        UUID sessionId = getSessionId(sessionInfoProto);
        SessionInfo sessionInfo = new SessionInfo(SessionType.ASYNC, sessionInfoProto.getNodeId());
        SubscriptionInfoProto subInfo = sessionSubscriptionInfoProto.getSubscriptionInfo();
        SessionInfoMetaData sessionMD = new SessionInfoMetaData(sessionInfo, subInfo.getLastActivityTime());
        sessions.put(sessionId, sessionMD);
        if (subInfo.getAttributeSubscription()) {
            attributeSubscriptions.put(sessionId, sessionInfo);
            sessionMD.setSubscribedToAttributes(true);
        }
        if (subInfo.getRpcSubscription()) {
            rpcSubscriptions.put(sessionId, sessionInfo);
            sessionMD.setSubscribedToRPC(true);
        }
        log.debug("[{}] Restored session: {}", deviceId, sessionMD);
    }
    log.debug("[{}] Restored sessions: {}, rpc subscriptions: {}, attribute subscriptions: {}", deviceId, sessions.size(), rpcSubscriptions.size(), attributeSubscriptions.size());
}
Also used : SessionSubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto) SessionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto) SessionSubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto) SubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SubscriptionInfoProto) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) DeviceSessionsCacheEntry(org.thingsboard.server.gen.transport.TransportProtos.DeviceSessionsCacheEntry) UUID(java.util.UUID)

Example 3 with SessionInfoProto

use of org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method processUplinkNotificationMsg.

private void processUplinkNotificationMsg(TbActorCtx context, SessionInfoProto sessionInfo, TransportProtos.UplinkNotificationMsg uplinkNotificationMsg) {
    String nodeId = sessionInfo.getNodeId();
    sessions.entrySet().stream().filter(kv -> kv.getValue().getSessionInfo().getNodeId().equals(nodeId) && (kv.getValue().isSubscribedToAttributes() || kv.getValue().isSubscribedToRPC())).forEach(kv -> {
        ToTransportMsg msg = ToTransportMsg.newBuilder().setSessionIdMSB(kv.getKey().getMostSignificantBits()).setSessionIdLSB(kv.getKey().getLeastSignificantBits()).setUplinkNotificationMsg(uplinkNotificationMsg).build();
        systemContext.getTbCoreToTransportService().process(kv.getValue().getSessionInfo().getNodeId(), msg);
    });
}
Also used : Arrays(java.util.Arrays) RpcStatus(org.thingsboard.server.common.data.rpc.RpcStatus) KeyValueType(org.thingsboard.server.gen.transport.TransportProtos.KeyValueType) ToDeviceRpcRequestActorMsg(org.thingsboard.server.service.rpc.ToDeviceRpcRequestActorMsg) TenantId(org.thingsboard.server.common.data.id.TenantId) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) SessionType(org.thingsboard.server.gen.transport.TransportProtos.SessionType) FromDeviceRpcResponseActorMsg(org.thingsboard.server.service.rpc.FromDeviceRpcResponseActorMsg) ActorSystemContext(org.thingsboard.server.actors.ActorSystemContext) Rpc(org.thingsboard.server.common.data.rpc.Rpc) AbstractContextAwareMsgProcessor(org.thingsboard.server.actors.shared.AbstractContextAwareMsgProcessor) SubscribeToAttributeUpdatesMsg(org.thingsboard.server.gen.transport.TransportProtos.SubscribeToAttributeUpdatesMsg) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) DeviceAttributesEventNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceAttributesEventNotificationMsg) DeviceCredentialsUpdateNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceCredentialsUpdateNotificationMsg) EdgeId(org.thingsboard.server.common.data.id.EdgeId) GetAttributeResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.GetAttributeResponseMsg) TransportToDeviceActorMsg(org.thingsboard.server.gen.transport.TransportProtos.TransportToDeviceActorMsg) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ClaimDeviceMsg(org.thingsboard.server.gen.transport.TransportProtos.ClaimDeviceMsg) DeviceId(org.thingsboard.server.common.data.id.DeviceId) PageLink(org.thingsboard.server.common.data.page.PageLink) ToTransportUpdateCredentialsProto(org.thingsboard.server.gen.transport.TransportProtos.ToTransportUpdateCredentialsProto) StringUtils(org.thingsboard.server.common.data.StringUtils) Set(java.util.Set) TbActorCtx(org.thingsboard.server.actors.TbActorCtx) UUID(java.util.UUID) SortOrder(org.thingsboard.server.common.data.page.SortOrder) Collectors(java.util.stream.Collectors) EdgeEventActionType(org.thingsboard.server.common.data.edge.EdgeEventActionType) ToServerRpcResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcResponseMsg) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) SubscribeToRPCMsg(org.thingsboard.server.gen.transport.TransportProtos.SubscribeToRPCMsg) TbActorMsg(org.thingsboard.server.common.msg.TbActorMsg) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) DeviceNameOrTypeUpdateMsg(org.thingsboard.rule.engine.api.msg.DeviceNameOrTypeUpdateMsg) TransportProtos(org.thingsboard.server.gen.transport.TransportProtos) GetAttributeRequestMsg(org.thingsboard.server.gen.transport.TransportProtos.GetAttributeRequestMsg) Optional(java.util.Optional) ToDeviceRpcRequestBody(org.thingsboard.server.common.data.rpc.ToDeviceRpcRequestBody) RemoveRpcActorMsg(org.thingsboard.server.service.rpc.RemoveRpcActorMsg) ConcurrentModificationException(java.util.ConcurrentModificationException) AttributeUpdateNotificationMsg(org.thingsboard.server.gen.transport.TransportProtos.AttributeUpdateNotificationMsg) DeviceActorServerSideRpcTimeoutMsg(org.thingsboard.server.common.msg.timeout.DeviceActorServerSideRpcTimeoutMsg) ToDeviceRpcRequestMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcRequestMsg) TransportToDeviceActorMsgWrapper(org.thingsboard.server.service.transport.msg.TransportToDeviceActorMsgWrapper) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ToDeviceRpcResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcResponseMsg) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ToDeviceRpcRequest(org.thingsboard.server.common.msg.rpc.ToDeviceRpcRequest) Device(org.thingsboard.server.common.data.Device) JacksonUtil(org.thingsboard.common.util.JacksonUtil) HashMap(java.util.HashMap) DeviceEdgeUpdateMsg(org.thingsboard.rule.engine.api.msg.DeviceEdgeUpdateMsg) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) SessionSubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMapRemoveEldest(org.thingsboard.common.util.LinkedHashMapRemoveEldest) CollectionUtils(org.apache.commons.collections.CollectionUtils) SessionCloseNotificationProto(org.thingsboard.server.gen.transport.TransportProtos.SessionCloseNotificationProto) KeyValueProto(org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto) SessionEvent(org.thingsboard.server.gen.transport.TransportProtos.SessionEvent) DeviceSessionsCacheEntry(org.thingsboard.server.gen.transport.TransportProtos.DeviceSessionsCacheEntry) TbCallback(org.thingsboard.server.common.msg.queue.TbCallback) Nullable(javax.annotation.Nullable) AttributeKey(org.thingsboard.server.common.data.kv.AttributeKey) DataConstants(org.thingsboard.server.common.data.DataConstants) RpcId(org.thingsboard.server.common.data.id.RpcId) FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) DeviceCredentialsType(org.thingsboard.server.common.data.security.DeviceCredentialsType) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) SessionEventMsg(org.thingsboard.server.gen.transport.TransportProtos.SessionEventMsg) SessionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto) RpcError(org.thingsboard.server.common.data.rpc.RpcError) FutureCallback(com.google.common.util.concurrent.FutureCallback) TsKvProto(org.thingsboard.server.gen.transport.TransportProtos.TsKvProto) Consumer(java.util.function.Consumer) SubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SubscriptionInfoProto) ToTransportMsg(org.thingsboard.server.gen.transport.TransportProtos.ToTransportMsg) Futures(com.google.common.util.concurrent.Futures) PageData(org.thingsboard.server.common.data.page.PageData) EdgeEvent(org.thingsboard.server.common.data.edge.EdgeEvent) EdgeEventType(org.thingsboard.server.common.data.edge.EdgeEventType) RelationTypeGroup(org.thingsboard.server.common.data.relation.RelationTypeGroup) ToDeviceRpcResponseStatusMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcResponseStatusMsg) Collections(java.util.Collections) ToTransportMsg(org.thingsboard.server.gen.transport.TransportProtos.ToTransportMsg)

Example 4 with SessionInfoProto

use of org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method dumpSessions.

private void dumpSessions() {
    if (systemContext.isLocalCacheType()) {
        return;
    }
    log.debug("[{}] Dumping sessions: {}, rpc subscriptions: {}, attribute subscriptions: {} to cache", deviceId, sessions.size(), rpcSubscriptions.size(), attributeSubscriptions.size());
    List<SessionSubscriptionInfoProto> sessionsList = new ArrayList<>(sessions.size());
    sessions.forEach((uuid, sessionMD) -> {
        if (sessionMD.getSessionInfo().getType() == SessionType.SYNC) {
            return;
        }
        SessionInfo sessionInfo = sessionMD.getSessionInfo();
        SubscriptionInfoProto subscriptionInfoProto = SubscriptionInfoProto.newBuilder().setLastActivityTime(sessionMD.getLastActivityTime()).setAttributeSubscription(sessionMD.isSubscribedToAttributes()).setRpcSubscription(sessionMD.isSubscribedToRPC()).build();
        SessionInfoProto sessionInfoProto = SessionInfoProto.newBuilder().setSessionIdMSB(uuid.getMostSignificantBits()).setSessionIdLSB(uuid.getLeastSignificantBits()).setNodeId(sessionInfo.getNodeId()).build();
        sessionsList.add(SessionSubscriptionInfoProto.newBuilder().setSessionInfo(sessionInfoProto).setSubscriptionInfo(subscriptionInfoProto).build());
        log.debug("[{}] Dumping session: {}", deviceId, sessionMD);
    });
    systemContext.getDeviceSessionCacheService().put(deviceId, DeviceSessionsCacheEntry.newBuilder().addAllSessions(sessionsList).build().toByteArray());
}
Also used : SessionSubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto) SessionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto) SessionSubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto) SubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SubscriptionInfoProto) ArrayList(java.util.ArrayList)

Example 5 with SessionInfoProto

use of org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto in project thingsboard by thingsboard.

the class DefaultLwM2mUplinkMsgHandler method doUnReg.

private void doUnReg(Registration registration, LwM2mClient client) {
    try {
        logService.log(client, LOG_LWM2M_INFO + ": Client unRegistration");
        clientContext.unregister(client, registration);
        SessionInfoProto sessionInfo = client.getSession();
        if (sessionInfo != null) {
            sessionManager.deregister(sessionInfo);
            sessionStore.remove(registration.getEndpoint());
            log.info("Client close session: [{}] unReg [{}] name  [{}] profile ", registration.getId(), registration.getEndpoint(), sessionInfo.getDeviceType());
        } else {
            log.error("Client close session: [{}] unReg [{}] name  [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), null);
        }
    } catch (LwM2MClientStateException stateException) {
        log.info("[{}] delete registration: [{}] {}.", registration.getEndpoint(), stateException.getState(), stateException.getMessage());
    } catch (Throwable t) {
        log.error("[{}] endpoint [{}] error Unable un registration.", registration.getEndpoint(), t);
        logService.log(client, LOG_LWM2M_ERROR + String.format(": Client Unable un Registration, %s", t.getMessage()));
    }
}
Also used : SessionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto) LwM2MClientStateException(org.thingsboard.server.transport.lwm2m.server.client.LwM2MClientStateException)

Aggregations

SessionInfoProto (org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto)6 UUID (java.util.UUID)3 SessionSubscriptionInfoProto (org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto)3 SubscriptionInfoProto (org.thingsboard.server.gen.transport.TransportProtos.SubscriptionInfoProto)3 LwM2MClientStateException (org.thingsboard.server.transport.lwm2m.server.client.LwM2MClientStateException)3 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 ArrayList (java.util.ArrayList)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 FutureCallback (com.google.common.util.concurrent.FutureCallback)1 Futures (com.google.common.util.concurrent.Futures)1 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 ConcurrentModificationException (java.util.ConcurrentModificationException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1