Introduced the FlightZone concept (inbound and outbound) and separated logic of storage system.
This commit is contained in:
@@ -1,4 +1,6 @@
|
|||||||
Version 0.10:
|
Version 0.10:
|
||||||
|
Separated in memory and MapDB storage implementations
|
||||||
|
Cleanly separated inflight part (inbound and outbound)
|
||||||
|
|
||||||
|
|
||||||
Version 0.9:
|
Version 0.9:
|
||||||
|
|||||||
+35
-29
@@ -1,29 +1,35 @@
|
|||||||
|
|
||||||
package io.moquette.interception.messages;
|
package io.moquette.interception.messages;
|
||||||
|
|
||||||
import static io.moquette.spi.IMessagesStore.StoredMessage;
|
import static io.moquette.spi.IMessagesStore.StoredMessage;
|
||||||
|
|
||||||
public class InterceptAcknowledgedMessage implements InterceptMessage {
|
public class InterceptAcknowledgedMessage implements InterceptMessage {
|
||||||
|
|
||||||
final private StoredMessage msg;
|
final private StoredMessage msg;
|
||||||
private final String username;
|
private final String username;
|
||||||
private final String topic;
|
private final String topic;
|
||||||
|
private final int packetID;
|
||||||
public InterceptAcknowledgedMessage(final StoredMessage msg, final String topic, final String username) {
|
|
||||||
this.msg = msg;
|
public InterceptAcknowledgedMessage(StoredMessage msg, String topic, String username, int packetID) {
|
||||||
this.username = username;
|
this.msg = msg;
|
||||||
this.topic = topic;
|
this.username = username;
|
||||||
}
|
this.topic = topic;
|
||||||
|
this.packetID = packetID;
|
||||||
public StoredMessage getMsg() {
|
}
|
||||||
return msg;
|
|
||||||
}
|
public StoredMessage getMsg() {
|
||||||
|
return msg;
|
||||||
public String getUsername() {
|
}
|
||||||
return username;
|
|
||||||
}
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
public String getTopic() {
|
}
|
||||||
return topic;
|
|
||||||
}
|
public String getTopic() {
|
||||||
}
|
return topic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPacketID() {
|
||||||
|
return packetID;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ public class MemoryMessagesStore implements IMessagesStore {
|
|||||||
|
|
||||||
private Map<Topic, MessageGUID> m_retainedStore = new HashMap<>();
|
private Map<Topic, MessageGUID> m_retainedStore = new HashMap<>();
|
||||||
private Map<MessageGUID, StoredMessage> m_persistentMessageStore = new HashMap<>();
|
private Map<MessageGUID, StoredMessage> m_persistentMessageStore = new HashMap<>();
|
||||||
private Map<String, Map<Integer, MessageGUID>> m_messageToGuids = new HashMap<>();
|
|
||||||
|
|
||||||
MemoryMessagesStore() {
|
MemoryMessagesStore() {
|
||||||
}
|
}
|
||||||
@@ -72,21 +71,13 @@ public class MemoryMessagesStore implements IMessagesStore {
|
|||||||
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
|
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
|
||||||
storedMessage.setGuid(guid);
|
storedMessage.setGuid(guid);
|
||||||
m_persistentMessageStore.put(guid, storedMessage);
|
m_persistentMessageStore.put(guid, storedMessage);
|
||||||
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
|
|
||||||
Map<Integer, MessageGUID> guids = defaultGet(m_messageToGuids, storedMessage.getClientID(), emptyGuids);
|
|
||||||
guids.put(storedMessage.getMessageID(), guid);
|
|
||||||
m_messageToGuids.put(storedMessage.getClientID(), guids);
|
|
||||||
return guid;
|
return guid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void dropMessagesInSession(String clientID) {
|
public void dropInFlightMessagesInSession(Collection<MessageGUID> pendingAckMessages) {
|
||||||
Map<Integer, MessageGUID> messageGUIDMap = m_messageToGuids.get(clientID);
|
|
||||||
if (messageGUIDMap == null || messageGUIDMap.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
//remove all guids from retained
|
//remove all guids from retained
|
||||||
Collection<MessageGUID> messagesToRemove = new HashSet<>(messageGUIDMap.values());
|
Collection<MessageGUID> messagesToRemove = new HashSet<>(pendingAckMessages);
|
||||||
messagesToRemove.removeAll(m_retainedStore.values());
|
messagesToRemove.removeAll(m_retainedStore.values());
|
||||||
|
|
||||||
for (MessageGUID guid : messagesToRemove) {
|
for (MessageGUID guid : messagesToRemove) {
|
||||||
@@ -103,20 +94,4 @@ public class MemoryMessagesStore implements IMessagesStore {
|
|||||||
public void cleanRetained(Topic topic) {
|
public void cleanRetained(Topic topic) {
|
||||||
m_retainedStore.remove(topic);
|
m_retainedStore.remove(topic);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getPendingPublishMessages(String clientID) {
|
|
||||||
Map<Integer, MessageGUID> messageToGuids = m_messageToGuids.get(clientID);
|
|
||||||
if (messageToGuids == null)
|
|
||||||
return 0;
|
|
||||||
else
|
|
||||||
return messageToGuids.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public MessageGUID mapToGuid(String clientID, int messageID) {
|
|
||||||
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
|
|
||||||
Map<Integer, MessageGUID> guids = Utils.defaultGet(m_messageToGuids, clientID, emptyGuids);
|
|
||||||
return guids.get(messageID);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ import java.util.*;
|
|||||||
import java.util.concurrent.ArrayBlockingQueue;
|
import java.util.concurrent.ArrayBlockingQueue;
|
||||||
import java.util.concurrent.BlockingQueue;
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
|
||||||
|
import static io.moquette.spi.impl.Utils.defaultGet;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author andrea
|
* @author andrea
|
||||||
@@ -45,12 +47,15 @@ public class MemorySessionStore implements ISessionsStore {
|
|||||||
|
|
||||||
// maps clientID->[MessageId -> guid]
|
// maps clientID->[MessageId -> guid]
|
||||||
private Map<String, Map<Integer, MessageGUID>> m_inflightStore = new HashMap<>();
|
private Map<String, Map<Integer, MessageGUID>> m_inflightStore = new HashMap<>();
|
||||||
// private Map<String, Set<Integer>> m_inflightIDs = new HashMap<>();
|
|
||||||
// maps clientID->BlockingQueue
|
// maps clientID->BlockingQueue
|
||||||
private Map<String, BlockingQueue<StoredMessage>> queues = new HashMap<>();
|
private Map<String, BlockingQueue<StoredMessage>> queues = new HashMap<>();
|
||||||
// maps clientID->[MessageId -> guid]
|
// maps clientID->[MessageId -> guid]
|
||||||
private Map<String, Map<Integer, MessageGUID>> m_secondPhaseStore = new HashMap<>();
|
private Map<String, Map<Integer, MessageGUID>> m_secondPhaseStore = new HashMap<>();
|
||||||
|
|
||||||
|
private Map<String, Map<Integer, MessageGUID>> outboundFlightMessageToGuid = new HashMap<>();
|
||||||
|
|
||||||
|
private Map<String, Map<Integer, MessageGUID>> inboundFlightMessageToGuid = new HashMap<>();
|
||||||
|
|
||||||
private final IMessagesStore m_messagesStore;
|
private final IMessagesStore m_messagesStore;
|
||||||
|
|
||||||
public MemorySessionStore(IMessagesStore messagesStore) {
|
public MemorySessionStore(IMessagesStore messagesStore) {
|
||||||
@@ -176,6 +181,11 @@ public class MemorySessionStore implements ISessionsStore {
|
|||||||
}
|
}
|
||||||
m.put(messageID, guid);
|
m.put(messageID, guid);
|
||||||
this.m_inflightStore.put(clientID, m);
|
this.m_inflightStore.put(clientID, m);
|
||||||
|
|
||||||
|
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
|
||||||
|
Map<Integer, MessageGUID> guids = defaultGet(outboundFlightMessageToGuid, clientID, emptyGuids);
|
||||||
|
guids.put(messageID, guid);
|
||||||
|
outboundFlightMessageToGuid.put(clientID, guids);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -251,9 +261,25 @@ public class MemorySessionStore implements ISessionsStore {
|
|||||||
return inflightMessages.size();
|
return inflightMessages.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StoredMessage inboundInflight(String clientID, int messageID) {
|
||||||
|
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
|
||||||
|
Map<Integer, MessageGUID> guids = Utils.defaultGet(inboundFlightMessageToGuid, clientID, emptyGuids);
|
||||||
|
final MessageGUID guid = guids.get(messageID);
|
||||||
|
return m_messagesStore.getMessageByGuid(guid);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void markAsInboundInflight(String clientID, int messageID, MessageGUID guid) {
|
||||||
|
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
|
||||||
|
Map<Integer, MessageGUID> guids = Utils.defaultGet(inboundFlightMessageToGuid, clientID, emptyGuids);
|
||||||
|
guids.put(messageID, guid);
|
||||||
|
inboundFlightMessageToGuid.put(clientID, guids);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getPendingPublishMessagesNo(String clientID) {
|
public int getPendingPublishMessagesNo(String clientID) {
|
||||||
return m_messagesStore.getPendingPublishMessages(clientID);
|
return queues.get(clientID).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -265,4 +291,13 @@ public class MemorySessionStore implements ISessionsStore {
|
|||||||
return pendingAcks.size();
|
return pendingAcks.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<MessageGUID> pendingAck(String clientID) {
|
||||||
|
Map<Integer, MessageGUID> messageGUIDMap = outboundFlightMessageToGuid.get(clientID);
|
||||||
|
if (messageGUIDMap == null || messageGUIDMap.isEmpty()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ArrayList<>(messageGUIDMap.values());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,16 +43,10 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
|||||||
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
|
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
|
||||||
if (descriptor == null) {
|
if (descriptor == null) {
|
||||||
if (messageID != null) {
|
if (messageID != null) {
|
||||||
LOG.error(
|
LOG.error("Client has just disconnected. {} message could not be sent. CId=<{}>, messageId={}",
|
||||||
"Client has just disconnected. The {} message could not be sent. CId=<{}>, messageId={}",
|
messageType, clientID, messageID);
|
||||||
messageType,
|
|
||||||
clientID,
|
|
||||||
messageID);
|
|
||||||
} else {
|
} else {
|
||||||
LOG.error(
|
LOG.error("Client has just disconnected. {} could not be sent. CId=<{}>", messageType, clientID);
|
||||||
"Client has just disconnected. The {} could not be sent. CId=<{}>",
|
|
||||||
messageType,
|
|
||||||
clientID);
|
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
* If the client has just disconnected, its connection descriptor will be null. We
|
* If the client has just disconnected, its connection descriptor will be null. We
|
||||||
@@ -103,11 +97,8 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
|||||||
public boolean closeConnection(String clientID, boolean closeImmediately) {
|
public boolean closeConnection(String clientID, boolean closeImmediately) {
|
||||||
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
|
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
|
||||||
if (descriptor == null) {
|
if (descriptor == null) {
|
||||||
LOG.error(
|
LOG.error("Connection descriptor doesn't exist. MQTT connection cannot be closed. CId=<{}>, " +
|
||||||
"The connection descriptor doesn't exist. "
|
"closeImmediately={}", clientID, closeImmediately);
|
||||||
+ "The MQTT connection cannot be closed. CId=<{}>, closeImmediately = {}.",
|
|
||||||
clientID,
|
|
||||||
closeImmediately);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (closeImmediately) {
|
if (closeImmediately) {
|
||||||
@@ -123,7 +114,7 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
|||||||
LOG.info("Retrieving status of session. CId=<{}>", clientID);
|
LOG.info("Retrieving status of session. CId=<{}>", clientID);
|
||||||
ClientSession session = sessionsStore.sessionForClient(clientID);
|
ClientSession session = sessionsStore.sessionForClient(clientID);
|
||||||
if (session == null) {
|
if (session == null) {
|
||||||
LOG.error("The given MQTT client ID doesn't have an associated session. CId=<{}>", clientID);
|
LOG.error("MQTT client ID doesn't have an associated session. CId=<{}>", clientID);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return buildMqttSession(session);
|
return buildMqttSession(session);
|
||||||
@@ -143,12 +134,8 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
|||||||
MqttSession result = new MqttSession();
|
MqttSession result = new MqttSession();
|
||||||
Collection<MqttSubscription> mqttSubscriptions = new ArrayList<>();
|
Collection<MqttSubscription> mqttSubscriptions = new ArrayList<>();
|
||||||
for (Subscription subscription : session.getSubscriptions()) {
|
for (Subscription subscription : session.getSubscriptions()) {
|
||||||
mqttSubscriptions.add(
|
mqttSubscriptions.add(new MqttSubscription(subscription.getRequestedQos().toString(),
|
||||||
new MqttSubscription(
|
subscription.getClientId(), subscription.getTopicFilter().toString(), subscription.isActive()));
|
||||||
subscription.getRequestedQos().toString(),
|
|
||||||
subscription.getClientId(),
|
|
||||||
subscription.getTopicFilter().toString(),
|
|
||||||
subscription.isActive()));
|
|
||||||
}
|
}
|
||||||
result.setActiveSubscriptions(mqttSubscriptions);
|
result.setActiveSubscriptions(mqttSubscriptions);
|
||||||
result.setCleanSession(session.isCleanSession());
|
result.setCleanSession(session.isCleanSession());
|
||||||
@@ -157,19 +144,14 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
|||||||
result.setConnectionEstablished(true);
|
result.setConnectionEstablished(true);
|
||||||
BytesMetrics bytesMetrics = descriptor.getBytesMetrics();
|
BytesMetrics bytesMetrics = descriptor.getBytesMetrics();
|
||||||
MessageMetrics messageMetrics = descriptor.getMessageMetrics();
|
MessageMetrics messageMetrics = descriptor.getMessageMetrics();
|
||||||
result.setConnectionMetrics(
|
result.setConnectionMetrics(new MqttConnectionMetrics(bytesMetrics.readBytes(), bytesMetrics.wroteBytes(),
|
||||||
new MqttConnectionMetrics(
|
messageMetrics.messagesRead(), messageMetrics.messagesWrote()));
|
||||||
bytesMetrics.readBytes(),
|
|
||||||
bytesMetrics.wroteBytes(),
|
|
||||||
messageMetrics.messagesRead(),
|
|
||||||
messageMetrics.messagesWrote()));
|
|
||||||
} else {
|
} else {
|
||||||
result.setConnectionEstablished(false);
|
result.setConnectionEstablished(false);
|
||||||
}
|
}
|
||||||
result.setPendingPublishMessagesNo(session.getPendingPublishMessagesNo());
|
result.setPendingPublishMessagesNo(session.getPendingPublishMessagesNo());
|
||||||
result.setSecondPhaseAckPendingMessages(session.getSecondPhaseAckPendingMessages());
|
result.setSecondPhaseAckPendingMessages(session.getSecondPhaseAckPendingMessages());
|
||||||
result.setInflightMessages(session.getInflightMessagesNo());
|
result.setInflightMessages(session.getInflightMessagesNo());
|
||||||
LOG.info("The status of the session has been retrieved successfully. CId=<{}>", session.clientID);
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ public class Server {
|
|||||||
*/
|
*/
|
||||||
public void startServer() throws IOException {
|
public void startServer() throws IOException {
|
||||||
File defaultConfigurationFile = defaultConfigFile();
|
File defaultConfigurationFile = defaultConfigFile();
|
||||||
LOG.info("Starting Moquette server. Configuration file path = {}.", defaultConfigurationFile.getAbsolutePath());
|
LOG.info("Starting Moquette server. Configuration file path={}", defaultConfigurationFile.getAbsolutePath());
|
||||||
IResourceLoader filesystemLoader = new FileResourceLoader(defaultConfigurationFile);
|
IResourceLoader filesystemLoader = new FileResourceLoader(defaultConfigurationFile);
|
||||||
final IConfig config = new ResourceLoaderConfig(filesystemLoader);
|
final IConfig config = new ResourceLoaderConfig(filesystemLoader);
|
||||||
startServer(config);
|
startServer(config);
|
||||||
@@ -115,7 +115,7 @@ public class Server {
|
|||||||
* in case of any IO Error.
|
* in case of any IO Error.
|
||||||
*/
|
*/
|
||||||
public void startServer(File configFile) throws IOException {
|
public void startServer(File configFile) throws IOException {
|
||||||
LOG.info("Starting Moquette server. Configuration file path = {}.", configFile.getAbsolutePath());
|
LOG.info("Starting Moquette server. Configuration file path={}", configFile.getAbsolutePath());
|
||||||
IResourceLoader filesystemLoader = new FileResourceLoader(configFile);
|
IResourceLoader filesystemLoader = new FileResourceLoader(configFile);
|
||||||
final IConfig config = new ResourceLoaderConfig(filesystemLoader);
|
final IConfig config = new ResourceLoaderConfig(filesystemLoader);
|
||||||
startServer(config);
|
startServer(config);
|
||||||
@@ -136,7 +136,7 @@ public class Server {
|
|||||||
* in case of any IO Error.
|
* in case of any IO Error.
|
||||||
*/
|
*/
|
||||||
public void startServer(Properties configProps) throws IOException {
|
public void startServer(Properties configProps) throws IOException {
|
||||||
LOG.info("Starting Moquette server using properties object...");
|
LOG.info("Starting Moquette server using properties object");
|
||||||
final IConfig config = new MemoryConfig(configProps);
|
final IConfig config = new MemoryConfig(configProps);
|
||||||
startServer(config);
|
startServer(config);
|
||||||
}
|
}
|
||||||
@@ -166,7 +166,7 @@ public class Server {
|
|||||||
* in case of any IO Error.
|
* in case of any IO Error.
|
||||||
*/
|
*/
|
||||||
public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException {
|
public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException {
|
||||||
LOG.info("Starting moquette server using IConfig instance and intercept handlers...");
|
LOG.info("Starting moquette server using IConfig instance and intercept handlers");
|
||||||
startServer(config, handlers, null, null, null);
|
startServer(config, handlers, null, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +175,7 @@ public class Server {
|
|||||||
if (handlers == null) {
|
if (handlers == null) {
|
||||||
handlers = Collections.emptyList();
|
handlers = Collections.emptyList();
|
||||||
}
|
}
|
||||||
LOG.info("Starting Moquette Server. MQTT message interceptors = {}.", getInterceptorIds(handlers));
|
LOG.info("Starting Moquette Server. MQTT message interceptors={}", getInterceptorIds(handlers));
|
||||||
|
|
||||||
scheduler = Executors.newScheduledThreadPool(1);
|
scheduler = Executors.newScheduledThreadPool(1);
|
||||||
|
|
||||||
@@ -184,30 +184,28 @@ public class Server {
|
|||||||
config.setProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, handlerProp);
|
config.setProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, handlerProp);
|
||||||
}
|
}
|
||||||
configureCluster(config);
|
configureCluster(config);
|
||||||
LOG.info(
|
final String persistencePath = config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME);
|
||||||
"Configuring Using persistent store file. Path = {}.",
|
LOG.info("Configuring Using persistent store file, path={}", persistencePath);
|
||||||
config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME));
|
|
||||||
m_processorBootstrapper = new ProtocolProcessorBootstrapper();
|
m_processorBootstrapper = new ProtocolProcessorBootstrapper();
|
||||||
LOG.info("Initializing MQTT protocol processor...");
|
final ProtocolProcessor processor = m_processorBootstrapper.init(config, handlers, authenticator, authorizator,
|
||||||
final ProtocolProcessor processor = m_processorBootstrapper
|
this);
|
||||||
.init(config, handlers, authenticator, authorizator, this);
|
LOG.info("Initialized MQTT protocol processor");
|
||||||
|
|
||||||
if (sslCtxCreator == null) {
|
if (sslCtxCreator == null) {
|
||||||
LOG.warn("Using default SSL context creator...");
|
LOG.warn("Using default SSL context creator");
|
||||||
sslCtxCreator = new DefaultMoquetteSslContextCreator(config);
|
sslCtxCreator = new DefaultMoquetteSslContextCreator(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG.info("Binding server to the configured ports...");
|
LOG.info("Binding server to the configured ports");
|
||||||
m_acceptor = new NettyAcceptor();
|
m_acceptor = new NettyAcceptor();
|
||||||
m_acceptor.initialize(processor, config, sslCtxCreator);
|
m_acceptor.initialize(processor, config, sslCtxCreator);
|
||||||
m_processor = processor;
|
m_processor = processor;
|
||||||
|
|
||||||
LOG.info("The Moquette server has been initialized successfully.");
|
LOG.info("Moquette server has been initialized successfully");
|
||||||
m_initialized = true;
|
m_initialized = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void configureCluster(IConfig config) throws FileNotFoundException {
|
private void configureCluster(IConfig config) throws FileNotFoundException {
|
||||||
LOG.info("Configuring embedded Hazelcast instance...");
|
LOG.info("Configuring embedded Hazelcast instance");
|
||||||
String interceptHandlerClassname = config.getProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME);
|
String interceptHandlerClassname = config.getProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME);
|
||||||
if (interceptHandlerClassname == null || !HZ_INTERCEPT_HANDLER.equals(interceptHandlerClassname)) {
|
if (interceptHandlerClassname == null || !HZ_INTERCEPT_HANDLER.equals(interceptHandlerClassname)) {
|
||||||
LOG.info("There are no Hazelcast intercept handlers. The server won't start a Hazelcast instance.");
|
LOG.info("There are no Hazelcast intercept handlers. The server won't start a Hazelcast instance.");
|
||||||
@@ -219,17 +217,17 @@ public class Server {
|
|||||||
Config hzconfig = isHzConfigOnClasspath
|
Config hzconfig = isHzConfigOnClasspath
|
||||||
? new ClasspathXmlConfig(hzConfigPath)
|
? new ClasspathXmlConfig(hzConfigPath)
|
||||||
: new FileSystemXmlConfig(hzConfigPath);
|
: new FileSystemXmlConfig(hzConfigPath);
|
||||||
LOG.info("Starting Hazelcast instance. ConfigurationFile = {}.", hzconfig);
|
LOG.info("Starting Hazelcast instance. ConfigurationFile={}", hzconfig);
|
||||||
hazelcastInstance = Hazelcast.newHazelcastInstance(hzconfig);
|
hazelcastInstance = Hazelcast.newHazelcastInstance(hzconfig);
|
||||||
} else {
|
} else {
|
||||||
LOG.info("Starting Hazelcast instance with default configuration.");
|
LOG.info("Starting Hazelcast instance with default configuration");
|
||||||
hazelcastInstance = Hazelcast.newHazelcastInstance();
|
hazelcastInstance = Hazelcast.newHazelcastInstance();
|
||||||
}
|
}
|
||||||
listenOnHazelCastMsg();
|
listenOnHazelCastMsg();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void listenOnHazelCastMsg() {
|
private void listenOnHazelCastMsg() {
|
||||||
LOG.info("Subscribing to Hazelcast topic. TopicName = {}.", "moquette");
|
LOG.info("Subscribing to Hazelcast topic. TopicName={}", "moquette");
|
||||||
HazelcastInstance hz = getHazelcastInstance();
|
HazelcastInstance hz = getHazelcastInstance();
|
||||||
ITopic<HazelcastMsg> topic = hz.getTopic("moquette");
|
ITopic<HazelcastMsg> topic = hz.getTopic("moquette");
|
||||||
topic.addMessageListener(new HazelcastListener(this));
|
topic.addMessageListener(new HazelcastListener(this));
|
||||||
@@ -253,34 +251,32 @@ public class Server {
|
|||||||
public void internalPublish(MqttPublishMessage msg, final String clientId) {
|
public void internalPublish(MqttPublishMessage msg, final String clientId) {
|
||||||
final int messageID = msg.variableHeader().messageId();
|
final int messageID = msg.variableHeader().messageId();
|
||||||
if (!m_initialized) {
|
if (!m_initialized) {
|
||||||
LOG.error(
|
LOG.error("Moquette is not started, internal message cannot be published. CId={}, messageId={}", clientId,
|
||||||
"The server is not started. The message cannot be published. MqttClientId = {}, messageId = {}",
|
messageID);
|
||||||
clientId,
|
|
||||||
messageID);
|
|
||||||
throw new IllegalStateException("Can't publish on a server is not yet started");
|
throw new IllegalStateException("Can't publish on a server is not yet started");
|
||||||
}
|
}
|
||||||
LOG.debug("Publishing message. MqttClientId = {}, messageId = {}", clientId, messageID);
|
LOG.debug("Publishing message. CId={}, messageId={}", clientId, messageID);
|
||||||
m_processor.internalPublish(msg, clientId);
|
m_processor.internalPublish(msg, clientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stopServer() {
|
public void stopServer() {
|
||||||
LOG.info("Unbinding server from the configured ports...");
|
LOG.info("Unbinding server from the configured ports");
|
||||||
m_acceptor.close();
|
m_acceptor.close();
|
||||||
LOG.info("Stopping MQTT protocol processor...");
|
LOG.trace("Stopping MQTT protocol processor");
|
||||||
m_processorBootstrapper.shutdown();
|
m_processorBootstrapper.shutdown();
|
||||||
m_initialized = false;
|
m_initialized = false;
|
||||||
if (hazelcastInstance != null) {
|
if (hazelcastInstance != null) {
|
||||||
LOG.info("Stopping embedded Hazelcast instance...");
|
LOG.trace("Stopping embedded Hazelcast instance");
|
||||||
try {
|
try {
|
||||||
hazelcastInstance.shutdown();
|
hazelcastInstance.shutdown();
|
||||||
} catch (HazelcastInstanceNotActiveException e) {
|
} catch (HazelcastInstanceNotActiveException e) {
|
||||||
LOG.warn("The embedded Hazelcast instance is already shut down.");
|
LOG.warn("embedded Hazelcast instance is already shut down.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
|
|
||||||
LOG.info("The Moquette server has been stopped.");
|
LOG.info("Moquette server has been stopped.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -304,12 +300,11 @@ public class Server {
|
|||||||
*/
|
*/
|
||||||
public void addInterceptHandler(InterceptHandler interceptHandler) {
|
public void addInterceptHandler(InterceptHandler interceptHandler) {
|
||||||
if (!m_initialized) {
|
if (!m_initialized) {
|
||||||
LOG.error(
|
LOG.error("Moquette is not started, MQTT message interceptor cannot be added. InterceptorId={}",
|
||||||
"The server is not started. The MQTT message interceptor cannot be added. InterceptorId = {}.",
|
interceptHandler.getID());
|
||||||
interceptHandler.getID());
|
|
||||||
throw new IllegalStateException("Can't register interceptors on a server that is not yet started");
|
throw new IllegalStateException("Can't register interceptors on a server that is not yet started");
|
||||||
}
|
}
|
||||||
LOG.info("Adding MQTT message interceptor. InterceptorId = {}.", interceptHandler.getID());
|
LOG.info("Adding MQTT message interceptor. InterceptorId={}", interceptHandler.getID());
|
||||||
m_processor.addInterceptHandler(interceptHandler);
|
m_processor.addInterceptHandler(interceptHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -321,12 +316,11 @@ public class Server {
|
|||||||
*/
|
*/
|
||||||
public void removeInterceptHandler(InterceptHandler interceptHandler) {
|
public void removeInterceptHandler(InterceptHandler interceptHandler) {
|
||||||
if (!m_initialized) {
|
if (!m_initialized) {
|
||||||
LOG.error(
|
LOG.error("Moquette is not started, MQTT message interceptor cannot be removed. InterceptorId={}",
|
||||||
"The server is not started. The MQTT message interceptor cannot be removed. InterceptorId = {}.",
|
interceptHandler.getID());
|
||||||
interceptHandler.getID());
|
|
||||||
throw new IllegalStateException("Can't deregister interceptors from a server that is not yet started");
|
throw new IllegalStateException("Can't deregister interceptors from a server that is not yet started");
|
||||||
}
|
}
|
||||||
LOG.info("Removing MQTT message interceptor. InterceptorId = {}.", interceptHandler.getID());
|
LOG.info("Removing MQTT message interceptor. InterceptorId={}", interceptHandler.getID());
|
||||||
m_processor.removeInterceptHandler(interceptHandler);
|
m_processor.removeInterceptHandler(interceptHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void initFactory(String host, int port, String protocol, final PipelineInitializer pipeliner) {
|
private void initFactory(String host, int port, String protocol, final PipelineInitializer pipeliner) {
|
||||||
LOG.info("Initializing server. Protocol = {}.", protocol);
|
LOG.info("Initializing server. Protocol={}", protocol);
|
||||||
ServerBootstrap b = new ServerBootstrap();
|
ServerBootstrap b = new ServerBootstrap();
|
||||||
b.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
|
b.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
|
||||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||||
@@ -157,26 +157,24 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
.option(ChannelOption.TCP_NODELAY, nettyTcpNodelay)
|
.option(ChannelOption.TCP_NODELAY, nettyTcpNodelay)
|
||||||
.childOption(ChannelOption.SO_KEEPALIVE, nettySoKeepalive);
|
.childOption(ChannelOption.SO_KEEPALIVE, nettySoKeepalive);
|
||||||
try {
|
try {
|
||||||
LOG.info("Binding server. Protocol = {}, host = {}, port = {}.", host, port);
|
LOG.info("Binding server. host={}, port={}", host, port);
|
||||||
// Bind and start to accept incoming connections.
|
// Bind and start to accept incoming connections.
|
||||||
ChannelFuture f = b.bind(host, port);
|
ChannelFuture f = b.bind(host, port);
|
||||||
LOG.info("The server has been binded. Protocol = {}, host = {}, port = {}", host, port);
|
LOG.info("Server has been bound. host={}, port={}", host, port);
|
||||||
f.sync();
|
f.sync();
|
||||||
} catch (InterruptedException ex) {
|
} catch (InterruptedException ex) {
|
||||||
LOG.error("An interruptedException was caught while initializing server. Protocol = {}.", protocol, ex);
|
LOG.error("An interruptedException was caught while initializing server. Protocol={}", protocol, ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initializePlainTCPTransport(final NettyMQTTHandler handler, IConfig props) throws IOException {
|
private void initializePlainTCPTransport(final NettyMQTTHandler handler, IConfig props) throws IOException {
|
||||||
LOG.info("Configuring TCP MQTT transport...");
|
LOG.info("Configuring TCP MQTT transport");
|
||||||
final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
|
final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
|
||||||
String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
|
String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
|
||||||
String tcpPortProp = props.getProperty(PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
String tcpPortProp = props.getProperty(PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
if (DISABLED_PORT_BIND.equals(tcpPortProp)) {
|
if (DISABLED_PORT_BIND.equals(tcpPortProp)) {
|
||||||
LOG.info(
|
LOG.info("Property {} has been set to {}. TCP MQTT will be disabled", BrokerConstants.PORT_PROPERTY_NAME,
|
||||||
"The property {} has been setted to {}. TCP MQTT will be disabled.",
|
DISABLED_PORT_BIND);
|
||||||
BrokerConstants.PORT_PROPERTY_NAME,
|
|
||||||
DISABLED_PORT_BIND);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int port = Integer.parseInt(tcpPortProp);
|
int port = Integer.parseInt(tcpPortProp);
|
||||||
@@ -198,14 +196,12 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void initializeWebSocketTransport(final NettyMQTTHandler handler, IConfig props) throws IOException {
|
private void initializeWebSocketTransport(final NettyMQTTHandler handler, IConfig props) throws IOException {
|
||||||
LOG.info("Configuring Websocket MQTT transport...");
|
LOG.info("Configuring Websocket MQTT transport");
|
||||||
String webSocketPortProp = props.getProperty(WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
String webSocketPortProp = props.getProperty(WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
if (DISABLED_PORT_BIND.equals(webSocketPortProp)) {
|
if (DISABLED_PORT_BIND.equals(webSocketPortProp)) {
|
||||||
// Do nothing no WebSocket configured
|
// Do nothing no WebSocket configured
|
||||||
LOG.info(
|
LOG.info("Property {} has been setted to {}. Websocket MQTT will be disabled",
|
||||||
"The property {} has been setted to {}. Websocket MQTT will be disabled.",
|
BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
|
|
||||||
DISABLED_PORT_BIND);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int port = Integer.parseInt(webSocketPortProp);
|
int port = Integer.parseInt(webSocketPortProp);
|
||||||
@@ -219,8 +215,7 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
void init(ChannelPipeline pipeline) {
|
void init(ChannelPipeline pipeline) {
|
||||||
pipeline.addLast(new HttpServerCodec());
|
pipeline.addLast(new HttpServerCodec());
|
||||||
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
|
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
|
||||||
pipeline.addLast(
|
pipeline.addLast("webSocketHandler",
|
||||||
"webSocketHandler",
|
|
||||||
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
||||||
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
|
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
|
||||||
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
|
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
|
||||||
@@ -238,14 +233,12 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
|
|
||||||
private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
|
private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
LOG.info("Configuring SSL MQTT transport...");
|
LOG.info("Configuring SSL MQTT transport");
|
||||||
String sslPortProp = props.getProperty(SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
String sslPortProp = props.getProperty(SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
if (DISABLED_PORT_BIND.equals(sslPortProp)) {
|
if (DISABLED_PORT_BIND.equals(sslPortProp)) {
|
||||||
// Do nothing no SSL configured
|
// Do nothing no SSL configured
|
||||||
LOG.info(
|
LOG.info("Property {} has been set to {}. SSL MQTT will be disabled",
|
||||||
"The property {} has been setted to {}. SSL MQTT will be disabled.",
|
BrokerConstants.SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
BrokerConstants.SSL_PORT_PROPERTY_NAME,
|
|
||||||
DISABLED_PORT_BIND);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,14 +269,12 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
|
|
||||||
private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
|
private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
LOG.info("Configuring secure websocket MQTT transport...");
|
LOG.info("Configuring secure websocket MQTT transport");
|
||||||
String sslPortProp = props.getProperty(WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
String sslPortProp = props.getProperty(WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
if (DISABLED_PORT_BIND.equals(sslPortProp)) {
|
if (DISABLED_PORT_BIND.equals(sslPortProp)) {
|
||||||
// Do nothing no SSL configured
|
// Do nothing no SSL configured
|
||||||
LOG.info(
|
LOG.info("Property {} has been set to {}. Secure websocket MQTT will be disabled",
|
||||||
"The property {} has been setted to {}. Secure websocket MQTT will be disabled.",
|
BrokerConstants.WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||||
BrokerConstants.WSS_PORT_PROPERTY_NAME,
|
|
||||||
DISABLED_PORT_BIND);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int sslPort = Integer.parseInt(sslPortProp);
|
int sslPort = Integer.parseInt(sslPortProp);
|
||||||
@@ -299,8 +290,7 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
pipeline.addLast("httpEncoder", new HttpResponseEncoder());
|
pipeline.addLast("httpEncoder", new HttpResponseEncoder());
|
||||||
pipeline.addLast("httpDecoder", new HttpRequestDecoder());
|
pipeline.addLast("httpDecoder", new HttpRequestDecoder());
|
||||||
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
|
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
|
||||||
pipeline.addLast(
|
pipeline.addLast("webSocketHandler",
|
||||||
"webSocketHandler",
|
|
||||||
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
||||||
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
|
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
|
||||||
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
|
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
|
||||||
@@ -319,7 +309,7 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
public void close() {
|
public void close() {
|
||||||
LOG.info("Closing Netty acceptor...");
|
LOG.info("Closing Netty acceptor...");
|
||||||
if (m_workerGroup == null || m_bossGroup == null) {
|
if (m_workerGroup == null || m_bossGroup == null) {
|
||||||
LOG.error("The Netty acceptor is not initialized.");
|
LOG.error("Netty acceptor is not initialized");
|
||||||
throw new IllegalStateException("Invoked close on an Acceptor that wasn't initialized");
|
throw new IllegalStateException("Invoked close on an Acceptor that wasn't initialized");
|
||||||
}
|
}
|
||||||
Future<?> workerWaiter = m_workerGroup.shutdownGracefully();
|
Future<?> workerWaiter = m_workerGroup.shutdownGracefully();
|
||||||
@@ -349,17 +339,13 @@ public class NettyAcceptor implements ServerAcceptor {
|
|||||||
|
|
||||||
LOG.info("Collecting message metrics...");
|
LOG.info("Collecting message metrics...");
|
||||||
MessageMetrics metrics = m_metricsCollector.computeMetrics();
|
MessageMetrics metrics = m_metricsCollector.computeMetrics();
|
||||||
LOG.info(
|
LOG.info("Metrics have been collected. Read messages={}, written messages={}", metrics.messagesRead(),
|
||||||
"The metrics have been collected. Read messages = {}, written messages = {}.",
|
metrics.messagesWrote());
|
||||||
metrics.messagesRead(),
|
|
||||||
metrics.messagesWrote());
|
|
||||||
|
|
||||||
LOG.info("Collecting bytes metrics...");
|
LOG.info("Collecting bytes metrics...");
|
||||||
BytesMetrics bytesMetrics = m_bytesMetricsCollector.computeMetrics();
|
BytesMetrics bytesMetrics = m_bytesMetricsCollector.computeMetrics();
|
||||||
LOG.info(
|
LOG.info("Bytes metrics have been collected. Read bytes={}, written bytes={}", bytesMetrics.readBytes(),
|
||||||
"The bytes metrics have been collected. Read bytes = {}, written bytes = {}.",
|
bytesMetrics.wroteBytes());
|
||||||
bytesMetrics.readBytes(),
|
|
||||||
bytesMetrics.wroteBytes());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ChannelHandler createSslHandler(SSLContext sslContext, boolean needsClientAuth) {
|
private ChannelHandler createSslHandler(SSLContext sslContext, boolean needsClientAuth) {
|
||||||
|
|||||||
@@ -43,6 +43,39 @@ import java.util.concurrent.BlockingQueue;
|
|||||||
*/
|
*/
|
||||||
public class ClientSession {
|
public class ClientSession {
|
||||||
|
|
||||||
|
class OutboundFlightZone {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save the binding messageID, clientID - guid
|
||||||
|
|
||||||
|
* @param messageID the packet ID used in transmission
|
||||||
|
* @param guid the guid of the message being in flight.
|
||||||
|
*/
|
||||||
|
void waitingAck(int messageID, MessageGUID guid) {
|
||||||
|
if (LOG.isTraceEnabled()) {
|
||||||
|
LOG.trace("Adding to inflight {}, guid <{}>", messageID, guid);
|
||||||
|
}
|
||||||
|
m_sessionsStore.inFlight(ClientSession.this.clientID, messageID, guid);
|
||||||
|
}
|
||||||
|
|
||||||
|
void acknowledged(int messageID) {
|
||||||
|
if (LOG.isTraceEnabled())
|
||||||
|
LOG.trace("Acknowledging inflight, clientID <{}> messageID {}", ClientSession.this.clientID, messageID);
|
||||||
|
m_sessionsStore.inFlightAck(ClientSession.this.clientID, messageID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class InboundFlightZone {
|
||||||
|
|
||||||
|
public IMessagesStore.StoredMessage lookup(int messageID) {
|
||||||
|
return m_sessionsStore.inboundInflight(clientID, messageID);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void waitingRel(int messageID, MessageGUID guid) {
|
||||||
|
m_sessionsStore.markAsInboundInflight(clientID, messageID, guid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private final static Logger LOG = LoggerFactory.getLogger(ClientSession.class);
|
private final static Logger LOG = LoggerFactory.getLogger(ClientSession.class);
|
||||||
|
|
||||||
public final String clientID;
|
public final String clientID;
|
||||||
@@ -57,6 +90,8 @@ public class ClientSession {
|
|||||||
|
|
||||||
// private BlockingQueue<AbstractMessage> m_queueToPublish = new
|
// private BlockingQueue<AbstractMessage> m_queueToPublish = new
|
||||||
// ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE);
|
// ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE);
|
||||||
|
private final OutboundFlightZone outboundFlightZone;
|
||||||
|
private final InboundFlightZone inboundFlightZone;
|
||||||
|
|
||||||
public ClientSession(String clientID, IMessagesStore messagesStore, ISessionsStore sessionsStore,
|
public ClientSession(String clientID, IMessagesStore messagesStore, ISessionsStore sessionsStore,
|
||||||
boolean cleanSession) {
|
boolean cleanSession) {
|
||||||
@@ -64,6 +99,8 @@ public class ClientSession {
|
|||||||
this.messagesStore = messagesStore;
|
this.messagesStore = messagesStore;
|
||||||
this.m_sessionsStore = sessionsStore;
|
this.m_sessionsStore = sessionsStore;
|
||||||
this.cleanSession = cleanSession;
|
this.cleanSession = cleanSession;
|
||||||
|
this.outboundFlightZone = new OutboundFlightZone();
|
||||||
|
this.inboundFlightZone = new InboundFlightZone();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -84,17 +121,12 @@ public class ClientSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean subscribe(Subscription newSubscription) {
|
public boolean subscribe(Subscription newSubscription) {
|
||||||
LOG.info(
|
LOG.info("Adding new subscription. ClientId={}, topics={}, qos={}", newSubscription.getClientId(),
|
||||||
"Adding new subscription. ClientId={}, topics={}, qos={}",
|
newSubscription.getTopicFilter(), newSubscription.getRequestedQos());
|
||||||
newSubscription.getClientId(),
|
|
||||||
newSubscription.getTopicFilter(),
|
|
||||||
newSubscription.getRequestedQos());
|
|
||||||
boolean validTopic = newSubscription.getTopicFilter().isValid();
|
boolean validTopic = newSubscription.getTopicFilter().isValid();
|
||||||
if (!validTopic) {
|
if (!validTopic) {
|
||||||
LOG.warn(
|
LOG.warn("The topic filter is not valid. ClientId={}, topics={}", newSubscription.getClientId(),
|
||||||
"The topic filter is not valid. ClientId={}, topics={}",
|
newSubscription.getTopicFilter());
|
||||||
newSubscription.getClientId(),
|
|
||||||
newSubscription.getTopicFilter());
|
|
||||||
// send SUBACK with 0x80 for this topic filter
|
// send SUBACK with 0x80 for this topic filter
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -140,7 +172,10 @@ public class ClientSession {
|
|||||||
|
|
||||||
// remove also the messages stored of type QoS1/2
|
// remove also the messages stored of type QoS1/2
|
||||||
LOG.info("Removing stored messages with QoS 1 and 2. ClientId={}", this.clientID);
|
LOG.info("Removing stored messages with QoS 1 and 2. ClientId={}", this.clientID);
|
||||||
messagesStore.dropMessagesInSession(this.clientID);
|
messagesStore.dropInFlightMessagesInSession(m_sessionsStore.pendingAck(this.clientID));
|
||||||
|
|
||||||
|
//remove also the enqueued messages
|
||||||
|
this.m_sessionsStore.dropQueue(this.clientID);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isCleanSession() {
|
public boolean isCleanSession() {
|
||||||
@@ -157,15 +192,19 @@ public class ClientSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void inFlightAcknowledged(int messageID) {
|
public void inFlightAcknowledged(int messageID) {
|
||||||
if (LOG.isTraceEnabled())
|
outboundFlightZone.acknowledged(messageID);
|
||||||
LOG.trace("Acknowledging inflight, clientID <{}> messageID {}", this.clientID, messageID);
|
|
||||||
m_sessionsStore.inFlightAck(this.clientID, messageID);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void inFlightAckWaiting(MessageGUID guid, int messageID) {
|
/**
|
||||||
if (LOG.isTraceEnabled())
|
* Mark the message identified by guid as publish in flight.
|
||||||
LOG.trace("Adding to inflight {}, guid <{}>", messageID, guid);
|
*
|
||||||
m_sessionsStore.inFlight(this.clientID, messageID, guid);
|
* @return the packetID for the message in flight.
|
||||||
|
* */
|
||||||
|
public int inFlightAckWaiting(MessageGUID guid) {
|
||||||
|
LOG.debug("Adding message ot inflight zone. ClientId={}, guid={}", clientID, guid);
|
||||||
|
int messageId = ClientSession.this.nextPacketId();
|
||||||
|
outboundFlightZone.waitingAck(messageId, guid);
|
||||||
|
return messageId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IMessagesStore.StoredMessage secondPhaseAcknowledged(int messageID) {
|
public IMessagesStore.StoredMessage secondPhaseAcknowledged(int messageID) {
|
||||||
@@ -183,9 +222,12 @@ public class ClientSession {
|
|||||||
this.m_sessionsStore.queue(this.clientID).add(message);
|
this.m_sessionsStore.queue(this.clientID).add(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public IMessagesStore.StoredMessage storedMessage(int messageID) {
|
public IMessagesStore.StoredMessage inboundInflight(int messageID) {
|
||||||
final MessageGUID guid = messagesStore.mapToGuid(clientID, messageID);
|
return inboundFlightZone.lookup(messageID);
|
||||||
return messagesStore.getMessageByGuid(guid);
|
}
|
||||||
|
|
||||||
|
public void markAsInboundInflight(int messageID, MessageGUID guid) {
|
||||||
|
inboundFlightZone.waitingRel(messageID, guid);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void moveInFlightToSecondPhaseAckWaiting(int messageID) {
|
public void moveInFlightToSecondPhaseAckWaiting(int messageID) {
|
||||||
|
|||||||
@@ -37,8 +37,6 @@ public interface IMessagesStore {
|
|||||||
final String m_topic;
|
final String m_topic;
|
||||||
private boolean m_retained;
|
private boolean m_retained;
|
||||||
private String m_clientID;
|
private String m_clientID;
|
||||||
// Optional attribute, available only fo QoS 1 and 2
|
|
||||||
private Integer m_msgID;
|
|
||||||
private MessageGUID m_guid;
|
private MessageGUID m_guid;
|
||||||
|
|
||||||
public StoredMessage(byte[] message, MqttQoS qos, String topic) {
|
public StoredMessage(byte[] message, MqttQoS qos, String topic) {
|
||||||
@@ -75,14 +73,6 @@ public interface IMessagesStore {
|
|||||||
this.m_clientID = m_clientID;
|
this.m_clientID = m_clientID;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMessageID(Integer messageID) {
|
|
||||||
this.m_msgID = messageID;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getMessageID() {
|
|
||||||
return m_msgID;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ByteBuf getMessage() {
|
public ByteBuf getMessage() {
|
||||||
return Unpooled.copiedBuffer(m_payload);
|
return Unpooled.copiedBuffer(m_payload);
|
||||||
}
|
}
|
||||||
@@ -97,7 +87,7 @@ public interface IMessagesStore {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "PublishEvent{" + "m_msgID=" + m_msgID + ", clientID='" + m_clientID + '\'' + ", m_retain="
|
return "PublishEvent{clientID='" + m_clientID + '\'' + ", m_retain="
|
||||||
+ m_retained + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + '}';
|
+ m_retained + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + '}';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -135,13 +125,9 @@ public interface IMessagesStore {
|
|||||||
*/
|
*/
|
||||||
MessageGUID storePublishForFuture(StoredMessage storedMessage);
|
MessageGUID storePublishForFuture(StoredMessage storedMessage);
|
||||||
|
|
||||||
void dropMessagesInSession(String clientID);
|
void dropInFlightMessagesInSession(Collection<MessageGUID> pendingAckMessages);
|
||||||
|
|
||||||
StoredMessage getMessageByGuid(MessageGUID guid);
|
StoredMessage getMessageByGuid(MessageGUID guid);
|
||||||
|
|
||||||
void cleanRetained(Topic topic);
|
void cleanRetained(Topic topic);
|
||||||
|
|
||||||
int getPendingPublishMessages(String clientID);
|
|
||||||
|
|
||||||
MessageGUID mapToGuid(String clientID, int messageID);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,13 +16,14 @@
|
|||||||
|
|
||||||
package io.moquette.spi;
|
package io.moquette.spi;
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.BlockingQueue;
|
|
||||||
import io.moquette.spi.IMessagesStore.StoredMessage;
|
import io.moquette.spi.IMessagesStore.StoredMessage;
|
||||||
import io.moquette.spi.impl.subscriptions.Subscription;
|
import io.moquette.spi.impl.subscriptions.Subscription;
|
||||||
import io.moquette.spi.impl.subscriptions.Topic;
|
import io.moquette.spi.impl.subscriptions.Topic;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Store used to handle the persistence of the subscriptions tree.
|
* Store used to handle the persistence of the subscriptions tree.
|
||||||
*
|
*
|
||||||
@@ -188,24 +189,33 @@ public interface ISessionsStore {
|
|||||||
/**
|
/**
|
||||||
* Returns the number of inflight messages for the given client ID
|
* Returns the number of inflight messages for the given client ID
|
||||||
*
|
*
|
||||||
* @param clientID
|
* @param clientID target client.
|
||||||
* @return
|
* @return count of pending in flight publish messages.
|
||||||
*/
|
*/
|
||||||
int getInflightMessagesNo(String clientID);
|
int getInflightMessagesNo(String clientID);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return the inflight inbound (PUBREL for Qos2) message.
|
||||||
|
* */
|
||||||
|
IMessagesStore.StoredMessage inboundInflight(String clientID, int messageID);
|
||||||
|
|
||||||
|
void markAsInboundInflight(String clientID, int messageID, MessageGUID guid);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the size of the session queue for the given client ID
|
* Returns the size of the session queue for the given client ID
|
||||||
*
|
*
|
||||||
* @param clientID
|
* @param clientID target client.
|
||||||
* @return
|
* @return count of enqueued publish messages.
|
||||||
*/
|
*/
|
||||||
int getPendingPublishMessagesNo(String clientID);
|
int getPendingPublishMessagesNo(String clientID);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the number of second-phase ACK pending messages for the given client ID
|
* Returns the number of second-phase ACK pending messages for the given client ID
|
||||||
*
|
*
|
||||||
* @param clientID
|
* @param clientID target client.
|
||||||
* @return
|
* @return count of pending in flight publish messages.
|
||||||
*/
|
*/
|
||||||
int getSecondPhaseAckPendingMessages(String clientID);
|
int getSecondPhaseAckPendingMessages(String clientID);
|
||||||
|
|
||||||
|
Collection<MessageGUID> pendingAck(String clientID);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
private final ExecutorService executor;
|
private final ExecutorService executor;
|
||||||
|
|
||||||
private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers) {
|
private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers) {
|
||||||
LOG.info("Initializing broker interceptor. InterceptorIds = {}.", getInterceptorIds(handlers));
|
LOG.info("Initializing broker interceptor. InterceptorIds={}", getInterceptorIds(handlers));
|
||||||
this.handlers = new HashMap<>();
|
this.handlers = new HashMap<>();
|
||||||
for (Class<?> messageType : InterceptHandler.ALL_MESSAGE_TYPES) {
|
for (Class<?> messageType : InterceptHandler.ALL_MESSAGE_TYPES) {
|
||||||
this.handlers.put(messageType, new CopyOnWriteArrayList<InterceptHandler>());
|
this.handlers.put(messageType, new CopyOnWriteArrayList<InterceptHandler>());
|
||||||
@@ -94,10 +94,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void notifyClientConnected(final MqttConnectMessage msg) {
|
public void notifyClientConnected(final MqttConnectMessage msg) {
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Sending MQTT CONNECT message to interceptor. CId={}, interceptorId={}",
|
||||||
"Sending MQTT CONNECT message to interceptor. MqttClientId = {}, interceptorId = {}.",
|
msg.payload().clientIdentifier(), handler.getID());
|
||||||
msg.payload().clientIdentifier(),
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -111,12 +109,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void notifyClientDisconnected(final String clientID, final String username) {
|
public void notifyClientDisconnected(final String clientID, final String username) {
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Notifying MQTT client disconnection to interceptor. CId={}, username={}, interceptorId={}",
|
||||||
"Notifying MQTT client disconnection to interceptor. MqttClientId = {}, username = {}, "
|
clientID, username, handler.getID());
|
||||||
+ "interceptorId = {}.",
|
|
||||||
clientID,
|
|
||||||
username,
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -130,12 +124,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void notifyClientConnectionLost(final String clientID, final String username) {
|
public void notifyClientConnectionLost(final String clientID, final String username) {
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptConnectionLostMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptConnectionLostMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Notifying unexpected MQTT client disconnection to interceptor CId={}, username={}, " +
|
||||||
"Notifying unexpected MQTT client disconnection to interceptor. MqttClientId = {}, "
|
"interceptorId={}", clientID, username, handler.getID());
|
||||||
+ "username = {}, interceptorId = {}.",
|
|
||||||
clientID,
|
|
||||||
username,
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -151,13 +141,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
int messageId = msg.variableHeader().messageId();
|
int messageId = msg.variableHeader().messageId();
|
||||||
String topic = msg.variableHeader().topicName();
|
String topic = msg.variableHeader().topicName();
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Notifying MQTT PUBLISH message to interceptor. CId={}, messageId={}, topic={}, interceptorId={}",
|
||||||
"Notifying MQTT PUBLISH message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, "
|
clientID, messageId, topic, handler.getID());
|
||||||
+ "interceptorId = {}.",
|
|
||||||
clientID,
|
|
||||||
messageId,
|
|
||||||
topic,
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -171,12 +156,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void notifyTopicSubscribed(final Subscription sub, final String username) {
|
public void notifyTopicSubscribed(final Subscription sub, final String username) {
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Notifying MQTT SUBSCRIBE message to interceptor. CId={}, topicFilter={}, interceptorId={}",
|
||||||
"Notifying MQTT SUBSCRIBE message to interceptor. MqttClientId = {}, topicFilter = {}, "
|
sub.getClientId(), sub.getTopicFilter(), handler.getID());
|
||||||
+ "interceptorId = {}.",
|
|
||||||
sub.getClientId(),
|
|
||||||
sub.getTopicFilter(),
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -190,12 +171,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) {
|
public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) {
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Notifying MQTT UNSUBSCRIBE message to interceptor. CId={}, topic={}, interceptorId={}", clientID,
|
||||||
"Notifying MQTT UNSUBSCRIBE message to interceptor. MqttClientId = {}, topic = {}, "
|
topic, handler.getID());
|
||||||
+ "interceptorId = {}.",
|
|
||||||
clientID,
|
|
||||||
topic,
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -209,13 +186,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg) {
|
public void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg) {
|
||||||
for (final InterceptHandler handler : this.handlers.get(InterceptAcknowledgedMessage.class)) {
|
for (final InterceptHandler handler : this.handlers.get(InterceptAcknowledgedMessage.class)) {
|
||||||
LOG.debug(
|
LOG.debug("Notifying MQTT ACK message to interceptor. CId={}, messageId={}, topic={}, interceptorId={}",
|
||||||
"Notifying MQTT ACK message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, "
|
msg.getMsg().getClientID(), msg.getPacketID(), msg.getTopic(), handler.getID());
|
||||||
+ "interceptorId = {}.",
|
|
||||||
msg.getMsg().getClientID(),
|
|
||||||
msg.getMsg().getMessageID(),
|
|
||||||
msg.getTopic(),
|
|
||||||
handler.getID());
|
|
||||||
executor.execute(new Runnable() {
|
executor.execute(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -229,10 +201,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void addInterceptHandler(InterceptHandler interceptHandler) {
|
public void addInterceptHandler(InterceptHandler interceptHandler) {
|
||||||
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
|
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
|
||||||
LOG.info(
|
LOG.info( "Adding MQTT message interceptor. InterceptorId={}, handledMessageTypes={}",
|
||||||
"Adding MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
|
interceptHandler.getID(), interceptedMessageTypes);
|
||||||
interceptHandler.getID(),
|
|
||||||
interceptedMessageTypes);
|
|
||||||
for (Class<?> interceptMessageType : interceptedMessageTypes) {
|
for (Class<?> interceptMessageType : interceptedMessageTypes) {
|
||||||
this.handlers.get(interceptMessageType).add(interceptHandler);
|
this.handlers.get(interceptMessageType).add(interceptHandler);
|
||||||
}
|
}
|
||||||
@@ -241,10 +211,8 @@ final class BrokerInterceptor implements Interceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void removeInterceptHandler(InterceptHandler interceptHandler) {
|
public void removeInterceptHandler(InterceptHandler interceptHandler) {
|
||||||
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
|
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
|
||||||
LOG.info(
|
LOG.info("Removing MQTT message interceptor. InterceptorId={}, handledMessageTypes={}",
|
||||||
"Removing MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
|
interceptHandler.getID(), interceptedMessageTypes);
|
||||||
interceptHandler.getID(),
|
|
||||||
interceptedMessageTypes);
|
|
||||||
for (Class<?> interceptMessageType : interceptedMessageTypes) {
|
for (Class<?> interceptMessageType : interceptedMessageTypes) {
|
||||||
this.handlers.get(interceptMessageType).remove(interceptHandler);
|
this.handlers.get(interceptMessageType).remove(interceptHandler);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,17 +25,16 @@ class InternalRepublisher {
|
|||||||
void publishRetained(ClientSession targetSession, Collection<IMessagesStore.StoredMessage> messages) {
|
void publishRetained(ClientSession targetSession, Collection<IMessagesStore.StoredMessage> messages) {
|
||||||
for (IMessagesStore.StoredMessage storedMsg : messages) {
|
for (IMessagesStore.StoredMessage storedMsg : messages) {
|
||||||
// fire as retained the message
|
// fire as retained the message
|
||||||
Integer packetID = storedMsg.getQos() == MqttQoS.AT_MOST_ONCE ? null : targetSession.nextPacketId();
|
|
||||||
if (packetID != null) {
|
|
||||||
LOG.debug("Adding message to inflight zone. ClientId={}, packetId={}, messageId={}, topic={}",
|
|
||||||
targetSession.clientID, packetID, storedMsg.getMessageID(), storedMsg.getTopic());
|
|
||||||
targetSession.inFlightAckWaiting(storedMsg.getGuid(), packetID);
|
|
||||||
}
|
|
||||||
MqttPublishMessage publishMsg = retainedPublish(storedMsg);
|
MqttPublishMessage publishMsg = retainedPublish(storedMsg);
|
||||||
// set the PacketIdentifier only for QoS > 0
|
if (storedMsg.getQos() != MqttQoS.AT_MOST_ONCE) {
|
||||||
if (publishMsg.fixedHeader().qosLevel() != MqttQoS.AT_MOST_ONCE) {
|
LOG.debug("Adding message to inflight zone. ClientId={}, topic={}", targetSession.clientID,
|
||||||
|
storedMsg.getTopic());
|
||||||
|
int packetID = targetSession.inFlightAckWaiting(storedMsg.getGuid());
|
||||||
|
|
||||||
|
// set the PacketIdentifier only for QoS > 0
|
||||||
publishMsg = retainedPublish(storedMsg, packetID);
|
publishMsg = retainedPublish(storedMsg, packetID);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.messageSender.sendPublish(targetSession, publishMsg);
|
this.messageSender.sendPublish(targetSession, publishMsg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,13 +45,13 @@ class InternalRepublisher {
|
|||||||
|
|
||||||
for (IMessagesStore.StoredMessage pubEvt : storedPublishes) {
|
for (IMessagesStore.StoredMessage pubEvt : storedPublishes) {
|
||||||
// put in flight zone
|
// put in flight zone
|
||||||
LOG.debug("Adding message ot inflight zone. ClientId={}, guid={}, messageId={}, topic={}",
|
LOG.debug("Adding message ot inflight zone. ClientId={}, guid={}, topic={}", clientSession.clientID,
|
||||||
clientSession.clientID, pubEvt.getGuid(), pubEvt.getMessageID(), pubEvt.getTopic());
|
pubEvt.getGuid(), pubEvt.getTopic());
|
||||||
clientSession.inFlightAckWaiting(pubEvt.getGuid(), pubEvt.getMessageID());
|
int messageId = clientSession.inFlightAckWaiting(pubEvt.getGuid());
|
||||||
MqttPublishMessage publishMsg = notRetainedPublish(pubEvt);
|
MqttPublishMessage publishMsg = notRetainedPublish(pubEvt);
|
||||||
// set the PacketIdentifier only for QoS > 0
|
// set the PacketIdentifier only for QoS > 0
|
||||||
if (publishMsg.fixedHeader().qosLevel() != MqttQoS.AT_MOST_ONCE) {
|
if (publishMsg.fixedHeader().qosLevel() != MqttQoS.AT_MOST_ONCE) {
|
||||||
publishMsg = notRetainedPublish(pubEvt, pubEvt.getMessageID());
|
publishMsg = notRetainedPublish(pubEvt, messageId);
|
||||||
}
|
}
|
||||||
this.messageSender.sendPublish(clientSession, publishMsg);
|
this.messageSender.sendPublish(clientSession, publishMsg);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,25 +63,20 @@ class MessagesPublisher {
|
|||||||
// refCnt = 0
|
// refCnt = 0
|
||||||
ByteBuf message = origMessage.retainedDuplicate();
|
ByteBuf message = origMessage.retainedDuplicate();
|
||||||
if (targetIsActive) {
|
if (targetIsActive) {
|
||||||
LOG.debug(
|
LOG.debug("Sending PUBLISH message to active subscriber. CId={}, topicFilter={}, qos={}",
|
||||||
"Sending PUBLISH message to active subscriber. MessageId={}, CId={}, topicFilter={}, qos={}",
|
sub.getClientId(), sub.getTopicFilter(), qos);
|
||||||
pubMsg.getMessageID(),
|
|
||||||
sub.getClientId(),
|
|
||||||
sub.getTopicFilter(),
|
|
||||||
qos);
|
|
||||||
MqttPublishMessage publishMsg = notRetainedPublish(topic, qos, message);
|
MqttPublishMessage publishMsg = notRetainedPublish(topic, qos, message);
|
||||||
if (qos != MqttQoS.AT_MOST_ONCE) {
|
if (qos != MqttQoS.AT_MOST_ONCE) {
|
||||||
// QoS 1 or 2
|
// QoS 1 or 2
|
||||||
int messageId = targetSession.nextPacketId();
|
int messageId = targetSession.inFlightAckWaiting(guid);
|
||||||
targetSession.inFlightAckWaiting(guid, messageId);
|
|
||||||
// set the PacketIdentifier only for QoS > 0
|
// set the PacketIdentifier only for QoS > 0
|
||||||
publishMsg = notRetainedPublishWithMessageId(topic, qos, message, messageId);
|
publishMsg = notRetainedPublishWithMessageId(topic, qos, message, messageId);
|
||||||
}
|
}
|
||||||
this.messageSender.sendPublish(targetSession, publishMsg);
|
this.messageSender.sendPublish(targetSession, publishMsg);
|
||||||
} else {
|
} else {
|
||||||
if (!targetSession.isCleanSession()) {
|
if (!targetSession.isCleanSession()) {
|
||||||
LOG.debug("Storing pending PUBLISH inactive message. MessageId={}, CId={}, topicFilter={}, qos={}",
|
LOG.debug("Storing pending PUBLISH inactive message. CId={}, topicFilter={}, qos={}",
|
||||||
pubMsg.getMessageID(), sub.getClientId(), sub.getTopicFilter(), qos);
|
sub.getClientId(), sub.getTopicFilter(), qos);
|
||||||
// store the message in targetSession queue to deliver
|
// store the message in targetSession queue to deliver
|
||||||
targetSession.enqueue(pubMsg);
|
targetSession.enqueue(pubMsg);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -474,7 +474,7 @@ public class ProtocolProcessor {
|
|||||||
targetSession.inFlightAcknowledged(messageID);
|
targetSession.inFlightAcknowledged(messageID);
|
||||||
|
|
||||||
String topic = inflightMsg.getTopic();
|
String topic = inflightMsg.getTopic();
|
||||||
m_interceptor.notifyMessageAcknowledged(new InterceptAcknowledgedMessage(inflightMsg, topic, username));
|
m_interceptor.notifyMessageAcknowledged(new InterceptAcknowledgedMessage(inflightMsg, topic, username, messageID));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg) {
|
public static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg) {
|
||||||
@@ -485,7 +485,6 @@ public class ProtocolProcessor {
|
|||||||
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(payloadContent,
|
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(payloadContent,
|
||||||
msg.fixedHeader().qosLevel(), msg.variableHeader().topicName());
|
msg.fixedHeader().qosLevel(), msg.variableHeader().topicName());
|
||||||
stored.setRetained(msg.fixedHeader().isRetain());
|
stored.setRetained(msg.fixedHeader().isRetain());
|
||||||
stored.setMessageID(msg.variableHeader().messageId());
|
|
||||||
return stored;
|
return stored;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -540,7 +539,6 @@ public class ProtocolProcessor {
|
|||||||
} else {
|
} else {
|
||||||
toStoreMsg.setClientID(clientId);
|
toStoreMsg.setClientID(clientId);
|
||||||
}
|
}
|
||||||
toStoreMsg.setMessageID(1);
|
|
||||||
if (qos == EXACTLY_ONCE) { // QoS2
|
if (qos == EXACTLY_ONCE) { // QoS2
|
||||||
guid = m_messagesStore.storePublishForFuture(toStoreMsg);
|
guid = m_messagesStore.storePublishForFuture(toStoreMsg);
|
||||||
}
|
}
|
||||||
@@ -568,18 +566,12 @@ public class ProtocolProcessor {
|
|||||||
private void forwardPublishWill(WillMessage will, String clientID) {
|
private void forwardPublishWill(WillMessage will, String clientID) {
|
||||||
// it has just to publish the message downstream to the subscribers
|
// it has just to publish the message downstream to the subscribers
|
||||||
// NB it's a will publish, it needs a PacketIdentifier for this conn, default to 1
|
// NB it's a will publish, it needs a PacketIdentifier for this conn, default to 1
|
||||||
Integer messageId = null;
|
|
||||||
if (will.getQos() != AT_MOST_ONCE) {
|
|
||||||
messageId = m_sessionsStore.nextPacketID(clientID);
|
|
||||||
}
|
|
||||||
|
|
||||||
IMessagesStore.StoredMessage tobeStored = asStoredMessage(will);
|
IMessagesStore.StoredMessage tobeStored = asStoredMessage(will);
|
||||||
tobeStored.setClientID(clientID);
|
tobeStored.setClientID(clientID);
|
||||||
tobeStored.setMessageID(messageId);
|
|
||||||
Topic topic = new Topic(tobeStored.getTopic());
|
Topic topic = new Topic(tobeStored.getTopic());
|
||||||
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
||||||
|
|
||||||
LOG.info("Publishing will message. CId={}, messageId={}, topic={}", clientID, messageId, topic);
|
LOG.info("Publishing will message. CId={}, topic={}", clientID, topic);
|
||||||
this.messagesPublisher.publish2Subscribers(tobeStored, topicMatchingSubscriptions);
|
this.messagesPublisher.publish2Subscribers(tobeStored, topicMatchingSubscriptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -626,7 +618,7 @@ public class ProtocolProcessor {
|
|||||||
StoredMessage inflightMsg = targetSession.secondPhaseAcknowledged(messageID);
|
StoredMessage inflightMsg = targetSession.secondPhaseAcknowledged(messageID);
|
||||||
String username = NettyUtils.userName(channel);
|
String username = NettyUtils.userName(channel);
|
||||||
String topic = inflightMsg.getTopic();
|
String topic = inflightMsg.getTopic();
|
||||||
m_interceptor.notifyMessageAcknowledged(new InterceptAcknowledgedMessage(inflightMsg, topic, username));
|
m_interceptor.notifyMessageAcknowledged(new InterceptAcknowledgedMessage(inflightMsg, topic, username, messageID));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void processDisconnect(Channel channel) throws InterruptedException {
|
public void processDisconnect(Channel channel) throws InterruptedException {
|
||||||
@@ -759,8 +751,7 @@ public class ProtocolProcessor {
|
|||||||
if (!validTopic) {
|
if (!validTopic) {
|
||||||
// close the connection, not valid topicFilter is a protocol violation
|
// close the connection, not valid topicFilter is a protocol violation
|
||||||
channel.close();
|
channel.close();
|
||||||
LOG.error( "Topic filter is not valid. CId={}, topics={}, badTopicFilter={}", clientID, topics,
|
LOG.error("Topic filter is not valid. CId={}, topics={}, badTopicFilter={}", clientID, topics, topic);
|
||||||
topic);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import io.netty.handler.codec.mqtt.*;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static io.moquette.spi.impl.DebugUtils.payload2Str;
|
||||||
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
|
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
|
||||||
import static io.moquette.spi.impl.Utils.messageId;
|
import static io.moquette.spi.impl.Utils.messageId;
|
||||||
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
|
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
|
||||||
@@ -23,7 +25,7 @@ import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
|
|||||||
|
|
||||||
class Qos2PublishHandler extends QosPublishHandler {
|
class Qos2PublishHandler extends QosPublishHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(Qos1PublishHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(Qos2PublishHandler.class);
|
||||||
|
|
||||||
private final SubscriptionsStore subscriptions;
|
private final SubscriptionsStore subscriptions;
|
||||||
private final IMessagesStore m_messagesStore;
|
private final IMessagesStore m_messagesStore;
|
||||||
@@ -57,18 +59,16 @@ class Qos2PublishHandler extends QosPublishHandler {
|
|||||||
String clientID = NettyUtils.clientID(channel);
|
String clientID = NettyUtils.clientID(channel);
|
||||||
toStoreMsg.setClientID(clientID);
|
toStoreMsg.setClientID(clientID);
|
||||||
|
|
||||||
|
LOG.info("Sending publish message to subscribers CId={}, topic={}, messageId={}", clientID, topic, messageID);
|
||||||
if (LOG.isTraceEnabled()) {
|
if (LOG.isTraceEnabled()) {
|
||||||
LOG.trace( "Sending publish message to subscribers. ClientId={}, topic={}, messageId={}, payload={}, " +
|
LOG.trace("payload={}, subs Tree={}", payload2Str(toStoreMsg.getMessage()), subscriptions.dumpTree());
|
||||||
"subscriptionTree={}", clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
|
||||||
subscriptions.dumpTree());
|
|
||||||
} else {
|
|
||||||
LOG.info("Sending publish message to subscribers. ClientId={}, topic={}, messageId={}", clientID, topic,
|
|
||||||
messageID);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// QoS2
|
// QoS2
|
||||||
MessageGUID guid = m_messagesStore.storePublishForFuture(toStoreMsg);
|
MessageGUID guid = m_messagesStore.storePublishForFuture(toStoreMsg);
|
||||||
// TODO Don't send PUBREC for Hz publish notification, if (msg.isLocal()) {
|
ClientSession sourceSession = m_sessionsStore.sessionForClient(clientID);
|
||||||
|
sourceSession.markAsInboundInflight(messageID, guid);
|
||||||
|
|
||||||
sendPubRec(clientID, messageID);
|
sendPubRec(clientID, messageID);
|
||||||
|
|
||||||
// Next the client will send us a pub rel
|
// Next the client will send us a pub rel
|
||||||
@@ -92,18 +92,22 @@ class Qos2PublishHandler extends QosPublishHandler {
|
|||||||
void processPubRel(Channel channel, MqttMessage msg) {
|
void processPubRel(Channel channel, MqttMessage msg) {
|
||||||
String clientID = NettyUtils.clientID(channel);
|
String clientID = NettyUtils.clientID(channel);
|
||||||
int messageID = messageId(msg);
|
int messageID = messageId(msg);
|
||||||
LOG.info("Processing PUBREL message. ClientId={}, messageId={}", clientID, messageID);
|
LOG.info("Processing PUBREL message. CId={}, messageId={}", clientID, messageID);
|
||||||
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
|
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
|
||||||
IMessagesStore.StoredMessage evt = targetSession.storedMessage(messageID);
|
IMessagesStore.StoredMessage evt = targetSession.inboundInflight(messageID);
|
||||||
|
if (evt == null) {
|
||||||
|
LOG.warn("Can't find inbound inflight message for CId={}, messageId={}", clientID, messageID);
|
||||||
|
throw new IllegalArgumentException("Can't find inbound inflight message");
|
||||||
|
}
|
||||||
final Topic topic = new Topic(evt.getTopic());
|
final Topic topic = new Topic(evt.getTopic());
|
||||||
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
||||||
|
|
||||||
if (LOG.isDebugEnabled()) {
|
if (LOG.isDebugEnabled()) {
|
||||||
LOG.debug("Sending publish message to subscribers. ClientId={}, topic={}, messageId={}, payload={}, " +
|
LOG.debug("Sending publish message to subscribers. CId={}, topic={}, messageId={}, payload={}, " +
|
||||||
"subscriptionTree={}", clientID, topic, messageID, DebugUtils.payload2Str(evt.getMessage()),
|
"subscriptionTree={}", clientID, topic, messageID, payload2Str(evt.getMessage()),
|
||||||
subscriptions.dumpTree());
|
subscriptions.dumpTree());
|
||||||
} else {
|
} else {
|
||||||
LOG.info("Sending publish message to subscribers. ClientId={}, topic={}, messageId={}", clientID, topic,
|
LOG.info("Sending publish message to subscribers. CId={}, topic={}, messageId={}", clientID, topic,
|
||||||
messageID);
|
messageID);
|
||||||
}
|
}
|
||||||
this.publisher.publish2Subscribers(evt, topicMatchingSubscriptions);
|
this.publisher.publish2Subscribers(evt, topicMatchingSubscriptions);
|
||||||
@@ -120,14 +124,14 @@ class Qos2PublishHandler extends QosPublishHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void sendPubRec(String clientID, int messageID) {
|
private void sendPubRec(String clientID, int messageID) {
|
||||||
LOG.debug("Sending PUBREC message. ClientId={}, messageId={}", clientID, messageID);
|
LOG.debug("Sending PUBREC message. CId={}, messageId={}", clientID, messageID);
|
||||||
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, AT_MOST_ONCE, false, 0);
|
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, AT_MOST_ONCE, false, 0);
|
||||||
MqttMessage pubRecMessage = new MqttMessage(fixedHeader, from(messageID));
|
MqttMessage pubRecMessage = new MqttMessage(fixedHeader, from(messageID));
|
||||||
connectionDescriptors.sendMessage(pubRecMessage, messageID, clientID);
|
connectionDescriptors.sendMessage(pubRecMessage, messageID, clientID);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendPubComp(String clientID, int messageID) {
|
private void sendPubComp(String clientID, int messageID) {
|
||||||
LOG.debug("Sending PUBCOMP message. ClientId={}, messageId={}", clientID, messageID);
|
LOG.debug("Sending PUBCOMP message. CId={}, messageId={}", clientID, messageID);
|
||||||
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP, false, AT_MOST_ONCE, false, 0);
|
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP, false, AT_MOST_ONCE, false, 0);
|
||||||
MqttMessage pubCompMessage = new MqttMessage(fixedHeader, from(messageID));
|
MqttMessage pubCompMessage = new MqttMessage(fixedHeader, from(messageID));
|
||||||
connectionDescriptors.sendMessage(pubCompMessage, messageID, clientID);
|
connectionDescriptors.sendMessage(pubCompMessage, messageID, clientID);
|
||||||
|
|||||||
+9
-4
@@ -9,10 +9,7 @@ import org.eclipse.paho.client.mqttv3.MqttClient;
|
|||||||
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
|
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
|
||||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||||
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
|
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
|
||||||
import org.junit.After;
|
import org.junit.*;
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.BeforeClass;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@@ -114,14 +111,22 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest {
|
|||||||
MqttMessage messageQos0 = m_messagesCollector.waitMessage(1);
|
MqttMessage messageQos0 = m_messagesCollector.waitMessage(1);
|
||||||
assertEquals("Hello world MQTT QoS0", messageQos0.toString());
|
assertEquals("Hello world MQTT QoS0", messageQos0.toString());
|
||||||
assertEquals(0, messageQos0.getQos());
|
assertEquals(0, messageQos0.getQos());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void checkPublishPassThroughCluster_Qos1() throws Exception {
|
||||||
|
LOG.info("*** checkPublishPassThroughCluster_Qos1 ***");
|
||||||
m_listener.subscribe("/topic", 1);
|
m_listener.subscribe("/topic", 1);
|
||||||
|
|
||||||
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(), 1, false);
|
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(), 1, false);
|
||||||
MqttMessage messageQos1 = m_messagesCollector.waitMessage(1);
|
MqttMessage messageQos1 = m_messagesCollector.waitMessage(1);
|
||||||
assertEquals("Hello world MQTT QoS1", messageQos1.toString());
|
assertEquals("Hello world MQTT QoS1", messageQos1.toString());
|
||||||
assertEquals(1, messageQos1.getQos());
|
assertEquals(1, messageQos1.getQos());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void checkPublishPassThroughCluster_Qos2() throws Exception {
|
||||||
|
LOG.info("*** checkPublishPassThroughCluster_Qos2 ***");
|
||||||
m_listener.subscribe("/topic", 2);
|
m_listener.subscribe("/topic", 2);
|
||||||
|
|
||||||
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 2, false);
|
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 2, false);
|
||||||
|
|||||||
@@ -364,7 +364,6 @@ public class ProtocolProcessorTest {
|
|||||||
|
|
||||||
StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(), MqttQoS.EXACTLY_ONCE, "/topic");
|
StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(), MqttQoS.EXACTLY_ONCE, "/topic");
|
||||||
retainedMessage.setRetained(true);
|
retainedMessage.setRetained(true);
|
||||||
retainedMessage.setMessageID(120);
|
|
||||||
retainedMessage.setClientID(FAKE_PUBLISHER_ID);
|
retainedMessage.setClientID(FAKE_PUBLISHER_ID);
|
||||||
m_messagesStore.storePublishForFuture(retainedMessage);
|
m_messagesStore.storePublishForFuture(retainedMessage);
|
||||||
|
|
||||||
|
|||||||
@@ -2,20 +2,14 @@
|
|||||||
log4j.rootLogger=ERROR, stdout, file
|
log4j.rootLogger=ERROR, stdout, file
|
||||||
|
|
||||||
log4j.logger.io.moquette=WARN
|
log4j.logger.io.moquette=WARN
|
||||||
#log4j.logger.io.moquette=DEBUG
|
|
||||||
|
|
||||||
#log4j.logger.io.moquette.spi.impl.ProtocolProcessor=TRACE
|
|
||||||
log4j.logger.io.moquette.spi.impl.ProtocolProcessor=WARN
|
log4j.logger.io.moquette.spi.impl.ProtocolProcessor=WARN
|
||||||
#log4j.logger.io.moquette.spi.impl.SimpleMessaging=DEBUG
|
|
||||||
|
|
||||||
#Protocol parsing
|
#Protocol dispatching
|
||||||
#log4j.logger.io.moquette.server.netty.NettyMQTTHandler=DEBUG
|
|
||||||
log4j.logger.io.moquette.server.netty.NettyMQTTHandler=WARN
|
log4j.logger.io.moquette.server.netty.NettyMQTTHandler=WARN
|
||||||
#log4j.logger.io.moquette.parser.netty=DEBUG
|
|
||||||
|
|
||||||
#Storage service
|
#Storage service
|
||||||
#log4j.logger.io.moquette.spi.impl.subscriptions.SubscriptionsStore=DEBUG
|
#log4j.logger.io.moquette.spi.impl.subscriptions.SubscriptionsStore=DEBUG
|
||||||
#log4j.logger.io.moquette.spi.persistence.MapDBPersistentStore=DEBUG
|
|
||||||
log4j.logger.io.moquette.spi.persistence.MapDBPersistentStore=WARN
|
log4j.logger.io.moquette.spi.persistence.MapDBPersistentStore=WARN
|
||||||
log4j.logger.io.moquette.spi.persistence.MapDBSessionsStore=WARN
|
log4j.logger.io.moquette.spi.persistence.MapDBSessionsStore=WARN
|
||||||
|
|
||||||
|
|||||||
@@ -48,14 +48,14 @@ class MapDBMessagesStore implements IMessagesStore {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void initStore() {
|
public void initStore() {
|
||||||
LOG.info("Initializing store...");
|
|
||||||
m_retainedStore = m_db.getHashMap("retained");
|
m_retainedStore = m_db.getHashMap("retained");
|
||||||
m_persistentMessageStore = m_db.getHashMap("persistedMessages");
|
m_persistentMessageStore = m_db.getHashMap("persistedMessages");
|
||||||
|
LOG.info("Initialized store");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void storeRetained(Topic topic, MessageGUID guid) {
|
public void storeRetained(Topic topic, MessageGUID guid) {
|
||||||
LOG.debug("Storing retained messages. Topic = {}, guid = {}.", topic, guid);
|
LOG.debug("Storing retained messages. Topic={}, guid={}", topic, guid);
|
||||||
m_retainedStore.put(topic, guid);
|
m_retainedStore.put(topic, guid);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +72,7 @@ class MapDBMessagesStore implements IMessagesStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (LOG.isTraceEnabled()) {
|
if (LOG.isTraceEnabled()) {
|
||||||
LOG.trace("The retained messages have been scanned. MatchingMessages = {}.", results);
|
LOG.trace("The retained messages have been scanned. MatchingMessages={}", results);
|
||||||
}
|
}
|
||||||
|
|
||||||
return results;
|
return results;
|
||||||
@@ -80,75 +80,35 @@ class MapDBMessagesStore implements IMessagesStore {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MessageGUID storePublishForFuture(StoredMessage storedMessage) {
|
public MessageGUID storePublishForFuture(StoredMessage storedMessage) {
|
||||||
assert storedMessage.getClientID() != null : "The message to be persisted must have a valid client ID";
|
assert storedMessage.getClientID() != null : "Message to be persisted must have a valid client ID";
|
||||||
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
|
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
|
||||||
storedMessage.setGuid(guid);
|
storedMessage.setGuid(guid);
|
||||||
LOG.debug(
|
LOG.debug("Storing publish event. CId={}, guid={}, topic={}", storedMessage.getClientID(), guid,
|
||||||
"Storing publish event. MqttClientId = {}, messageId = {}, guid = {}, topic = {}.",
|
storedMessage.getTopic());
|
||||||
storedMessage.getClientID(),
|
|
||||||
storedMessage.getMessageID(),
|
|
||||||
guid,
|
|
||||||
storedMessage.getTopic());
|
|
||||||
m_persistentMessageStore.put(guid, storedMessage);
|
m_persistentMessageStore.put(guid, storedMessage);
|
||||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db
|
|
||||||
.getHashMap(messageId2GuidsMapName(storedMessage.getClientID()));
|
|
||||||
messageIdToGuid.put(storedMessage.getMessageID(), guid);
|
|
||||||
return guid;
|
return guid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void dropMessagesInSession(String clientID) {
|
public void dropInFlightMessagesInSession(Collection<MessageGUID> pendingAckMessages) {
|
||||||
LOG.debug("Dropping stored messages. ClientId = {}.", clientID);
|
//remove all guids from retained
|
||||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(messageId2GuidsMapName(clientID));
|
Collection<MessageGUID> messagesToRemove = new HashSet<>(pendingAckMessages);
|
||||||
for (MessageGUID guid : messageIdToGuid.values()) {
|
messagesToRemove.removeAll(m_retainedStore.values());
|
||||||
removeStoredMessage(guid);
|
|
||||||
}
|
|
||||||
messageIdToGuid.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
void removeStoredMessage(MessageGUID guid) {
|
for (MessageGUID guid : messagesToRemove) {
|
||||||
// remove only the not retained and no more referenced
|
|
||||||
StoredMessage storedMessage = m_persistentMessageStore.get(guid);
|
|
||||||
if (!storedMessage.isRetained()) {
|
|
||||||
LOG.debug(
|
|
||||||
"Dropping stored message. ClientId = {}, messageId = {}, guid = {}, topic = {}.",
|
|
||||||
storedMessage.getClientID(),
|
|
||||||
storedMessage.getMessageID(),
|
|
||||||
guid,
|
|
||||||
storedMessage.getTopic());
|
|
||||||
m_persistentMessageStore.remove(guid);
|
m_persistentMessageStore.remove(guid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public StoredMessage getMessageByGuid(MessageGUID guid) {
|
public StoredMessage getMessageByGuid(MessageGUID guid) {
|
||||||
LOG.debug("Retrieving stored message. Guid = {}.", guid);
|
LOG.debug("Retrieving stored message. Guid={}", guid);
|
||||||
return m_persistentMessageStore.get(guid);
|
return m_persistentMessageStore.get(guid);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void cleanRetained(Topic topic) {
|
public void cleanRetained(Topic topic) {
|
||||||
LOG.debug("Cleaning retained messages. Topic = {}.", topic);
|
LOG.debug("Cleaning retained messages. Topic={}", topic);
|
||||||
m_retainedStore.remove(topic);
|
m_retainedStore.remove(topic);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getPendingPublishMessages(String clientID) {
|
|
||||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuidMap = m_db
|
|
||||||
.getHashMap(messageId2GuidsMapName(clientID));
|
|
||||||
return messageIdToGuidMap.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public MessageGUID mapToGuid(String clientID, int messageID) {
|
|
||||||
LOG.debug("Mapping message ID to GUID CId={}, messageId={}", clientID, messageID);
|
|
||||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(messageId2GuidsMapName(clientID));
|
|
||||||
MessageGUID result = messageIdToGuid.get(messageID);
|
|
||||||
LOG.debug("Message ID has been mapped to a GUID CId={}, messageId={}, guid={}", clientID, messageID, result);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String messageId2GuidsMapName(String clientID) {
|
|
||||||
return "guidsMapping_" + clientID;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import io.moquette.spi.impl.subscriptions.Topic;
|
|||||||
import org.mapdb.DB;
|
import org.mapdb.DB;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.BlockingQueue;
|
import java.util.concurrent.BlockingQueue;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -310,9 +311,24 @@ class MapDBSessionsStore implements ISessionsStore {
|
|||||||
return m_inflightStore.get(clientID).size();
|
return m_inflightStore.get(clientID).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StoredMessage inboundInflight(String clientID, int messageID) {
|
||||||
|
LOG.debug("Mapping inbound message ID to GUID CId={}, messageId={}", clientID, messageID);
|
||||||
|
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(inboundMessageId2GuidsMapName(clientID));
|
||||||
|
final MessageGUID guid = messageIdToGuid.get(messageID);
|
||||||
|
LOG.debug("Inbound message ID has been mapped CId={}, messageId={}, guid={}", clientID, messageID, guid);
|
||||||
|
return m_messagesStore.getMessageByGuid(guid);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void markAsInboundInflight(String clientID, int messageID, MessageGUID guid) {
|
||||||
|
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(inboundMessageId2GuidsMapName(clientID));
|
||||||
|
messageIdToGuid.put(messageID, guid);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getPendingPublishMessagesNo(String clientID) {
|
public int getPendingPublishMessagesNo(String clientID) {
|
||||||
return m_messagesStore.getPendingPublishMessages(clientID);
|
return queue(clientID).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -322,4 +338,22 @@ class MapDBSessionsStore implements ISessionsStore {
|
|||||||
else
|
else
|
||||||
return m_secondPhaseStore.get(clientID).size();
|
return m_secondPhaseStore.get(clientID).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<MessageGUID> pendingAck(String clientID) {
|
||||||
|
ConcurrentMap<Integer, MessageGUID> messageGUIDMap = m_db.getHashMap(messageId2GuidsMapName(clientID));
|
||||||
|
if (messageGUIDMap == null || messageGUIDMap.isEmpty()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ArrayList<>(messageGUIDMap.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
static String messageId2GuidsMapName(String clientID) {
|
||||||
|
return "guidsMapping_" + clientID;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String inboundMessageId2GuidsMapName(String clientID) {
|
||||||
|
return "inboundInflightGuidsMapping_" + clientID;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-24
@@ -16,9 +16,6 @@
|
|||||||
|
|
||||||
package io.moquette.persistence.mapdb;
|
package io.moquette.persistence.mapdb;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import io.moquette.BrokerConstants;
|
import io.moquette.BrokerConstants;
|
||||||
import io.moquette.server.config.IConfig;
|
import io.moquette.server.config.IConfig;
|
||||||
import io.moquette.server.config.MemoryConfig;
|
import io.moquette.server.config.MemoryConfig;
|
||||||
@@ -29,15 +26,19 @@ import io.moquette.spi.ISessionsStore.ClientTopicCouple;
|
|||||||
import io.moquette.spi.MessageGUID;
|
import io.moquette.spi.MessageGUID;
|
||||||
import io.moquette.spi.impl.subscriptions.Subscription;
|
import io.moquette.spi.impl.subscriptions.Subscription;
|
||||||
import io.moquette.spi.impl.subscriptions.Topic;
|
import io.moquette.spi.impl.subscriptions.Topic;
|
||||||
import io.netty.handler.codec.mqtt.MqttQoS;
|
import static io.netty.handler.codec.mqtt.MqttQoS.*;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
|
import static java.util.Collections.singletonList;
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -92,14 +93,11 @@ public class MapDBPersistentStoreTest {
|
|||||||
ClientSession session1 = m_sessionsStore.createNewSession("SESSION_ID_1", true);
|
ClientSession session1 = m_sessionsStore.createNewSession("SESSION_ID_1", true);
|
||||||
|
|
||||||
// Subscribe on /topic with QOSType.MOST_ONE
|
// Subscribe on /topic with QOSType.MOST_ONE
|
||||||
Subscription oldSubscription = new Subscription(session1.clientID, new Topic("/topic"), MqttQoS.AT_MOST_ONCE);
|
Subscription oldSubscription = new Subscription(session1.clientID, new Topic("/topic"), AT_MOST_ONCE);
|
||||||
session1.subscribe(oldSubscription);
|
session1.subscribe(oldSubscription);
|
||||||
|
|
||||||
// Subscribe on /topic again that overrides the previous subscription.
|
// Subscribe on /topic again that overrides the previous subscription.
|
||||||
Subscription overridingSubscription = new Subscription(
|
Subscription overridingSubscription = new Subscription(session1.clientID, new Topic("/topic"), EXACTLY_ONCE);
|
||||||
session1.clientID,
|
|
||||||
new Topic("/topic"),
|
|
||||||
MqttQoS.EXACTLY_ONCE);
|
|
||||||
session1.subscribe(overridingSubscription);
|
session1.subscribe(overridingSubscription);
|
||||||
|
|
||||||
// Verify
|
// Verify
|
||||||
@@ -156,18 +154,15 @@ public class MapDBPersistentStoreTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDropMessagesInSessionCleanAllNotRetainedStoredMessages() {
|
public void testDropMessagesInSessionCleanAllNotRetainedStoredMessages() {
|
||||||
m_sessionsStore.createNewSession("TestClient", true);
|
m_sessionsStore.createNewSession(TEST_CLIENT, true);
|
||||||
IMessagesStore.StoredMessage publishToStore = new IMessagesStore.StoredMessage(
|
IMessagesStore.StoredMessage publishToStore = new IMessagesStore.StoredMessage("Hello".getBytes(), EXACTLY_ONCE,
|
||||||
"Hello".getBytes(),
|
"/topic");
|
||||||
MqttQoS.EXACTLY_ONCE,
|
|
||||||
"/topic");
|
|
||||||
publishToStore.setClientID(TEST_CLIENT);
|
publishToStore.setClientID(TEST_CLIENT);
|
||||||
publishToStore.setMessageID(1);
|
|
||||||
publishToStore.setRetained(false);
|
publishToStore.setRetained(false);
|
||||||
MessageGUID guid = m_messagesStore.storePublishForFuture(publishToStore);
|
MessageGUID guid = m_messagesStore.storePublishForFuture(publishToStore);
|
||||||
|
|
||||||
// Exercise
|
// Exercise
|
||||||
m_messagesStore.dropMessagesInSession("TestClient");
|
m_messagesStore.dropInFlightMessagesInSession(singletonList(guid));
|
||||||
|
|
||||||
// Verify the message store for session is empty.
|
// Verify the message store for session is empty.
|
||||||
IMessagesStore.StoredMessage storedPublish = m_messagesStore.getMessageByGuid(guid);
|
IMessagesStore.StoredMessage storedPublish = m_messagesStore.getMessageByGuid(guid);
|
||||||
@@ -176,18 +171,16 @@ public class MapDBPersistentStoreTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() {
|
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() {
|
||||||
m_sessionsStore.createNewSession("TestClient", true);
|
m_sessionsStore.createNewSession(TEST_CLIENT, true);
|
||||||
IMessagesStore.StoredMessage publishToStore = new IMessagesStore.StoredMessage(
|
IMessagesStore.StoredMessage publishToStore = new IMessagesStore.StoredMessage("Hello".getBytes(), EXACTLY_ONCE,
|
||||||
"Hello".getBytes(),
|
"/topic");
|
||||||
MqttQoS.EXACTLY_ONCE,
|
|
||||||
"/topic");
|
|
||||||
publishToStore.setClientID(TEST_CLIENT);
|
publishToStore.setClientID(TEST_CLIENT);
|
||||||
publishToStore.setMessageID(1);
|
|
||||||
publishToStore.setRetained(true);
|
publishToStore.setRetained(true);
|
||||||
MessageGUID guid = m_messagesStore.storePublishForFuture(publishToStore);
|
MessageGUID guid = m_messagesStore.storePublishForFuture(publishToStore);
|
||||||
|
m_messagesStore.storeRetained(new Topic("/topic"), guid);
|
||||||
|
|
||||||
// Exercise
|
// Exercise
|
||||||
m_messagesStore.dropMessagesInSession("TestClient");
|
m_messagesStore.dropInFlightMessagesInSession(singletonList(guid));
|
||||||
|
|
||||||
// Verify the message store for session is empty.
|
// Verify the message store for session is empty.
|
||||||
IMessagesStore.StoredMessage storedPublish = m_messagesStore.getMessageByGuid(guid);
|
IMessagesStore.StoredMessage storedPublish = m_messagesStore.getMessageByGuid(guid);
|
||||||
|
|||||||
Reference in New Issue
Block a user