Browse Source

lwm2m: The method "getTasks" is thread-safe

pull/6119/head
nickAS21 5 years ago
parent
commit
5241c371df
  1. 27
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java
  2. 31
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapClientInstanceIds.java
  3. 120
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapConfigStoreTaskProvider.java
  4. 26
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapTaskProvider.java

27
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java

@ -27,6 +27,7 @@ import org.eclipse.leshan.server.bootstrap.BootstrapSession;
import org.eclipse.leshan.server.bootstrap.BootstrapTaskProvider; import org.eclipse.leshan.server.bootstrap.BootstrapTaskProvider;
import org.eclipse.leshan.server.bootstrap.DefaultBootstrapSession; import org.eclipse.leshan.server.bootstrap.DefaultBootstrapSession;
import org.eclipse.leshan.server.bootstrap.DefaultBootstrapSessionManager; import org.eclipse.leshan.server.bootstrap.DefaultBootstrapSessionManager;
import org.eclipse.leshan.server.bootstrap.InvalidConfigurationException;
import org.eclipse.leshan.server.model.LwM2mBootstrapModelProvider; import org.eclipse.leshan.server.model.LwM2mBootstrapModelProvider;
import org.eclipse.leshan.server.model.StandardBootstrapModelProvider; import org.eclipse.leshan.server.model.StandardBootstrapModelProvider;
import org.eclipse.leshan.server.security.BootstrapSecurityStore; import org.eclipse.leshan.server.security.BootstrapSecurityStore;
@ -35,6 +36,7 @@ import org.eclipse.leshan.server.security.SecurityInfo;
import org.thingsboard.server.common.transport.TransportService; import org.thingsboard.server.common.transport.TransportService;
import org.thingsboard.server.transport.lwm2m.bootstrap.store.LwM2MBootstrapConfigStoreTaskProvider; import org.thingsboard.server.transport.lwm2m.bootstrap.store.LwM2MBootstrapConfigStoreTaskProvider;
import org.thingsboard.server.transport.lwm2m.bootstrap.store.LwM2MBootstrapSecurityStore; import org.thingsboard.server.transport.lwm2m.bootstrap.store.LwM2MBootstrapSecurityStore;
import org.thingsboard.server.transport.lwm2m.bootstrap.store.LwM2MBootstrapTaskProvider;
import org.thingsboard.server.transport.lwm2m.server.client.LwM2MAuthException; import org.thingsboard.server.transport.lwm2m.server.client.LwM2MAuthException;
import java.util.ArrayList; import java.util.ArrayList;
@ -48,10 +50,10 @@ import static org.thingsboard.server.transport.lwm2m.utils.LwM2MTransportUtil.LO
@Slf4j @Slf4j
public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSessionManager { public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSessionManager {
private BootstrapSecurityStore bsSecurityStore; private final BootstrapSecurityStore bsSecurityStore;
private SecurityChecker securityChecker; private final SecurityChecker securityChecker;
private BootstrapTaskProvider tasksProvider; private final LwM2MBootstrapTaskProvider tasksProvider;
private LwM2mBootstrapModelProvider modelProvider; private final LwM2mBootstrapModelProvider modelProvider;
private TransportService transportService; private TransportService transportService;
/** /**
@ -73,7 +75,7 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
* @param securityChecker used to accept or refuse new {@link BootstrapSession}. * @param securityChecker used to accept or refuse new {@link BootstrapSession}.
*/ */
public LwM2mDefaultBootstrapSessionManager(BootstrapSecurityStore bsSecurityStore, SecurityChecker securityChecker, public LwM2mDefaultBootstrapSessionManager(BootstrapSecurityStore bsSecurityStore, SecurityChecker securityChecker,
BootstrapTaskProvider tasksProvider, LwM2mBootstrapModelProvider modelProvider) { LwM2MBootstrapTaskProvider tasksProvider, LwM2mBootstrapModelProvider modelProvider) {
super(bsSecurityStore, securityChecker, tasksProvider, modelProvider); super(bsSecurityStore, securityChecker, tasksProvider, modelProvider);
this.bsSecurityStore = bsSecurityStore; this.bsSecurityStore = bsSecurityStore;
this.securityChecker = securityChecker; this.securityChecker = securityChecker;
@ -100,7 +102,12 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
} }
DefaultBootstrapSession session = new DefaultBootstrapSession(request, clientIdentity, authorized); DefaultBootstrapSession session = new DefaultBootstrapSession(request, clientIdentity, authorized);
if (authorized) { if (authorized) {
this.sendLogs (request.getEndpointName(), try {
this.tasksProvider.put(session.getEndpoint());
} catch (InvalidConfigurationException e){
log.error("Failed put to lwM2MBootstrapSessionClients by endpoint [{}]", request.getEndpointName(), e);
}
this.sendLogs(request.getEndpointName(),
String.format("%s: Bootstrap session started...", LOG_LWM2M_INFO, request.getEndpointName())); String.format("%s: Bootstrap session started...", LOG_LWM2M_INFO, request.getEndpointName()));
} }
return session; return session;
@ -108,7 +115,7 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
@Override @Override
public boolean hasConfigFor(BootstrapSession session) { public boolean hasConfigFor(BootstrapSession session) {
BootstrapTaskProvider.Tasks firstTasks = tasksProvider.getTasks(session, null); BootstrapTaskProvider.Tasks firstTasks = this.tasksProvider.getTasks(session, null);
if (firstTasks == null) { if (firstTasks == null) {
return false; return false;
} }
@ -147,7 +154,7 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
return requestsToSend.remove(0); return requestsToSend.remove(0);
} else { } else {
if (session.hasMoreTasks()) { if (session.hasMoreTasks()) {
BootstrapTaskProvider.Tasks nextTasks = tasksProvider.getTasks(session, session.getResponses()); BootstrapTaskProvider.Tasks nextTasks = this.tasksProvider.getTasks(session, session.getResponses());
if (nextTasks == null) { if (nextTasks == null) {
session.setMoreTasks(false); session.setMoreTasks(false);
return new BootstrapFinishRequest(); return new BootstrapFinishRequest();
@ -178,6 +185,7 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
// on success for bootstrap finish request we stop the session // on success for bootstrap finish request we stop the session
this.sendLogs(bsSession.getEndpoint(), this.sendLogs(bsSession.getEndpoint(),
String.format("%s: receives success response for bootstrap finish.", LOG_LWM2M_INFO)); String.format("%s: receives success response for bootstrap finish.", LOG_LWM2M_INFO));
this.tasksProvider.remove(bsSession.getEndpoint());
return BootstrapPolicy.finished(); return BootstrapPolicy.finished();
} }
} }
@ -199,6 +207,7 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
// on response error for bootstrap finish request we stop the session // on response error for bootstrap finish request we stop the session
this.sendLogs(bsSession.getEndpoint(), this.sendLogs(bsSession.getEndpoint(),
String.format("%s: error response for request bootstrap finish. Stop the session: %s", LOG_LWM2M_ERROR, bsSession.toString())); String.format("%s: error response for request bootstrap finish. Stop the session: %s", LOG_LWM2M_ERROR, bsSession.toString()));
this.tasksProvider.remove(bsSession.getEndpoint());
return BootstrapPolicy.failed(); return BootstrapPolicy.failed();
} }
} }
@ -215,12 +224,14 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession
@Override @Override
public void end(BootstrapSession bsSession) { public void end(BootstrapSession bsSession) {
this.sendLogs(bsSession.getEndpoint(), String.format("%s: Bootstrap session finished.", LOG_LWM2M_INFO)); this.sendLogs(bsSession.getEndpoint(), String.format("%s: Bootstrap session finished.", LOG_LWM2M_INFO));
this.tasksProvider.remove(bsSession.getEndpoint());
} }
@Override @Override
public void failed(BootstrapSession bsSession, BootstrapFailureCause cause) { public void failed(BootstrapSession bsSession, BootstrapFailureCause cause) {
this.sendLogs(bsSession.getEndpoint(), String.format("%s: Bootstrap session failed because of %s", LOG_LWM2M_ERROR, this.sendLogs(bsSession.getEndpoint(), String.format("%s: Bootstrap session failed because of %s", LOG_LWM2M_ERROR,
cause.toString())); cause.toString()));
this.tasksProvider.remove(bsSession.getEndpoint());
} }
private void sendLogs(String endpointName, String logMsg) { private void sendLogs(String endpointName, String logMsg) {

31
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapClientInstanceIds.java

@ -0,0 +1,31 @@
/**
* Copyright © 2016-2022 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.transport.lwm2m.bootstrap.store;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class LwM2MBootstrapClientInstanceIds {
/**
* Map<serverId (shortId), InstanceId>
*/
private Map<Integer, Integer> securityInstances = new HashMap<>();
private Map<Integer, Integer> serverInstances = new HashMap<>();
}

120
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapConfigStoreTaskProvider.java

@ -30,8 +30,8 @@ import org.eclipse.leshan.core.response.LwM2mResponse;
import org.eclipse.leshan.server.bootstrap.BootstrapConfig; import org.eclipse.leshan.server.bootstrap.BootstrapConfig;
import org.eclipse.leshan.server.bootstrap.BootstrapConfigStore; import org.eclipse.leshan.server.bootstrap.BootstrapConfigStore;
import org.eclipse.leshan.server.bootstrap.BootstrapSession; import org.eclipse.leshan.server.bootstrap.BootstrapSession;
import org.eclipse.leshan.server.bootstrap.BootstrapTaskProvider;
import org.eclipse.leshan.server.bootstrap.BootstrapUtil; import org.eclipse.leshan.server.bootstrap.BootstrapUtil;
import org.eclipse.leshan.server.bootstrap.InvalidConfigurationException;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList; import java.util.ArrayList;
@ -42,28 +42,35 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.eclipse.leshan.core.model.ResourceModel.Type.OPAQUE; import static org.eclipse.leshan.core.model.ResourceModel.Type.OPAQUE;
import static org.eclipse.leshan.server.bootstrap.BootstrapUtil.toWriteRequest; import static org.eclipse.leshan.server.bootstrap.BootstrapUtil.toWriteRequest;
@Slf4j @Slf4j
public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvider { public class LwM2MBootstrapConfigStoreTaskProvider implements LwM2MBootstrapTaskProvider {
protected final ReadWriteLock readWriteLock;
protected final Lock writeLock;
private BootstrapConfigStore store; private BootstrapConfigStore store;
private Map<Integer, String> supportedObjects; private Map<Integer, String> supportedObjects;
/** /**
* Map<serverId, InstanceId> * Map<sEndpoint, LwM2MBootstrapClientInstanceIds: securityInstances, serverInstances>
*/ */
protected Map<Integer, Integer> securityInstances; protected Map<String, LwM2MBootstrapClientInstanceIds> lwM2MBootstrapSessionClients;
protected Map<Integer, Integer> serverInstances;
protected Integer bootstrapServerIdOld;
protected Integer bootstrapServerIdNew;
public LwM2MBootstrapConfigStoreTaskProvider(BootstrapConfigStore store) { public LwM2MBootstrapConfigStoreTaskProvider(BootstrapConfigStore store) {
this.store = store; this.store = store;
this.lwM2MBootstrapSessionClients = new ConcurrentHashMap<>();
readWriteLock = new ReentrantReadWriteLock();
writeLock = readWriteLock.writeLock();
} }
@Override @Override
@ -91,13 +98,13 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
BootstrapDiscoverResponse discoverResponse = (BootstrapDiscoverResponse) previousResponse.get(0); BootstrapDiscoverResponse discoverResponse = (BootstrapDiscoverResponse) previousResponse.get(0);
if (discoverResponse.isSuccess()) { if (discoverResponse.isSuccess()) {
this.initAfterBootstrapDiscover(discoverResponse); this.initAfterBootstrapDiscover(discoverResponse);
findSecurityInstanceId(discoverResponse.getObjectLinks()); findSecurityInstanceId(discoverResponse.getObjectLinks(), session.getEndpoint());
} else { } else {
log.warn( log.warn(
"Bootstrap Discover return error {} : to continue bootstrap session without autoIdForSecurityObject mode. {}", "Bootstrap Discover return error {} : to continue bootstrap session without autoIdForSecurityObject mode. {}",
discoverResponse, session); discoverResponse, session);
} }
if (this.securityInstances.get(0) == null) { if (this.lwM2MBootstrapSessionClients.get(session.getEndpoint()).getSecurityInstances().get(0) == null) {
log.error( log.error(
"Unable to find bootstrap server instance in Security Object (0) in response {}: unable to continue bootstrap session with autoIdForSecurityObject mode. {}", "Unable to find bootstrap server instance in Security Object (0) in response {}: unable to continue bootstrap session with autoIdForSecurityObject mode. {}",
discoverResponse, session); discoverResponse, session);
@ -109,8 +116,12 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
return tasks; return tasks;
} }
BootstrapReadResponse readResponse = (BootstrapReadResponse) previousResponse.get(0); BootstrapReadResponse readResponse = (BootstrapReadResponse) previousResponse.get(0);
Integer bootstrapServerIdOld = null;
if (readResponse.isSuccess()) { if (readResponse.isSuccess()) {
findServerInstanceId(readResponse); findServerInstanceId(readResponse, session.getEndpoint());
if (this.lwM2MBootstrapSessionClients.get(session.getEndpoint()).getSecurityInstances().size() > 0 && this.lwM2MBootstrapSessionClients.get(session.getEndpoint()).getServerInstances().size() > 0) {
bootstrapServerIdOld = this.findBootstrapServerId(session.getEndpoint());
}
} else { } else {
log.warn( log.warn(
"Bootstrap ReadResponse return error {} : to continue bootstrap session without find Server Instance Id. {}", "Bootstrap ReadResponse return error {} : to continue bootstrap session without find Server Instance Id. {}",
@ -118,7 +129,8 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
} }
// create requests from config // create requests from config
tasks.requestsToSend = this.toRequests(config, tasks.requestsToSend = this.toRequests(config,
config.contentFormat != null ? config.contentFormat : session.getContentFormat()); config.contentFormat != null ? config.contentFormat : session.getContentFormat(),
bootstrapServerIdOld, session.getEndpoint());
} else { } else {
// create requests from config // create requests from config
tasks.requestsToSend = BootstrapUtil.toRequests(config, tasks.requestsToSend = BootstrapUtil.toRequests(config,
@ -132,9 +144,8 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
return config.autoIdForSecurityObject; return config.autoIdForSecurityObject;
} }
protected void findSecurityInstanceId(Link[] objectLinks) { protected void findSecurityInstanceId(Link[] objectLinks, String endpoint) {
log.info("Object after discover: [{}]", objectLinks); log.info("Object after discover: [{}]", objectLinks);
this.securityInstances = new HashMap<>();
for (Link link : objectLinks) { for (Link link : objectLinks) {
if (link.getUriReference().startsWith("/0/")) { if (link.getUriReference().startsWith("/0/")) {
try { try {
@ -142,15 +153,15 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
if (path.isObjectInstance()) { if (path.isObjectInstance()) {
if (link.getLinkParams().containsKey("ssid")) { if (link.getLinkParams().containsKey("ssid")) {
int serverId = Integer.parseInt(link.getLinkParams().get("ssid").getUnquoted()); int serverId = Integer.parseInt(link.getLinkParams().get("ssid").getUnquoted());
if (!this.securityInstances.containsKey(serverId)) { if (!lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().containsKey(serverId)) {
this.securityInstances.put(serverId, path.getObjectInstanceId()); lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().put(serverId, path.getObjectInstanceId());
} else { } else {
log.error("Invalid lwm2mSecurityInstance by [{}]", path.getObjectInstanceId()); log.error("Invalid lwm2mSecurityInstance by [{}]", path.getObjectInstanceId());
} }
this.securityInstances.put(Integer.valueOf(link.getLinkParams().get("ssid").getUnquoted()), path.getObjectInstanceId()); lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().put(Integer.valueOf(link.getLinkParams().get("ssid").getUnquoted()), path.getObjectInstanceId());
} else { } else {
if (!this.securityInstances.containsKey(0)) { if (!this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().containsKey(0)) {
this.securityInstances.put(0, path.getObjectInstanceId()); this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().put(0, path.getObjectInstanceId());
} else { } else {
log.error("Invalid bootstrapSecurityInstance by [{}]", path.getObjectInstanceId()); log.error("Invalid bootstrapSecurityInstance by [{}]", path.getObjectInstanceId());
} }
@ -164,8 +175,7 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
} }
} }
protected void findServerInstanceId(BootstrapReadResponse readResponse) { protected void findServerInstanceId(BootstrapReadResponse readResponse, String endpoint) {
this.serverInstances = new HashMap<>();
try { try {
((LwM2mObject) readResponse.getContent()).getInstances().values().forEach(instance -> { ((LwM2mObject) readResponse.getContent()).getInstances().values().forEach(instance -> {
var shId = OPAQUE.equals(instance.getResource(0).getType()) ? new BigInteger((byte[]) instance.getResource(0).getValue()).intValue() : instance.getResource(0).getValue(); var shId = OPAQUE.equals(instance.getResource(0).getType()) ? new BigInteger((byte[]) instance.getResource(0).getValue()).intValue() : instance.getResource(0).getValue();
@ -175,23 +185,22 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
} else { } else {
shortId = (int) shId; shortId = (int) shId;
} }
serverInstances.put(shortId, instance.getId()); this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().put(shortId, instance.getId());
}); });
} catch (Exception e) { } catch (Exception e) {
log.error("Failed find Server Instance Id. ", e); log.error("Failed find Server Instance Id. ", e);
} }
if (this.securityInstances != null && this.securityInstances.size() > 0 && this.serverInstances != null && this.serverInstances.size() > 0) {
this.findBootstrapServerId();
}
} }
protected void findBootstrapServerId() { protected Integer findBootstrapServerId(String endpoint) {
Map<Integer, Integer> filteredMap = this.serverInstances.entrySet() Integer bootstrapServerIdOld = null;
.stream().filter(x -> !this.securityInstances.containsKey(x.getKey())) Map<Integer, Integer> filteredMap = this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().entrySet()
.stream().filter(x -> !this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().containsKey(x.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (filteredMap.size() > 0) { if (filteredMap.size() > 0) {
this.bootstrapServerIdOld = filteredMap.keySet().stream().findFirst().get(); bootstrapServerIdOld = filteredMap.keySet().stream().findFirst().get();
} }
return bootstrapServerIdOld;
} }
public BootstrapConfigStore getStore() { public BootstrapConfigStore getStore() {
@ -213,7 +222,9 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
public List<BootstrapDownlinkRequest<? extends LwM2mResponse>> toRequests(BootstrapConfig bootstrapConfig, public List<BootstrapDownlinkRequest<? extends LwM2mResponse>> toRequests(BootstrapConfig bootstrapConfig,
ContentFormat contentFormat) { ContentFormat contentFormat,
Integer bootstrapServerIdOld,
String endpoint) {
List<BootstrapDownlinkRequest<? extends LwM2mResponse>> requests = new ArrayList<>(); List<BootstrapDownlinkRequest<? extends LwM2mResponse>> requests = new ArrayList<>();
Set<String> pathsDelete = new HashSet<>(); Set<String> pathsDelete = new HashSet<>();
List<BootstrapDownlinkRequest<? extends LwM2mResponse>> requestsWrite = new ArrayList<>(); List<BootstrapDownlinkRequest<? extends LwM2mResponse>> requestsWrite = new ArrayList<>();
@ -221,36 +232,38 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
boolean isLwServer = false; boolean isLwServer = false;
/** Map<serverId, InstanceId> */ /** Map<serverId, InstanceId> */
Map<Integer, Integer> instances = new HashMap<>(); Map<Integer, Integer> instances = new HashMap<>();
Integer bootstrapServerIdNew = null;
// handle security // handle security
int id = 0; int id = 0;
for (BootstrapConfig.ServerSecurity security : new TreeMap<>(bootstrapConfig.security).values()) { for (BootstrapConfig.ServerSecurity security : new TreeMap<>(bootstrapConfig.security).values()) {
if (security.bootstrapServer) { if (security.bootstrapServer) {
requestsWrite.add(toWriteRequest(this.securityInstances.get(0), security, contentFormat)); requestsWrite.add(toWriteRequest(this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().get(0), security, contentFormat));
isBsServer = true; isBsServer = true;
this.bootstrapServerIdNew = security.serverId; bootstrapServerIdNew = security.serverId;
instances.put(security.serverId, this.securityInstances.get(0)); instances.put(security.serverId, this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().get(0));
} else { } else {
if (id == this.securityInstances.get(0)) { if (id == this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().get(0)) {
id++; id++;
} }
requestsWrite.add(toWriteRequest(id, security, contentFormat)); requestsWrite.add(toWriteRequest(id, security, contentFormat));
instances.put(security.serverId, id); instances.put(security.serverId, id);
isLwServer = true; isLwServer = true;
if (!isBsServer && this.securityInstances.containsKey(security.serverId) && id != this.securityInstances.get(security.serverId)) { if (!isBsServer && this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().containsKey(security.serverId) &&
pathsDelete.add("/0/" + this.securityInstances.get(security.serverId)); id != this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().get(security.serverId)) {
pathsDelete.add("/0/" + this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().get(security.serverId));
} }
/** /**
* If there is an instance in the serverInstances with serverId which we replace in the securityInstances * If there is an instance in the serverInstances with serverId which we replace in the securityInstances
*/ */
// find serverId in securityInstances by id (instance) // find serverId in securityInstances by id (instance)
Integer serverIdOld = null; Integer serverIdOld = null;
for (Map.Entry<Integer, Integer> entry : this.securityInstances.entrySet()) { for (Map.Entry<Integer, Integer> entry : this.lwM2MBootstrapSessionClients.get(endpoint).getSecurityInstances().entrySet()) {
if (entry.getValue().equals(id)) { if (entry.getValue().equals(id)) {
serverIdOld = entry.getKey(); serverIdOld = entry.getKey();
} }
} }
if (!isBsServer && serverIdOld != null && this.serverInstances.containsKey(serverIdOld)) { if (!isBsServer && serverIdOld != null && this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().containsKey(serverIdOld)) {
pathsDelete.add("/1/" + this.serverInstances.get(serverIdOld)); pathsDelete.add("/1/" + this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().get(serverIdOld));
} }
id++; id++;
} }
@ -261,12 +274,13 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
requestsWrite.add(toWriteRequest(securityInstanceId, server.getValue(), contentFormat)); requestsWrite.add(toWriteRequest(securityInstanceId, server.getValue(), contentFormat));
if (!isBsServer) { if (!isBsServer) {
/** Delete instance if bootstrapServerIdNew not equals bootstrapServerIdOld or securityInstanceBsIdNew not equals serverInstanceBsIdOld */ /** Delete instance if bootstrapServerIdNew not equals bootstrapServerIdOld or securityInstanceBsIdNew not equals serverInstanceBsIdOld */
if (this.bootstrapServerIdNew != null && server.getValue().shortId == this.bootstrapServerIdNew && if (bootstrapServerIdNew != null && server.getValue().shortId == bootstrapServerIdNew &&
(this.bootstrapServerIdNew != this.bootstrapServerIdOld || securityInstanceId != this.serverInstances.get(this.bootstrapServerIdOld))) { (bootstrapServerIdNew != bootstrapServerIdOld || securityInstanceId != this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().get(bootstrapServerIdOld))) {
pathsDelete.add("/1/" + this.serverInstances.get(this.bootstrapServerIdOld)); pathsDelete.add("/1/" + this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().get(bootstrapServerIdOld));
/** Delete instance if serverIdNew is present in serverInstances and securityInstanceIdOld by serverIdNew not equals serverInstanceIdOld */ /** Delete instance if serverIdNew is present in serverInstances and securityInstanceIdOld by serverIdNew not equals serverInstanceIdOld */
} else if (this.serverInstances.containsKey(server.getValue().shortId) && securityInstanceId != this.serverInstances.get(server.getValue().shortId)) { } else if (this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().containsKey(server.getValue().shortId) &&
pathsDelete.add("/1/" + this.serverInstances.get(server.getValue().shortId)); securityInstanceId != this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().get(server.getValue().shortId)) {
pathsDelete.add("/1/" + this.lwM2MBootstrapSessionClients.get(endpoint).getServerInstances().get(server.getValue().shortId));
} }
} }
} }
@ -294,4 +308,24 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements BootstrapTaskProvi
this.supportedObjects.put(1, "1.1"); this.supportedObjects.put(1, "1.1");
this.supportedObjects.put(2, "1.0"); this.supportedObjects.put(2, "1.0");
} }
@Override
public void remove(String endpoint) {
writeLock.lock();
try {
this.lwM2MBootstrapSessionClients.remove(endpoint);
} finally {
writeLock.unlock();
}
}
@Override
public void put(String endpoint) throws InvalidConfigurationException {
writeLock.lock();
try {
this.lwM2MBootstrapSessionClients.put(endpoint, new LwM2MBootstrapClientInstanceIds());
} finally {
writeLock.unlock();
}
}
} }

26
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapTaskProvider.java

@ -0,0 +1,26 @@
/**
* Copyright © 2016-2022 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.transport.lwm2m.bootstrap.store;
import org.eclipse.leshan.server.bootstrap.BootstrapTaskProvider;
import org.eclipse.leshan.server.bootstrap.InvalidConfigurationException;
public interface LwM2MBootstrapTaskProvider extends BootstrapTaskProvider {
void put(String endpoint) throws InvalidConfigurationException;
void remove(String endpoint);
}
Loading…
Cancel
Save