Merge pull request #265 from AndreasMager/fromating-broker
Minor Checkstyle adjustement & Fromating broker folder
This commit is contained in:
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette;
|
||||
|
||||
import java.io.File;
|
||||
@@ -21,6 +22,7 @@ import java.io.File;
|
||||
* Created by andrea on 08/12/15.
|
||||
*/
|
||||
public class BrokerConstants {
|
||||
|
||||
public static final String INTERCEPT_HANDLER_PROPERTY_NAME = "intercept.handler";
|
||||
public static final String BROKER_INTERCEPTOR_THREAD_POOL_SIZE = "intercept.thread_pool.size";
|
||||
public static final String PERSISTENT_STORE_PROPERTY_NAME = "persistent_store";
|
||||
@@ -29,7 +31,8 @@ public class BrokerConstants {
|
||||
public static final String PORT_PROPERTY_NAME = "port";
|
||||
public static final String HOST_PROPERTY_NAME = "host";
|
||||
public static final String DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME = "moquette_store.mapdb";
|
||||
public static final String DEFAULT_PERSISTENT_PATH = System.getProperty("user.dir") + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
|
||||
public static final String DEFAULT_PERSISTENT_PATH = System.getProperty("user.dir") + File.separator
|
||||
+ DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
|
||||
public static final String WEB_SOCKET_PORT_PROPERTY_NAME = "websocket_port";
|
||||
public static final String WSS_PORT_PROPERTY_NAME = "secure_websocket_port";
|
||||
public static final String SSL_PORT_PROPERTY_NAME = "ssl_port";
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
|
||||
package io.moquette.connections;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* This interface will be used by an external codebase to retrieve and close
|
||||
* physical connections.
|
||||
* This interface will be used by an external codebase to retrieve and close physical connections.
|
||||
*
|
||||
* @author lbarrios
|
||||
*
|
||||
*/
|
||||
public interface IConnectionsManager {
|
||||
|
||||
/**
|
||||
* Returns the number of physical connections
|
||||
*
|
||||
@@ -26,8 +27,7 @@ public interface IConnectionsManager {
|
||||
public boolean isConnected(String clientID);
|
||||
|
||||
/**
|
||||
* Returns the identifiers of the MQTT clients that are connected to the
|
||||
* broker.
|
||||
* Returns the identifiers of the MQTT clients that are connected to the broker.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@@ -45,6 +45,7 @@ public interface IConnectionsManager {
|
||||
|
||||
/**
|
||||
* Returns the state of the session of a given client.
|
||||
*
|
||||
* @param clientID
|
||||
* @return
|
||||
*/
|
||||
@@ -52,6 +53,7 @@ public interface IConnectionsManager {
|
||||
|
||||
/**
|
||||
* Returns the state of all the sessions
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Collection<MqttSession> getSessions();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.connections;
|
||||
|
||||
/**
|
||||
@@ -7,6 +8,7 @@ package io.moquette.connections;
|
||||
*
|
||||
*/
|
||||
public class MqttConnectionMetrics {
|
||||
|
||||
private long readKb;
|
||||
private long writtenKb;
|
||||
private long readMessages;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
|
||||
package io.moquette.connections;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* A class that represents the overall connection status of a MQTT session. Its
|
||||
* instances will be used by an external codebase when the broker is configured
|
||||
* in embedded mode.
|
||||
* A class that represents the overall connection status of a MQTT session. Its instances will be
|
||||
* used by an external codebase when the broker is configured in embedded mode.
|
||||
*
|
||||
* @author lbarrios
|
||||
*
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.connections;
|
||||
|
||||
/**
|
||||
@@ -7,6 +8,7 @@ package io.moquette.connections;
|
||||
*
|
||||
*/
|
||||
public class MqttSubscription {
|
||||
|
||||
private final String requestedQos;
|
||||
private final String clientId;
|
||||
private final String topicFilter;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.interception;
|
||||
|
||||
import io.moquette.interception.messages.InterceptAcknowledgedMessage;
|
||||
@@ -36,23 +37,30 @@ public abstract class AbstractInterceptHandler implements InterceptHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnect(InterceptConnectMessage msg) {}
|
||||
public void onConnect(InterceptConnectMessage msg) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisconnect(InterceptDisconnectMessage msg) {}
|
||||
public void onDisconnect(InterceptDisconnectMessage msg) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnectionLost(InterceptConnectionLostMessage msg) {}
|
||||
public void onConnectionLost(InterceptConnectionLostMessage msg) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPublish(InterceptPublishMessage msg) {}
|
||||
public void onPublish(InterceptPublishMessage msg) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSubscribe(InterceptSubscribeMessage msg) {}
|
||||
public void onSubscribe(InterceptSubscribeMessage msg) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUnsubscribe(InterceptUnsubscribeMessage msg) {}
|
||||
public void onUnsubscribe(InterceptUnsubscribeMessage msg) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageAcknowledged(InterceptAcknowledgedMessage msg) {}
|
||||
public void onMessageAcknowledged(InterceptAcknowledgedMessage msg) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.interception;
|
||||
|
||||
import com.hazelcast.core.HazelcastInstance;
|
||||
@@ -7,7 +8,6 @@ import io.moquette.server.Server;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static io.moquette.spi.impl.Utils.readBytesAndRewind;
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
|
||||
package io.moquette.interception;
|
||||
|
||||
import io.moquette.interception.messages.InterceptPublishMessage;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import static io.moquette.spi.impl.Utils.readBytesAndRewind;
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.interception;
|
||||
|
||||
import io.moquette.interception.messages.*;
|
||||
@@ -24,28 +25,29 @@ import io.netty.handler.codec.mqtt.MqttMessage;
|
||||
* <p>
|
||||
* The events can act only as observers.
|
||||
* <p>
|
||||
* Almost every method receives a subclass of {@link MqttMessage}, except
|
||||
* <code>onDisconnect</code> that receives the client id string and
|
||||
* <code>onSubscribe</code> and <code>onUnsubscribe</code> that receive a
|
||||
* {@link Subscription} object.
|
||||
* Almost every method receives a subclass of {@link MqttMessage}, except <code>onDisconnect</code>
|
||||
* that receives the client id string and <code>onSubscribe</code> and <code>onUnsubscribe</code>
|
||||
* that receive a {@link Subscription} object.
|
||||
*
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public interface InterceptHandler {
|
||||
|
||||
public static final Class<?> ALL_MESSAGE_TYPES[] = { InterceptConnectMessage.class,
|
||||
InterceptDisconnectMessage.class, InterceptConnectionLostMessage.class, InterceptPublishMessage.class,
|
||||
InterceptSubscribeMessage.class, InterceptUnsubscribeMessage.class, InterceptAcknowledgedMessage.class };
|
||||
Class<?>[] ALL_MESSAGE_TYPES = {InterceptConnectMessage.class, InterceptDisconnectMessage.class,
|
||||
InterceptConnectionLostMessage.class, InterceptPublishMessage.class, InterceptSubscribeMessage.class,
|
||||
InterceptUnsubscribeMessage.class, InterceptAcknowledgedMessage.class};
|
||||
|
||||
/**
|
||||
* Returns the identifier of this intercept handler.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String getID();
|
||||
|
||||
/**
|
||||
* Returns the InterceptMessage subtypes that this handler can process. If the result is null or equal to ALL_MESSAGE_TYPES,
|
||||
* all the message types will be processed.
|
||||
* Returns the InterceptMessage subtypes that this handler can process. If the result is null or
|
||||
* equal to ALL_MESSAGE_TYPES, all the message types will be processed.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Class<?>[] getInterceptedMessageTypes();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.interception;
|
||||
|
||||
import io.moquette.interception.messages.InterceptAcknowledgedMessage;
|
||||
@@ -23,12 +24,10 @@ import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
/**
|
||||
* This interface is to be used internally by the broker components.
|
||||
* <p>
|
||||
* An interface is used instead of a class to allow more flexibility in changing
|
||||
* an implementation.
|
||||
* An interface is used instead of a class to allow more flexibility in changing an implementation.
|
||||
* <p>
|
||||
* Interceptor implementations forward notifications to a <code>InterceptHandler</code>,
|
||||
* that is normally a field. So, the implementations should act as a proxy to a custom
|
||||
* intercept handler.
|
||||
* Interceptor implementations forward notifications to a <code>InterceptHandler</code>, that is
|
||||
* normally a field. So, the implementations should act as a proxy to a custom intercept handler.
|
||||
*
|
||||
* @see InterceptHandler
|
||||
* @author Wagner Macedo
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
import io.netty.handler.codec.mqtt.MqttMessage;
|
||||
@@ -22,6 +23,7 @@ import io.netty.handler.codec.mqtt.MqttQoS;
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public abstract class InterceptAbstractMessage implements InterceptMessage {
|
||||
|
||||
private final MqttMessage msg;
|
||||
|
||||
InterceptAbstractMessage(MqttMessage msg) {
|
||||
|
||||
+2
@@ -1,8 +1,10 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
import static io.moquette.spi.IMessagesStore.StoredMessage;
|
||||
|
||||
public class InterceptAcknowledgedMessage implements InterceptMessage {
|
||||
|
||||
final private StoredMessage msg;
|
||||
private final String username;
|
||||
private final String topic;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
import io.netty.handler.codec.mqtt.MqttConnectMessage;
|
||||
@@ -6,6 +7,7 @@ import io.netty.handler.codec.mqtt.MqttConnectMessage;
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public class InterceptConnectMessage extends InterceptAbstractMessage {
|
||||
|
||||
private final MqttConnectMessage msg;
|
||||
|
||||
public InterceptConnectMessage(MqttConnectMessage msg) {
|
||||
|
||||
+2
@@ -1,9 +1,11 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
/**
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public class InterceptConnectionLostMessage implements InterceptMessage {
|
||||
|
||||
private final String clientID;
|
||||
private final String username;
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
/**
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public class InterceptDisconnectMessage implements InterceptMessage {
|
||||
|
||||
private final String clientID;
|
||||
private final String username;
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
/**
|
||||
* An interface that sets the root of the interceptor messages type hierarchy.
|
||||
*
|
||||
* @author lbarrios
|
||||
*
|
||||
*/
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
@@ -7,6 +8,7 @@ import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public class InterceptPublishMessage extends InterceptAbstractMessage {
|
||||
|
||||
private final MqttPublishMessage msg;
|
||||
private final String clientID;
|
||||
private final String username;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
import io.moquette.spi.impl.subscriptions.Subscription;
|
||||
@@ -7,6 +8,7 @@ import io.netty.handler.codec.mqtt.MqttQoS;
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public class InterceptSubscribeMessage implements InterceptMessage {
|
||||
|
||||
private final Subscription subscription;
|
||||
private final String username;
|
||||
|
||||
|
||||
+2
@@ -1,9 +1,11 @@
|
||||
|
||||
package io.moquette.interception.messages;
|
||||
|
||||
/**
|
||||
* @author Wagner Macedo
|
||||
*/
|
||||
public class InterceptUnsubscribeMessage implements InterceptMessage {
|
||||
|
||||
private final String topicFilter;
|
||||
private final String clientID;
|
||||
private final String username;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
|
||||
package io.moquette.logging;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
import io.moquette.interception.InterceptHandler;
|
||||
|
||||
public class LoggingUtils {
|
||||
|
||||
public static <T extends InterceptHandler> Collection<String> getInterceptorIds(Collection<T> handlers) {
|
||||
Collection<String> result = new ArrayList<>(handlers.size());
|
||||
for (T handler : handlers) {
|
||||
|
||||
@@ -13,15 +13,14 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.moquette.server.netty.AutoFlushHandler;
|
||||
import io.moquette.server.netty.NettyUtils;
|
||||
import io.moquette.server.netty.metrics.BytesMetrics;
|
||||
@@ -30,10 +29,9 @@ import io.moquette.server.netty.metrics.MessageMetrics;
|
||||
import io.moquette.server.netty.metrics.MessageMetricsHandler;
|
||||
import io.netty.channel.Channel;
|
||||
|
||||
|
||||
/**
|
||||
* Value object to maintain the information of single connection, like ClientID, Channel,
|
||||
* and clean session flag.
|
||||
* Value object to maintain the information of single connection, like ClientID, Channel, and clean
|
||||
* session flag.
|
||||
*
|
||||
*
|
||||
* @author andrea
|
||||
@@ -44,9 +42,15 @@ public class ConnectionDescriptor {
|
||||
|
||||
public enum ConnectionState {
|
||||
// Connection states
|
||||
DISCONNECTED, SENDACK, SESSION_CREATED, MESSAGES_REPUBLISHED, ESTABLISHED,
|
||||
DISCONNECTED,
|
||||
SENDACK,
|
||||
SESSION_CREATED,
|
||||
MESSAGES_REPUBLISHED,
|
||||
ESTABLISHED,
|
||||
// Disconnection states
|
||||
SUBSCRIPTIONS_REMOVED, MESSAGES_DROPPED, INTERCEPTORS_NOTIFIED;
|
||||
SUBSCRIPTIONS_REMOVED,
|
||||
MESSAGES_DROPPED,
|
||||
INTERCEPTORS_NOTIFIED;
|
||||
}
|
||||
|
||||
public final String clientID;
|
||||
@@ -66,10 +70,14 @@ public class ConnectionDescriptor {
|
||||
|
||||
public void setupAutoFlusher(int flushIntervalMs) {
|
||||
try {
|
||||
this.channel.pipeline().addAfter("idleEventHandler", "autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
|
||||
this.channel.pipeline().addAfter(
|
||||
"idleEventHandler",
|
||||
"autoFlusher",
|
||||
new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
|
||||
} catch (NoSuchElementException nseex) {
|
||||
// the idleEventHandler is not present on the pipeline
|
||||
this.channel.pipeline().addFirst("autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
|
||||
this.channel.pipeline()
|
||||
.addFirst("autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,35 +110,41 @@ public class ConnectionDescriptor {
|
||||
}
|
||||
|
||||
public boolean assignState(ConnectionState expected, ConnectionState newState) {
|
||||
LOG.debug("Updating state of connection descriptor. MqttClientId = {}, expectedState = {}, newState = {}.",
|
||||
clientID, expected, newState);
|
||||
LOG.debug(
|
||||
"Updating state of connection descriptor. MqttClientId = {}, expectedState = {}, newState = {}.",
|
||||
clientID,
|
||||
expected,
|
||||
newState);
|
||||
boolean retval = channelState.compareAndSet(expected, newState);
|
||||
if (!retval) {
|
||||
LOG.error(
|
||||
"Unable to update state of connection descriptor. MqttclientId = {}, expectedState = {}, newState = {}.",
|
||||
clientID, expected, newState);
|
||||
"Unable to update state of connection descriptor."
|
||||
+ " MqttclientId = {}, expectedState = {}, newState = {}.",
|
||||
clientID,
|
||||
expected,
|
||||
newState);
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ConnectionDescriptor{" + "clientID=" + clientID +
|
||||
", cleanSession=" + cleanSession +
|
||||
", state=" + channelState.get() +
|
||||
'}';
|
||||
return "ConnectionDescriptor{" + "clientID=" + clientID + ", cleanSession=" + cleanSession + ", state="
|
||||
+ channelState.get() + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
ConnectionDescriptor that = (ConnectionDescriptor) o;
|
||||
|
||||
if (clientID != null ? !clientID.equals(that.clientID) : that.clientID != null) return false;
|
||||
if (clientID != null ? !clientID.equals(that.clientID) : that.clientID != null)
|
||||
return false;
|
||||
return !(channel != null ? !channel.equals(that.channel) : that.channel != null);
|
||||
|
||||
}
|
||||
|
||||
public BytesMetrics getBytesMetrics() {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.connections.IConnectionsManager;
|
||||
@@ -13,7 +14,6 @@ import io.netty.handler.codec.mqtt.MqttMessage;
|
||||
import io.netty.handler.codec.mqtt.MqttMessageType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -43,15 +43,20 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
||||
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
|
||||
if (descriptor == null) {
|
||||
if (messageID != null) {
|
||||
LOG.error("Client has just disconnected. The {} message could not be sent. CId=<{}>, messageId={}",
|
||||
messageType, clientID, messageID);
|
||||
LOG.error(
|
||||
"Client has just disconnected. The {} message could not be sent. CId=<{}>, messageId={}",
|
||||
messageType,
|
||||
clientID,
|
||||
messageID);
|
||||
} else {
|
||||
LOG.error("Client has just disconnected. The {} could not be sent. CId=<{}>", messageType, clientID);
|
||||
LOG.error(
|
||||
"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 don't have to make the broker
|
||||
* crash: we'll just discard the PUBACK message.
|
||||
* If the client has just disconnected, its connection descriptor will be null. We
|
||||
* don't have to make the broker crash: we'll just discard the PUBACK message.
|
||||
*/
|
||||
return false;
|
||||
}
|
||||
@@ -99,8 +104,10 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
||||
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
|
||||
if (descriptor == null) {
|
||||
LOG.error(
|
||||
"The connection descriptor doesn't exist. The MQTT connection cannot be closed. CId=<{}>, closeImmediately = {}.",
|
||||
clientID, closeImmediately);
|
||||
"The connection descriptor doesn't exist. "
|
||||
+ "The MQTT connection cannot be closed. CId=<{}>, closeImmediately = {}.",
|
||||
clientID,
|
||||
closeImmediately);
|
||||
return false;
|
||||
}
|
||||
if (closeImmediately) {
|
||||
@@ -125,7 +132,7 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
||||
@Override
|
||||
public Collection<MqttSession> getSessions() {
|
||||
LOG.info("Retrieving status of all sessions.");
|
||||
Collection<MqttSession> result = new ArrayList<MqttSession>();
|
||||
Collection<MqttSession> result = new ArrayList<>();
|
||||
for (ClientSession session : sessionsStore.getAllSessions()) {
|
||||
result.add(buildMqttSession(session));
|
||||
}
|
||||
@@ -136,8 +143,12 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
||||
MqttSession result = new MqttSession();
|
||||
Collection<MqttSubscription> mqttSubscriptions = new ArrayList<>();
|
||||
for (Subscription subscription : session.getSubscriptions()) {
|
||||
mqttSubscriptions.add(new MqttSubscription(subscription.getRequestedQos().toString(),
|
||||
subscription.getClientId(), subscription.getTopicFilter(), subscription.isActive()));
|
||||
mqttSubscriptions.add(
|
||||
new MqttSubscription(
|
||||
subscription.getRequestedQos().toString(),
|
||||
subscription.getClientId(),
|
||||
subscription.getTopicFilter(),
|
||||
subscription.isActive()));
|
||||
}
|
||||
result.setActiveSubscriptions(mqttSubscriptions);
|
||||
result.setCleanSession(session.isCleanSession());
|
||||
@@ -146,8 +157,12 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
|
||||
result.setConnectionEstablished(true);
|
||||
BytesMetrics bytesMetrics = descriptor.getBytesMetrics();
|
||||
MessageMetrics messageMetrics = descriptor.getMessageMetrics();
|
||||
result.setConnectionMetrics(new MqttConnectionMetrics(bytesMetrics.readBytes(), bytesMetrics.wroteBytes(),
|
||||
messageMetrics.messagesRead(), messageMetrics.messagesWrote()));
|
||||
result.setConnectionMetrics(
|
||||
new MqttConnectionMetrics(
|
||||
bytesMetrics.readBytes(),
|
||||
bytesMetrics.wroteBytes(),
|
||||
messageMetrics.messagesRead(),
|
||||
messageMetrics.messagesWrote()));
|
||||
} else {
|
||||
result.setConnectionEstablished(false);
|
||||
}
|
||||
|
||||
@@ -13,12 +13,14 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
/**
|
||||
* Server constants keeper
|
||||
*/
|
||||
public class Constants {
|
||||
|
||||
public static final String ATTR_CLIENTID = "ClientID";
|
||||
public static final String CLEAN_SESSION = "cleanSession";
|
||||
public static final String KEEP_ALIVE = "keepAlive";
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -20,20 +21,18 @@ import io.moquette.server.config.IConfig;
|
||||
import io.moquette.spi.security.ISslContextCreator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URL;
|
||||
import java.security.*;
|
||||
import java.security.cert.CertificateException;
|
||||
|
||||
/**
|
||||
* Moquette server implementation to load SSL certificate from local filesystem path
|
||||
* configured in config file.
|
||||
* Moquette server implementation to load SSL certificate from local filesystem path configured in
|
||||
* config file.
|
||||
*
|
||||
* Created by andrea on 13/12/15.
|
||||
*/
|
||||
@@ -90,9 +89,11 @@ class DefaultMoquetteSslContextCreator implements ISslContextCreator {
|
||||
TrustManager[] trustManagers = null;
|
||||
if (needsClientAuth) {
|
||||
LOG.warn(
|
||||
"Client authentication is enabled. The keystore will be used as a truststore. KeystorePath = {}.",
|
||||
"Client authentication is enabled. "
|
||||
+ "The keystore will be used as a truststore. KeystorePath = {}.",
|
||||
jksPath);
|
||||
// use keystore as truststore, as server needs to trust certificates signed by the server certificates
|
||||
// use keystore as truststore, as server needs to trust certificates signed by the
|
||||
// server certificates
|
||||
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
tmf.init(ks);
|
||||
trustManagers = tmf.getTrustManagers();
|
||||
@@ -105,7 +106,10 @@ class DefaultMoquetteSslContextCreator implements ISslContextCreator {
|
||||
return serverContext;
|
||||
} catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException
|
||||
| KeyManagementException | IOException ex) {
|
||||
LOG.error("Unable to initialize SSL context. Cause = {}, errorMessage = {}.", ex.getCause(), ex.getMessage());
|
||||
LOG.error(
|
||||
"Unable to initialize SSL context. Cause = {}, errorMessage = {}.",
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import com.hazelcast.core.Message;
|
||||
@@ -13,6 +14,7 @@ import org.slf4j.LoggerFactory;
|
||||
* Created by mackristof on 28/05/2016.
|
||||
*/
|
||||
public class HazelcastListener implements MessageListener<HazelcastMsg> {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(HazelcastListener.class);
|
||||
|
||||
private final Server server;
|
||||
@@ -26,8 +28,11 @@ public class HazelcastListener implements MessageListener<HazelcastMsg> {
|
||||
try {
|
||||
if (!msg.getPublishingMember().equals(server.getHazelcastInstance().getCluster().getLocalMember())) {
|
||||
HazelcastMsg hzMsg = msg.getMessageObject();
|
||||
LOG.info("{} received from hazelcast for topic {} message: {}", hzMsg.getClientId(),
|
||||
hzMsg.getTopic(), hzMsg.getPayload());
|
||||
LOG.info(
|
||||
"{} received from hazelcast for topic {} message: {}",
|
||||
hzMsg.getClientId(),
|
||||
hzMsg.getTopic(),
|
||||
hzMsg.getPayload());
|
||||
// TODO pass forward this information in somehow publishMessage.setLocal(false);
|
||||
|
||||
MqttQoS qos = MqttQoS.valueOf(hzMsg.getQos());
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import com.hazelcast.config.ClasspathXmlConfig;
|
||||
@@ -38,18 +39,17 @@ import io.moquette.spi.security.ISslContextCreator;
|
||||
import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import static io.moquette.logging.LoggingUtils.getInterceptorIds;
|
||||
|
||||
/**
|
||||
* Launch a configured version of the server.
|
||||
*
|
||||
* @author andrea
|
||||
*/
|
||||
public class Server {
|
||||
@@ -74,6 +74,7 @@ public class Server {
|
||||
System.out.println("Server started, version 0.10-SNAPSHOT");
|
||||
// Bind a shutdown hook
|
||||
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
server.stopServer();
|
||||
@@ -82,9 +83,10 @@ public class Server {
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts Moquette bringing the configuration from the file
|
||||
* located at m_config/moquette.conf
|
||||
* @throws IOException in case of any IO error.
|
||||
* Starts Moquette bringing the configuration from the file located at m_config/moquette.conf
|
||||
*
|
||||
* @throws IOException
|
||||
* in case of any IO error.
|
||||
*/
|
||||
public void startServer() throws IOException {
|
||||
File defaultConfigurationFile = defaultConfigFile();
|
||||
@@ -101,8 +103,11 @@ public class Server {
|
||||
|
||||
/**
|
||||
* Starts Moquette bringing the configuration from the given file
|
||||
* @param configFile text file that contains the configuration.
|
||||
* @throws IOException in case of any IO Error.
|
||||
*
|
||||
* @param configFile
|
||||
* text file that contains the configuration.
|
||||
* @throws IOException
|
||||
* in case of any IO Error.
|
||||
*/
|
||||
public void startServer(File configFile) throws IOException {
|
||||
LOG.info("Starting Moquette server. Configuration file path = {}.", configFile.getAbsolutePath());
|
||||
@@ -120,8 +125,10 @@ public class Server {
|
||||
* <li>password_file</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param configProps the properties map to use as configuration.
|
||||
* @throws IOException in case of any IO Error.
|
||||
* @param configProps
|
||||
* the properties map to use as configuration.
|
||||
* @throws IOException
|
||||
* in case of any IO Error.
|
||||
*/
|
||||
public void startServer(Properties configProps) throws IOException {
|
||||
LOG.info("Starting Moquette server using properties object...");
|
||||
@@ -131,8 +138,11 @@ public class Server {
|
||||
|
||||
/**
|
||||
* Starts Moquette bringing the configuration files from the given Config implementation.
|
||||
* @param config the configuration to use to start the broker.
|
||||
* @throws IOException in case of any IO Error.
|
||||
*
|
||||
* @param config
|
||||
* the configuration to use to start the broker.
|
||||
* @throws IOException
|
||||
* in case of any IO Error.
|
||||
*/
|
||||
public void startServer(IConfig config) throws IOException {
|
||||
LOG.info("Starting Moquette server using IConfig instance...");
|
||||
@@ -140,20 +150,23 @@ public class Server {
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts Moquette with config provided by an implementation of IConfig class and with the
|
||||
* set of InterceptHandler.
|
||||
* @param config the configuration to use to start the broker.
|
||||
* @param handlers the handlers to install in the broker.
|
||||
* @throws IOException in case of any IO Error.
|
||||
* */
|
||||
* Starts Moquette with config provided by an implementation of IConfig class and with the set
|
||||
* of InterceptHandler.
|
||||
*
|
||||
* @param config
|
||||
* the configuration to use to start the broker.
|
||||
* @param handlers
|
||||
* the handlers to install in the broker.
|
||||
* @throws IOException
|
||||
* in case of any IO Error.
|
||||
*/
|
||||
public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException {
|
||||
LOG.info("Starting moquette server using IConfig instance and intercept handlers...");
|
||||
startServer(config, handlers, null, null, null);
|
||||
}
|
||||
|
||||
public void startServer(IConfig config, List<? extends InterceptHandler> handlers,
|
||||
ISslContextCreator sslCtxCreator, IAuthenticator authenticator,
|
||||
IAuthorizator authorizator) throws IOException {
|
||||
public void startServer(IConfig config, List<? extends InterceptHandler> handlers, ISslContextCreator sslCtxCreator,
|
||||
IAuthenticator authenticator, IAuthorizator authorizator) throws IOException {
|
||||
if (handlers == null) {
|
||||
handlers = Collections.emptyList();
|
||||
}
|
||||
@@ -164,10 +177,13 @@ public class Server {
|
||||
config.setProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, handlerProp);
|
||||
}
|
||||
configureCluster(config);
|
||||
LOG.info("Configuring Using persistent store file. Path = {}.", config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME));
|
||||
LOG.info(
|
||||
"Configuring Using persistent store file. Path = {}.",
|
||||
config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME));
|
||||
m_processorBootstrapper = new ProtocolProcessorBootstrapper();
|
||||
LOG.info("Initializing MQTT protocol processor...");
|
||||
final ProtocolProcessor processor = m_processorBootstrapper.init(config, handlers, authenticator, authorizator, this);
|
||||
final ProtocolProcessor processor = m_processorBootstrapper
|
||||
.init(config, handlers, authenticator, authorizator, this);
|
||||
|
||||
if (sslCtxCreator == null) {
|
||||
LOG.warn("Using default SSL context creator...");
|
||||
@@ -193,9 +209,9 @@ public class Server {
|
||||
String hzConfigPath = config.getProperty(BrokerConstants.HAZELCAST_CONFIGURATION);
|
||||
if (hzConfigPath != null) {
|
||||
boolean isHzConfigOnClasspath = this.getClass().getClassLoader().getResource(hzConfigPath) != null;
|
||||
Config hzconfig = isHzConfigOnClasspath ?
|
||||
new ClasspathXmlConfig(hzConfigPath) :
|
||||
new FileSystemXmlConfig(hzConfigPath);
|
||||
Config hzconfig = isHzConfigOnClasspath
|
||||
? new ClasspathXmlConfig(hzConfigPath)
|
||||
: new FileSystemXmlConfig(hzConfigPath);
|
||||
LOG.info("Starting Hazelcast instance. ConfigurationFile = {}.", hzconfig);
|
||||
hazelcastInstance = Hazelcast.newHazelcastInstance(hzconfig);
|
||||
} else {
|
||||
@@ -217,18 +233,23 @@ public class Server {
|
||||
}
|
||||
|
||||
/**
|
||||
* Use the broker to publish a message. It's intended for embedding applications.
|
||||
* It can be used only after the server is correctly started with startServer.
|
||||
* Use the broker to publish a message. It's intended for embedding applications. It can be used
|
||||
* only after the server is correctly started with startServer.
|
||||
*
|
||||
* @param msg the message to forward.
|
||||
* @param clientId the id of the sending server.
|
||||
* @throws IllegalStateException if the server is not yet started
|
||||
* */
|
||||
* @param msg
|
||||
* the message to forward.
|
||||
* @param clientId
|
||||
* the id of the sending server.
|
||||
* @throws IllegalStateException
|
||||
* if the server is not yet started
|
||||
*/
|
||||
public void internalPublish(MqttPublishMessage msg, final String clientId) {
|
||||
final int messageID = msg.variableHeader().messageId();
|
||||
if (!m_initialized) {
|
||||
LOG.error("The server is not started. The message cannot be published. MqttClientId = {}, messageId = {}",
|
||||
clientId, messageID);
|
||||
LOG.error(
|
||||
"The server is not started. The message cannot be published. MqttClientId = {}, messageId = {}",
|
||||
clientId,
|
||||
messageID);
|
||||
throw new IllegalStateException("Can't publish on a server is not yet started");
|
||||
}
|
||||
LOG.debug("Publishing message. MqttClientId = {}, messageId = {}", clientId, messageID);
|
||||
@@ -253,8 +274,8 @@ public class Server {
|
||||
}
|
||||
|
||||
/**
|
||||
* SPI method used by Broker embedded applications to get list of subscribers.
|
||||
* Returns null if the broker is not started.
|
||||
* SPI method used by Broker embedded applications to get list of subscribers. Returns null if
|
||||
* the broker is not started.
|
||||
*
|
||||
* @return list of subscriptions.
|
||||
*/
|
||||
@@ -267,14 +288,16 @@ public class Server {
|
||||
|
||||
/**
|
||||
* SPI method used by Broker embedded applications to add intercept handlers.
|
||||
* @param interceptHandler the handler to add.
|
||||
* */
|
||||
*
|
||||
* @param interceptHandler
|
||||
* the handler to add.
|
||||
*/
|
||||
public void addInterceptHandler(InterceptHandler interceptHandler) {
|
||||
if (!m_initialized) {
|
||||
LOG.error("The server is not started. The MQTT message interceptor cannot be added. InterceptorId = {}.",
|
||||
LOG.error(
|
||||
"The server is not started. The MQTT message interceptor cannot be added. InterceptorId = {}.",
|
||||
interceptHandler.getID());
|
||||
throw new IllegalStateException("Can't register interceptors on a server that is not yet started");
|
||||
|
||||
}
|
||||
LOG.info("Adding MQTT message interceptor. InterceptorId = {}.", interceptHandler.getID());
|
||||
m_processor.addInterceptHandler(interceptHandler);
|
||||
@@ -282,11 +305,14 @@ public class Server {
|
||||
|
||||
/**
|
||||
* SPI method used by Broker embedded applications to remove intercept handlers.
|
||||
* @param interceptHandler the handler to remove.
|
||||
* */
|
||||
*
|
||||
* @param interceptHandler
|
||||
* the handler to remove.
|
||||
*/
|
||||
public void removeInterceptHandler(InterceptHandler interceptHandler) {
|
||||
if (!m_initialized) {
|
||||
LOG.error("The server is not started. The MQTT message interceptor cannot be removed. InterceptorId = {}.",
|
||||
LOG.error(
|
||||
"The server is not started. The MQTT message interceptor cannot be removed. InterceptorId = {}.",
|
||||
interceptHandler.getID());
|
||||
throw new IllegalStateException("Can't deregister interceptors from a server that is not yet started");
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
import io.moquette.spi.impl.ProtocolProcessor;
|
||||
import io.moquette.spi.security.ISslContextCreator;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
@@ -30,8 +30,8 @@ import java.util.Properties;
|
||||
/**
|
||||
* Mosquitto configuration parser.
|
||||
*
|
||||
* A line that at the very first has # is a comment
|
||||
* Each line has key value format, where the separator used it the space.
|
||||
* A line that at the very first has # is a comment Each line has key value format, where the
|
||||
* separator used it the space.
|
||||
*
|
||||
* @author andrea
|
||||
*/
|
||||
@@ -50,14 +50,21 @@ class ConfigurationParser {
|
||||
return;
|
||||
}
|
||||
if (!file.exists()) {
|
||||
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()));
|
||||
LOG.warn(
|
||||
String.format(
|
||||
"parsing not existing file %s, so fallback on default configuration!",
|
||||
file.getAbsolutePath()));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
FileReader reader = new FileReader(file);
|
||||
parse(reader);
|
||||
} catch (FileNotFoundException fex) {
|
||||
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex);
|
||||
LOG.warn(
|
||||
String.format(
|
||||
"parsing not existing file %s, so fallback on default configuration!",
|
||||
file.getAbsolutePath()),
|
||||
fex);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -65,7 +72,8 @@ class ConfigurationParser {
|
||||
/**
|
||||
* Parse the configuration
|
||||
*
|
||||
* @throws ParseException if the format is not compliant.
|
||||
* @throws ParseException
|
||||
* if the format is not compliant.
|
||||
*/
|
||||
void parse(Reader reader) throws ParseException {
|
||||
if (reader == null) {
|
||||
@@ -103,12 +111,10 @@ class ConfigurationParser {
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
throw new ParseException("Failed to read", 1);
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
try {
|
||||
reader.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
} catch (IOException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.Reader;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -23,6 +24,7 @@ import io.moquette.BrokerConstants;
|
||||
* @author andrea
|
||||
*/
|
||||
public abstract class IConfig {
|
||||
|
||||
public static final String DEFAULT_CONFIG = "config/moquette.conf";
|
||||
|
||||
public abstract void setProperty(String name, String value);
|
||||
@@ -34,9 +36,11 @@ public abstract class IConfig {
|
||||
void assignDefaults() {
|
||||
setProperty(BrokerConstants.PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT));
|
||||
setProperty(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST);
|
||||
//setProperty(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT));
|
||||
// setProperty(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
|
||||
// Integer.toString(BrokerConstants.WEBSOCKET_PORT));
|
||||
setProperty(BrokerConstants.PASSWORD_FILE_PROPERTY_NAME, "");
|
||||
//setProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, BrokerConstants.DEFAULT_PERSISTENT_PATH);
|
||||
// setProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME,
|
||||
// BrokerConstants.DEFAULT_PERSISTENT_PATH);
|
||||
setProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, Boolean.TRUE.toString());
|
||||
setProperty(BrokerConstants.AUTHENTICATOR_CLASS_NAME, "");
|
||||
setProperty(BrokerConstants.AUTHORIZATOR_CLASS_NAME, "");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import java.io.Reader;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import java.util.Map;
|
||||
@@ -37,9 +38,11 @@ public class MemoryConfig extends IConfig {
|
||||
// private void createDefaults() {
|
||||
// m_properties.put(BrokerConstants.PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT));
|
||||
// m_properties.put(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST);
|
||||
// m_properties.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT));
|
||||
// m_properties.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
|
||||
// Integer.toString(BrokerConstants.WEBSOCKET_PORT));
|
||||
// m_properties.put(BrokerConstants.PASSWORD_FILE_PROPERTY_NAME, "");
|
||||
// m_properties.put(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, BrokerConstants.DEFAULT_PERSISTENT_PATH);
|
||||
// m_properties.put(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME,
|
||||
// BrokerConstants.DEFAULT_PERSISTENT_PATH);
|
||||
// m_properties.put(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, true);
|
||||
// m_properties.put(BrokerConstants.AUTHENTICATOR_CLASS_NAME, "");
|
||||
// m_properties.put(BrokerConstants.AUTHORIZATOR_CLASS_NAME, "");
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.Reader;
|
||||
import java.text.ParseException;
|
||||
import java.util.Properties;
|
||||
@@ -41,9 +41,8 @@ public class ResourceLoaderConfig extends IConfig {
|
||||
this.resourceLoader = resourceLoader;
|
||||
|
||||
/*
|
||||
* If we use a conditional operator, the loadResource() and the
|
||||
* loadDefaultResource() methods will be always called. This makes the
|
||||
* log traces confusing.
|
||||
* If we use a conditional operator, the loadResource() and the loadDefaultResource()
|
||||
* methods will be always called. This makes the log traces confusing.
|
||||
*/
|
||||
|
||||
Reader configReader;
|
||||
@@ -54,12 +53,16 @@ public class ResourceLoaderConfig extends IConfig {
|
||||
}
|
||||
|
||||
if (configReader == null) {
|
||||
LOG.error("The resource loader returned no configuration reader. ResourceLoader = {}, configName = {}.",
|
||||
resourceLoader.getName(), configName);
|
||||
LOG.error(
|
||||
"The resource loader returned no configuration reader. ResourceLoader = {}, configName = {}.",
|
||||
resourceLoader.getName(),
|
||||
configName);
|
||||
throw new IllegalArgumentException("Can't locate " + resourceLoader.getName() + " \"" + configName + "\"");
|
||||
}
|
||||
|
||||
LOG.info("Parsing configuration properties. ResourceLoader = {}, configName = {}.", resourceLoader.getName(),
|
||||
LOG.info(
|
||||
"Parsing configuration properties. ResourceLoader = {}, configName = {}.",
|
||||
resourceLoader.getName(),
|
||||
configName);
|
||||
ConfigurationParser confParser = new ConfigurationParser();
|
||||
m_properties = confParser.getProperties();
|
||||
@@ -68,8 +71,12 @@ public class ResourceLoaderConfig extends IConfig {
|
||||
confParser.parse(configReader);
|
||||
} catch (ParseException pex) {
|
||||
LOG.warn(
|
||||
"Unable to parse configuration properties. Using default configuration. ResourceLoader = {}, configName = {}, cause = {}, errorMessage = {}.",
|
||||
resourceLoader.getName(), configName, pex.getCause(), pex.getMessage());
|
||||
"Unable to parse configuration properties. Using default configuration. "
|
||||
+ "ResourceLoader = {}, configName = {}, cause = {}, errorMessage = {}.",
|
||||
resourceLoader.getName(),
|
||||
configName,
|
||||
pex.getCause(),
|
||||
pex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,23 +13,21 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty;
|
||||
|
||||
import io.netty.channel.ChannelDuplexHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.util.concurrent.EventExecutor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Auto-flush data on channel after a read timeout.
|
||||
* It's inspired by IdleStateHandler but it's specialized version, just flushing data after
|
||||
* no read is done on the channel after a period. It's used to avoid aggressively flushing from
|
||||
* the ProtocolProcessor.
|
||||
* Auto-flush data on channel after a read timeout. It's inspired by IdleStateHandler but it's
|
||||
* specialized version, just flushing data after no read is done on the channel after a period. It's
|
||||
* used to avoid aggressively flushing from the ProtocolProcessor.
|
||||
*/
|
||||
public class AutoFlushHandler extends ChannelDuplexHandler {
|
||||
|
||||
@@ -126,9 +124,7 @@ public class AutoFlushHandler extends ChannelDuplexHandler {
|
||||
EventExecutor loop = ctx.executor();
|
||||
|
||||
lastWriteTime = System.nanoTime();
|
||||
writerIdleTimeout = loop.schedule(
|
||||
new WriterIdleTimeoutTask(ctx),
|
||||
writerIdleTimeNanos, TimeUnit.NANOSECONDS);
|
||||
writerIdleTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), writerIdleTimeNanos, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
|
||||
private void destroy() {
|
||||
@@ -143,8 +139,10 @@ public class AutoFlushHandler extends ChannelDuplexHandler {
|
||||
/**
|
||||
* Is called when the write timeout expire.
|
||||
*
|
||||
* @param ctx the channel context.
|
||||
* @throws Exception in case of any IO error.
|
||||
* @param ctx
|
||||
* the channel context.
|
||||
* @throws Exception
|
||||
* in case of any IO error.
|
||||
*/
|
||||
protected void channelIdle(ChannelHandlerContext ctx/* , IdleStateEvent evt */) throws Exception {
|
||||
// ctx.fireUserEventTriggered(evt);
|
||||
@@ -173,16 +171,13 @@ public class AutoFlushHandler extends ChannelDuplexHandler {
|
||||
long nextDelay = writerIdleTimeNanos - (System.nanoTime() - lastWriteTime);
|
||||
if (nextDelay <= 0) {
|
||||
// Writer is idle - set a new timeout and notify the callback.
|
||||
writerIdleTimeout = ctx.executor().schedule(
|
||||
this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
|
||||
writerIdleTimeout = ctx.executor().schedule(this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
|
||||
try {
|
||||
/*IdleStateEvent event;
|
||||
if (firstWriterIdleEvent) {
|
||||
firstWriterIdleEvent = false;
|
||||
event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT;
|
||||
} else {
|
||||
event = IdleStateEvent.WRITER_IDLE_STATE_EVENT;
|
||||
}*/
|
||||
/*
|
||||
* IdleStateEvent event; if (firstWriterIdleEvent) { firstWriterIdleEvent =
|
||||
* false; event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT; } else { event =
|
||||
* IdleStateEvent.WRITER_IDLE_STATE_EVENT; }
|
||||
*/
|
||||
channelIdle(ctx/* , event */);
|
||||
} catch (Throwable t) {
|
||||
ctx.fireExceptionCaught(t);
|
||||
|
||||
@@ -13,17 +13,18 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty;
|
||||
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.handler.codec.mqtt.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MessageBuilder {
|
||||
|
||||
public static class PublishBuilder {
|
||||
|
||||
private String topic = null;
|
||||
private boolean retained = false;
|
||||
private MqttQoS qos;
|
||||
@@ -138,9 +139,13 @@ public class MessageBuilder {
|
||||
}
|
||||
|
||||
public MqttConnectMessage build() {
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0);
|
||||
MqttConnectVariableHeader mqttConnectVariableHeader =
|
||||
new MqttConnectVariableHeader(
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
|
||||
MqttMessageType.CONNECT,
|
||||
false,
|
||||
MqttQoS.AT_MOST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(
|
||||
version.protocolName(),
|
||||
version.protocolLevel(),
|
||||
hasUser,
|
||||
@@ -150,7 +155,12 @@ public class MessageBuilder {
|
||||
willFlag,
|
||||
cleanSession,
|
||||
keepAliveSecs);
|
||||
MqttConnectPayload mqttConnectPayload = new MqttConnectPayload(clientId, willTopic, willMessage, username, password);
|
||||
MqttConnectPayload mqttConnectPayload = new MqttConnectPayload(
|
||||
clientId,
|
||||
willTopic,
|
||||
willMessage,
|
||||
username,
|
||||
password);
|
||||
return new MqttConnectMessage(mqttFixedHeader, mqttConnectVariableHeader, mqttConnectPayload);
|
||||
}
|
||||
}
|
||||
@@ -171,7 +181,12 @@ public class MessageBuilder {
|
||||
}
|
||||
|
||||
public MqttSubscribeMessage build() {
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE, false, 0);
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
|
||||
MqttMessageType.SUBSCRIBE,
|
||||
false,
|
||||
MqttQoS.AT_LEAST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttMessageIdVariableHeader mqttVariableHeader = MqttMessageIdVariableHeader.from(messageId);
|
||||
MqttSubscribePayload mqttSubscribePayload = new MqttSubscribePayload(subscriptions);
|
||||
return new MqttSubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload);
|
||||
@@ -194,8 +209,12 @@ public class MessageBuilder {
|
||||
}
|
||||
|
||||
public MqttUnsubscribeMessage build() {
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBSCRIBE, false,
|
||||
MqttQoS.AT_LEAST_ONCE, false, 0);
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
|
||||
MqttMessageType.UNSUBSCRIBE,
|
||||
false,
|
||||
MqttQoS.AT_LEAST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttMessageIdVariableHeader mqttVariableHeader = MqttMessageIdVariableHeader.from(messageId);
|
||||
MqttUnsubscribePayload mqttSubscribePayload = new MqttUnsubscribePayload(topicFilters);
|
||||
return new MqttUnsubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload);
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.netty.channel.ChannelDuplexHandler;
|
||||
import io.netty.channel.ChannelHandler.Sharable;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
@@ -41,7 +41,9 @@ class MoquetteIdleTimeoutHandler extends ChannelDuplexHandler {
|
||||
}
|
||||
} else {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("Firing Netty event. MqttClientId = {}, eventClass = {}.", NettyUtils.clientID(ctx.channel()),
|
||||
LOG.debug(
|
||||
"Firing Netty event. MqttClientId = {}, eventClass = {}.",
|
||||
NettyUtils.clientID(ctx.channel()),
|
||||
evt.getClass().getName());
|
||||
}
|
||||
super.userEventTriggered(ctx, evt);
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -42,13 +43,11 @@ import io.netty.handler.timeout.IdleStateHandler;
|
||||
import io.netty.util.concurrent.Future;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.moquette.BrokerConstants.*;
|
||||
|
||||
/**
|
||||
@@ -62,10 +61,12 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
static class WebSocketFrameToByteBufDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {
|
||||
|
||||
@Override
|
||||
protected void decode(ChannelHandlerContext chc, BinaryWebSocketFrame frame, List<Object> out) throws Exception {
|
||||
protected void decode(ChannelHandlerContext chc, BinaryWebSocketFrame frame, List<Object> out)
|
||||
throws Exception {
|
||||
// convert the frame to a ByteBuf
|
||||
ByteBuf bb = frame.content();
|
||||
//System.out.println("WebSocketFrameToByteBufDecoder decode - " + ByteBufUtil.hexDump(bb));
|
||||
// System.out.println("WebSocketFrameToByteBufDecoder decode - " +
|
||||
// ByteBufUtil.hexDump(bb));
|
||||
bb.retain();
|
||||
out.add(bb);
|
||||
}
|
||||
@@ -77,7 +78,8 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
protected void encode(ChannelHandlerContext chc, ByteBuf bb, List<Object> out) throws Exception {
|
||||
// convert the ByteBuf to a WebSocketFrame
|
||||
BinaryWebSocketFrame result = new BinaryWebSocketFrame();
|
||||
//System.out.println("ByteBufToWebSocketFrameEncoder encode - " + ByteBufUtil.hexDump(bb));
|
||||
// System.out.println("ByteBufToWebSocketFrameEncoder encode - " +
|
||||
// ByteBufUtil.hexDump(bb));
|
||||
result.content().writeBytes(bb);
|
||||
out.add(result);
|
||||
}
|
||||
@@ -102,13 +104,17 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
private int nettyChannelTimeoutSeconds;
|
||||
|
||||
@Override
|
||||
public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator) throws IOException {
|
||||
public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator)
|
||||
throws IOException {
|
||||
LOG.info("Initializing Netty acceptor...");
|
||||
|
||||
nettySoBacklog = Integer.parseInt(props.getProperty(BrokerConstants.NETTY_SO_BACKLOG_PROPERTY_NAME, "128"));
|
||||
nettySoReuseaddr = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true"));
|
||||
nettyTcpNodelay = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true"));
|
||||
nettySoKeepalive = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true"));
|
||||
nettySoReuseaddr = Boolean
|
||||
.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true"));
|
||||
nettyTcpNodelay = Boolean
|
||||
.parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true"));
|
||||
nettySoKeepalive = Boolean
|
||||
.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true"));
|
||||
nettyChannelTimeoutSeconds = Integer
|
||||
.parseInt(props.getProperty(BrokerConstants.NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME, "10"));
|
||||
|
||||
@@ -134,9 +140,9 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
private void initFactory(String host, int port, String protocol, final PipelineInitializer pipeliner) {
|
||||
LOG.info("Initializing server. Protocol = {}.", protocol);
|
||||
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>() {
|
||||
|
||||
@Override
|
||||
public void initChannel(SocketChannel ch) throws Exception {
|
||||
ChannelPipeline pipeline = ch.pipeline();
|
||||
@@ -147,9 +153,7 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
throw th;
|
||||
}
|
||||
}
|
||||
})
|
||||
.option(ChannelOption.SO_BACKLOG, nettySoBacklog)
|
||||
.option(ChannelOption.SO_REUSEADDR, nettySoReuseaddr)
|
||||
}).option(ChannelOption.SO_BACKLOG, nettySoBacklog).option(ChannelOption.SO_REUSEADDR, nettySoReuseaddr)
|
||||
.option(ChannelOption.TCP_NODELAY, nettyTcpNodelay)
|
||||
.childOption(ChannelOption.SO_KEEPALIVE, nettySoKeepalive);
|
||||
try {
|
||||
@@ -169,11 +173,15 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
|
||||
String tcpPortProp = props.getProperty(PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
if (DISABLED_PORT_BIND.equals(tcpPortProp)) {
|
||||
LOG.info("The property {} has been setted to {}. TCP MQTT will be disabled.", BrokerConstants.PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
LOG.info(
|
||||
"The property {} has been setted to {}. TCP MQTT will be disabled.",
|
||||
BrokerConstants.PORT_PROPERTY_NAME,
|
||||
DISABLED_PORT_BIND);
|
||||
return;
|
||||
}
|
||||
int port = Integer.parseInt(tcpPortProp);
|
||||
initFactory(host, port, "TCP MQTT", new PipelineInitializer() {
|
||||
|
||||
@Override
|
||||
void init(ChannelPipeline pipeline) {
|
||||
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds));
|
||||
@@ -194,8 +202,10 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
String webSocketPortProp = props.getProperty(WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
if (DISABLED_PORT_BIND.equals(webSocketPortProp)) {
|
||||
// Do nothing no WebSocket configured
|
||||
LOG.info("The property {} has been setted to {}. Websocket MQTT will be disabled.",
|
||||
BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
LOG.info(
|
||||
"The property {} has been setted to {}. Websocket MQTT will be disabled.",
|
||||
BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
|
||||
DISABLED_PORT_BIND);
|
||||
return;
|
||||
}
|
||||
int port = Integer.parseInt(webSocketPortProp);
|
||||
@@ -204,11 +214,14 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
|
||||
String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
|
||||
initFactory(host, port, "Websocket MQTT", new PipelineInitializer() {
|
||||
|
||||
@Override
|
||||
void init(ChannelPipeline pipeline) {
|
||||
pipeline.addLast(new HttpServerCodec());
|
||||
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
|
||||
pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
||||
pipeline.addLast(
|
||||
"webSocketHandler",
|
||||
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
||||
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
|
||||
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
|
||||
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds));
|
||||
@@ -223,13 +236,16 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
});
|
||||
}
|
||||
|
||||
private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext) throws IOException {
|
||||
private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
|
||||
throws IOException {
|
||||
LOG.info("Configuring SSL MQTT transport...");
|
||||
String sslPortProp = props.getProperty(SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
if (DISABLED_PORT_BIND.equals(sslPortProp)) {
|
||||
// Do nothing no SSL configured
|
||||
LOG.info("The property {} has been setted to {}. SSL MQTT will be disabled.",
|
||||
BrokerConstants.SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
LOG.info(
|
||||
"The property {} has been setted to {}. SSL MQTT will be disabled.",
|
||||
BrokerConstants.SSL_PORT_PROPERTY_NAME,
|
||||
DISABLED_PORT_BIND);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -241,6 +257,7 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
|
||||
final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
|
||||
initFactory(host, sslPort, "SSL MQTT", new PipelineInitializer() {
|
||||
|
||||
@Override
|
||||
void init(ChannelPipeline pipeline) throws Exception {
|
||||
pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
|
||||
@@ -257,13 +274,16 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
});
|
||||
}
|
||||
|
||||
private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext) throws IOException {
|
||||
private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
|
||||
throws IOException {
|
||||
LOG.info("Configuring secure websocket MQTT transport...");
|
||||
String sslPortProp = props.getProperty(WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
if (DISABLED_PORT_BIND.equals(sslPortProp)) {
|
||||
// Do nothing no SSL configured
|
||||
LOG.info("The property {} has been setted to {}. Secure websocket MQTT will be disabled.",
|
||||
BrokerConstants.WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
|
||||
LOG.info(
|
||||
"The property {} has been setted to {}. Secure websocket MQTT will be disabled.",
|
||||
BrokerConstants.WSS_PORT_PROPERTY_NAME,
|
||||
DISABLED_PORT_BIND);
|
||||
return;
|
||||
}
|
||||
int sslPort = Integer.parseInt(sslPortProp);
|
||||
@@ -272,13 +292,16 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
|
||||
final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
|
||||
initFactory(host, sslPort, "Secure websocket", new PipelineInitializer() {
|
||||
|
||||
@Override
|
||||
void init(ChannelPipeline pipeline) throws Exception {
|
||||
pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
|
||||
pipeline.addLast("httpEncoder", new HttpResponseEncoder());
|
||||
pipeline.addLast("httpDecoder", new HttpRequestDecoder());
|
||||
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
|
||||
pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
||||
pipeline.addLast(
|
||||
"webSocketHandler",
|
||||
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
|
||||
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
|
||||
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
|
||||
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds));
|
||||
@@ -303,8 +326,8 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
Future<?> bossWaiter = m_bossGroup.shutdownGracefully();
|
||||
|
||||
/*
|
||||
* We shouldn't raise an IllegalStateException if we are interrupted. If
|
||||
* we did so, the broker is not shut down properly.
|
||||
* We shouldn't raise an IllegalStateException if we are interrupted. If we did so, the
|
||||
* broker is not shut down properly.
|
||||
*/
|
||||
LOG.info("Waiting for worker and boss event loop groups to terminate...");
|
||||
try {
|
||||
@@ -326,12 +349,16 @@ public class NettyAcceptor implements ServerAcceptor {
|
||||
|
||||
LOG.info("Collecting message metrics...");
|
||||
MessageMetrics metrics = m_metricsCollector.computeMetrics();
|
||||
LOG.info("The metrics have been collected. Read messages = {}, written messages = {}.",
|
||||
metrics.messagesRead(), metrics.messagesWrote());
|
||||
LOG.info(
|
||||
"The metrics have been collected. Read messages = {}, written messages = {}.",
|
||||
metrics.messagesRead(),
|
||||
metrics.messagesWrote());
|
||||
|
||||
LOG.info("Collecting bytes metrics...");
|
||||
BytesMetrics bytesMetrics = m_bytesMetricsCollector.computeMetrics();
|
||||
LOG.info("The bytes metrics have been collected. Read bytes = {}, written bytes = {}.", bytesMetrics.readBytes(),
|
||||
LOG.info(
|
||||
"The bytes metrics have been collected. Read bytes = {}, written bytes = {}.",
|
||||
bytesMetrics.readBytes(),
|
||||
bytesMetrics.wroteBytes());
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty;
|
||||
|
||||
import io.moquette.spi.impl.ProtocolProcessor;
|
||||
@@ -22,10 +23,8 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.mqtt.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author andrea
|
||||
@@ -75,7 +74,12 @@ public class NettyMQTTHandler extends ChannelInboundHandlerAdapter {
|
||||
m_processor.processPubAck(ctx.channel(), (MqttPubAckMessage) msg);
|
||||
break;
|
||||
case PINGREQ:
|
||||
MqttFixedHeader pingHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, AT_MOST_ONCE, false, 0);
|
||||
MqttFixedHeader pingHeader = new MqttFixedHeader(
|
||||
MqttMessageType.PINGRESP,
|
||||
false,
|
||||
AT_MOST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttMessage pingResp = new MqttMessage(pingHeader);
|
||||
ctx.writeAndFlush(pingResp);
|
||||
break;
|
||||
@@ -99,8 +103,11 @@ public class NettyMQTTHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
LOG.error(
|
||||
"An unexpected exception was caught while processing MQTT message. Closing Netty channel. MqttClientId = {}, cause = {}, errorMessage = {}.",
|
||||
NettyUtils.clientID(ctx.channel()), cause.getCause(), cause.getMessage());
|
||||
"An unexpected exception was caught while processing MQTT message. "
|
||||
+ "Closing Netty channel. MqttClientId = {}, cause = {}, errorMessage = {}.",
|
||||
NettyUtils.clientID(ctx.channel()),
|
||||
cause.getCause(),
|
||||
cause.getMessage());
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty;
|
||||
|
||||
import io.moquette.server.Constants;
|
||||
|
||||
@@ -13,9 +13,11 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
public class BytesMetrics {
|
||||
|
||||
private long m_readBytes = 0;
|
||||
private long m_wroteBytes = 0;
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
@@ -55,10 +56,8 @@ public class BytesMetricsHandler extends ChannelDuplexHandler {
|
||||
ctx.write(msg, promise);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void close(ChannelHandlerContext ctx,
|
||||
ChannelPromise promise) throws Exception {
|
||||
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
|
||||
BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
|
||||
m_collector.sumReadBytes(metrics.readBytes());
|
||||
m_collector.sumWroteBytes(metrics.wroteBytes());
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
import io.moquette.server.netty.NettyUtils;
|
||||
@@ -23,7 +24,6 @@ import io.netty.channel.ChannelPromise;
|
||||
import io.netty.handler.codec.mqtt.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static io.moquette.spi.impl.Utils.messageId;
|
||||
|
||||
/**
|
||||
@@ -54,7 +54,11 @@ public class MQTTMessageLogger extends ChannelDuplexHandler {
|
||||
break;
|
||||
case SUBSCRIBE:
|
||||
MqttSubscribeMessage subscribe = (MqttSubscribeMessage) msg;
|
||||
LOG.info("{} SUBSCRIBE <{}> to topics {}", direction, clientID, subscribe.payload().topicSubscriptions());
|
||||
LOG.info(
|
||||
"{} SUBSCRIBE <{}> to topics {}",
|
||||
direction,
|
||||
clientID,
|
||||
subscribe.payload().topicSubscriptions());
|
||||
break;
|
||||
case UNSUBSCRIBE:
|
||||
MqttUnsubscribeMessage unsubscribe = (MqttUnsubscribeMessage) msg;
|
||||
|
||||
@@ -13,9 +13,11 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
public class MessageMetrics {
|
||||
|
||||
private long m_messagesRead = 0;
|
||||
private long m_messageWrote = 0;
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
@@ -21,6 +22,7 @@ import java.util.concurrent.atomic.AtomicLong;
|
||||
* Collects all the metrics from the various pipeline.
|
||||
*/
|
||||
public class MessageMetricsCollector {
|
||||
|
||||
private AtomicLong readMsgs = new AtomicLong();
|
||||
private AtomicLong wroteMsgs = new AtomicLong();
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server.netty.metrics;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
@@ -54,10 +55,8 @@ public class MessageMetricsHandler extends ChannelDuplexHandler {
|
||||
ctx.write(msg, promise);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void close(ChannelHandlerContext ctx,
|
||||
ChannelPromise promise) throws Exception {
|
||||
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
|
||||
MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
|
||||
m_collector.sumReadMessages(metrics.messagesRead());
|
||||
m_collector.sumWroteMessages(metrics.messagesWrote());
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi;
|
||||
|
||||
import io.moquette.spi.ISessionsStore.ClientTopicCouple;
|
||||
@@ -20,7 +21,6 @@ import io.moquette.spi.impl.subscriptions.Subscription;
|
||||
import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
@@ -55,7 +55,8 @@ public class ClientSession {
|
||||
|
||||
private volatile boolean cleanSession;
|
||||
|
||||
// private BlockingQueue<AbstractMessage> m_queueToPublish = new ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE);
|
||||
// private BlockingQueue<AbstractMessage> m_queueToPublish = new
|
||||
// ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE);
|
||||
|
||||
public ClientSession(String clientID, IMessagesStore messagesStore, ISessionsStore sessionsStore,
|
||||
boolean cleanSession) {
|
||||
@@ -66,12 +67,12 @@ public class ClientSession {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of persisted publishes for the given clientID.
|
||||
* For QoS1 and QoS2 with clean session flag, this method return the list of
|
||||
* missed publish events while the client was disconnected.
|
||||
* Return the list of persisted publishes for the given clientID. For QoS1 and QoS2 with clean
|
||||
* session flag, this method return the list of missed publish events while the client was
|
||||
* disconnected.
|
||||
*
|
||||
* @return the list of messages to be delivered for client related to the session.
|
||||
* */
|
||||
*/
|
||||
public BlockingQueue<IMessagesStore.StoredMessage> queue() {
|
||||
LOG.info("Retrieving stored messages. MqttClientId = {}.", clientID);
|
||||
return this.m_sessionsStore.queue(clientID);
|
||||
@@ -83,11 +84,16 @@ public class ClientSession {
|
||||
}
|
||||
|
||||
public boolean subscribe(Subscription newSubscription) {
|
||||
LOG.info("Adding new subscription. MqttClientId = {}, topics = {}, qos = {}.", newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter(), newSubscription.getRequestedQos());
|
||||
LOG.info(
|
||||
"Adding new subscription. MqttClientId = {}, topics = {}, qos = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter(),
|
||||
newSubscription.getRequestedQos());
|
||||
boolean validTopic = SubscriptionsStore.validate(newSubscription.getTopicFilter());
|
||||
if (!validTopic) {
|
||||
LOG.warn("The topic filter is not valid. MqttClientId = {}, topics = {}.", newSubscription.getClientId(),
|
||||
LOG.warn(
|
||||
"The topic filter is not valid. MqttClientId = {}, topics = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter());
|
||||
// send SUBACK with 0x80 for this topic filter
|
||||
return false;
|
||||
@@ -97,8 +103,12 @@ public class ClientSession {
|
||||
// update the selected subscriptions if not present or if has a greater qos
|
||||
if (existingSub == null || existingSub.getRequestedQos().value() < newSubscription.getRequestedQos().value()) {
|
||||
if (existingSub != null) {
|
||||
LOG.info("The subscription already existed with a lower QoS value. It will be updated. MqttClientId = {}, topics = {}, existingQos = {}, newQos = {}.",
|
||||
newSubscription.getClientId(), newSubscription.getTopicFilter(), existingSub.getRequestedQos(),
|
||||
LOG.info(
|
||||
"The subscription already existed with a lower QoS value. It will be updated. "
|
||||
+ "MqttClientId = {}, topics = {}, existingQos = {}, newQos = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter(),
|
||||
existingSub.getRequestedQos(),
|
||||
newSubscription.getRequestedQos());
|
||||
subscriptions.remove(newSubscription);
|
||||
}
|
||||
@@ -126,7 +136,6 @@ public class ClientSession {
|
||||
// cleanup topic subscriptions
|
||||
cleanSession();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void cleanSession() {
|
||||
@@ -170,8 +179,10 @@ public class ClientSession {
|
||||
|
||||
/**
|
||||
* Enqueue a message to be sent to the client.
|
||||
* @param message the message to enqueue.
|
||||
* */
|
||||
*
|
||||
* @param message
|
||||
* the message to enqueue.
|
||||
*/
|
||||
public void enqueue(IMessagesStore.StoredMessage message) {
|
||||
this.m_sessionsStore.queue(this.clientID).add(message);
|
||||
}
|
||||
|
||||
@@ -13,11 +13,12 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi;
|
||||
|
||||
/**
|
||||
*/
|
||||
public interface IMatchingCondition {
|
||||
|
||||
boolean match(String key);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,12 +13,12 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.handler.codec.mqtt.MqttQoS;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Collection;
|
||||
@@ -29,6 +29,7 @@ import java.util.Collection;
|
||||
public interface IMessagesStore {
|
||||
|
||||
class StoredMessage implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1755296138639817304L;
|
||||
final MqttQoS m_qos;
|
||||
final byte[] m_payload;
|
||||
@@ -95,41 +96,42 @@ public interface IMessagesStore {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PublishEvent{" +
|
||||
"m_msgID=" + m_msgID +
|
||||
", clientID='" + m_clientID + '\'' +
|
||||
", m_retain=" + m_retained +
|
||||
", m_qos=" + m_qos +
|
||||
", m_topic='" + m_topic + '\'' +
|
||||
'}';
|
||||
return "PublishEvent{" + "m_msgID=" + m_msgID + ", clientID='" + m_clientID + '\'' + ", m_retain="
|
||||
+ m_retained + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + '}';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to initialize all persistent store structures
|
||||
* */
|
||||
*/
|
||||
void initStore();
|
||||
|
||||
/**
|
||||
* Persist the message.
|
||||
* If the message is empty then the topic is cleaned, else it's stored.
|
||||
* @param topic for the retained.
|
||||
* @param guid of the message to mark as retained.
|
||||
* Persist the message. If the message is empty then the topic is cleaned, else it's stored.
|
||||
*
|
||||
* @param topic
|
||||
* for the retained.
|
||||
* @param guid
|
||||
* of the message to mark as retained.
|
||||
*/
|
||||
void storeRetained(String topic, MessageGUID guid);
|
||||
|
||||
/**
|
||||
* Return a list of retained messages that satisfy the condition.
|
||||
* @param condition the condition to match during the search.
|
||||
*
|
||||
* @param condition
|
||||
* the condition to match during the search.
|
||||
* @return the collection of matching messages.
|
||||
*/
|
||||
Collection<StoredMessage> searchMatching(IMatchingCondition condition);
|
||||
|
||||
/**
|
||||
* Persist the message.
|
||||
* @param storedMessage the message to store for future usage.
|
||||
*
|
||||
* @param storedMessage
|
||||
* the message to store for future usage.
|
||||
* @return the unique id in the storage (guid).
|
||||
* */
|
||||
*/
|
||||
MessageGUID storePublishForFuture(StoredMessage storedMessage);
|
||||
|
||||
void dropMessagesInSession(String clientID);
|
||||
|
||||
@@ -13,13 +13,13 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi;
|
||||
|
||||
/**
|
||||
* Callback interface used to be notified of some events from the input event queue.
|
||||
*
|
||||
* It's the abstraction of the messaging stuff attached in after the front protocol
|
||||
* parsing stuff.
|
||||
* It's the abstraction of the messaging stuff attached in after the front protocol parsing stuff.
|
||||
*
|
||||
* @author andrea
|
||||
*/
|
||||
|
||||
@@ -13,12 +13,12 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
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.impl.subscriptions.Subscription;
|
||||
|
||||
@@ -30,6 +30,7 @@ import io.moquette.spi.impl.subscriptions.Subscription;
|
||||
public interface ISessionsStore {
|
||||
|
||||
class ClientTopicCouple {
|
||||
|
||||
public final String topicFilter;
|
||||
public final String clientID;
|
||||
|
||||
@@ -40,12 +41,15 @@ public interface ISessionsStore {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
ClientTopicCouple that = (ClientTopicCouple) o;
|
||||
|
||||
if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null) return false;
|
||||
if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null)
|
||||
return false;
|
||||
return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null);
|
||||
}
|
||||
|
||||
@@ -58,10 +62,7 @@ public interface ISessionsStore {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ClientTopicCouple{" +
|
||||
"topicFilter='" + topicFilter + '\'' +
|
||||
", clientID='" + clientID + '\'' +
|
||||
'}';
|
||||
return "ClientTopicCouple{" + "topicFilter='" + topicFilter + '\'' + ", clientID='" + clientID + '\'' + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -72,32 +73,40 @@ public interface ISessionsStore {
|
||||
|
||||
/**
|
||||
* Add a new subscription to the session
|
||||
* @param newSubscription the subscription to add.
|
||||
*
|
||||
* @param newSubscription
|
||||
* the subscription to add.
|
||||
*/
|
||||
void addNewSubscription(Subscription newSubscription);
|
||||
|
||||
/**
|
||||
* Removed a specific subscription
|
||||
* @param topic the topic of the subscription.
|
||||
* @param clientID the session client.
|
||||
* */
|
||||
*
|
||||
* @param topic
|
||||
* the topic of the subscription.
|
||||
* @param clientID
|
||||
* the session client.
|
||||
*/
|
||||
void removeSubscription(String topic, String clientID);
|
||||
|
||||
/**
|
||||
* Remove all the subscriptions of the session
|
||||
* @param sessionID the client ID
|
||||
*
|
||||
* @param sessionID
|
||||
* the client ID
|
||||
*/
|
||||
void wipeSubscriptions(String sessionID);
|
||||
|
||||
/**
|
||||
* Return all topic filters to recreate the subscription tree.
|
||||
* */
|
||||
*/
|
||||
List<ClientTopicCouple> listAllSubscriptions();
|
||||
|
||||
/**
|
||||
* @param couple the subscription descriptor.
|
||||
* @param couple
|
||||
* the subscription descriptor.
|
||||
* @return the subscription stored by clientID and topicFilter, if any else null;
|
||||
* */
|
||||
*/
|
||||
Subscription getSubscription(ClientTopicCouple couple);
|
||||
|
||||
/*
|
||||
@@ -106,7 +115,8 @@ public interface ISessionsStore {
|
||||
List<Subscription> getSubscriptions();
|
||||
|
||||
/**
|
||||
* @param clientID the session client ID.
|
||||
* @param clientID
|
||||
* the session client ID.
|
||||
* @return true iff there are subscriptions persisted with clientID
|
||||
*/
|
||||
boolean contains(String clientID);
|
||||
@@ -114,13 +124,15 @@ public interface ISessionsStore {
|
||||
ClientSession createNewSession(String clientID, boolean cleanSession);
|
||||
|
||||
/**
|
||||
* @param clientID the client owning the session.
|
||||
* @param clientID
|
||||
* the client owning the session.
|
||||
* @return the session for the given clientID, null if not found.
|
||||
* */
|
||||
*/
|
||||
ClientSession sessionForClient(String clientID);
|
||||
|
||||
/**
|
||||
* Returns all the sessions
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Collection<ClientSession> getAllSessions();
|
||||
@@ -129,24 +141,32 @@ public interface ISessionsStore {
|
||||
|
||||
/**
|
||||
* Save the binding messageID, clientID - guid
|
||||
* @param clientID the client ID
|
||||
* @param messageID the message ID
|
||||
* @param guid the uuid of the message to mark as inflight.
|
||||
* */
|
||||
*
|
||||
* @param clientID
|
||||
* the client ID
|
||||
* @param messageID
|
||||
* the message ID
|
||||
* @param guid
|
||||
* the uuid of the message to mark as inflight.
|
||||
*/
|
||||
void inFlight(String clientID, int messageID, MessageGUID guid);
|
||||
|
||||
/**
|
||||
* Return the next valid packetIdentifier for the given client session.
|
||||
* @param clientID the clientID requesting next packet id.
|
||||
*
|
||||
* @param clientID
|
||||
* the clientID requesting next packet id.
|
||||
* @return the next valid id.
|
||||
* */
|
||||
*/
|
||||
int nextPacketID(String clientID);
|
||||
|
||||
/**
|
||||
* List the guids for retained messages for the session
|
||||
* @param clientID the client ID owning the queue.
|
||||
*
|
||||
* @param clientID
|
||||
* the client ID owning the queue.
|
||||
* @return the list of queue message UUIDs.
|
||||
* */
|
||||
*/
|
||||
BlockingQueue<StoredMessage> queue(String clientID);
|
||||
|
||||
void dropQueue(String clientID);
|
||||
@@ -154,10 +174,12 @@ public interface ISessionsStore {
|
||||
void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID);
|
||||
|
||||
/**
|
||||
* @param clientID the client ID accessing the second phase.
|
||||
* @param messageID the message ID that reached the second phase.
|
||||
* @param clientID
|
||||
* the client ID accessing the second phase.
|
||||
* @param messageID
|
||||
* the message ID that reached the second phase.
|
||||
* @return the guid of message just acked.
|
||||
* */
|
||||
*/
|
||||
MessageGUID secondPhaseAcknowledged(String clientID, int messageID);
|
||||
|
||||
MessageGUID mapToGuid(String clientID, int messageID);
|
||||
@@ -181,8 +203,7 @@ public interface ISessionsStore {
|
||||
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
|
||||
* @return
|
||||
|
||||
@@ -13,14 +13,16 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Value object for GUIDs of messages.
|
||||
* */
|
||||
*/
|
||||
public class MessageGUID implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 4315161987111542406L;
|
||||
private final String guid;
|
||||
|
||||
@@ -30,13 +32,14 @@ public class MessageGUID implements Serializable {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
MessageGUID that = (MessageGUID) o;
|
||||
|
||||
return guid != null ? guid.equals(that.guid) : that.guid == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -46,8 +49,6 @@ public class MessageGUID implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MessageGUID{" +
|
||||
"guid='" + guid + '\'' +
|
||||
'}';
|
||||
return "MessageGUID{" + "guid='" + guid + '\'' + '}';
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -25,7 +26,6 @@ import io.netty.handler.codec.mqtt.MqttConnectMessage;
|
||||
import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -33,7 +33,6 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.moquette.logging.LoggingUtils.getInterceptorIds;
|
||||
|
||||
/**
|
||||
@@ -61,6 +60,7 @@ final class BrokerInterceptor implements Interceptor {
|
||||
|
||||
/**
|
||||
* Configures a broker interceptor, with a thread pool of one thread.
|
||||
*
|
||||
* @param handlers
|
||||
*/
|
||||
public BrokerInterceptor(List<InterceptHandler> handlers) {
|
||||
@@ -68,8 +68,7 @@ final class BrokerInterceptor implements Interceptor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a broker interceptor using the pool size specified in the
|
||||
* IConfig argument.
|
||||
* Configures a broker interceptor using the pool size specified in the IConfig argument.
|
||||
*/
|
||||
public BrokerInterceptor(IConfig props, List<InterceptHandler> handlers) {
|
||||
this(Integer.parseInt(props.getProperty(BrokerConstants.BROKER_INTERCEPTOR_THREAD_POOL_SIZE, "1")), handlers);
|
||||
@@ -84,7 +83,8 @@ final class BrokerInterceptor implements Interceptor {
|
||||
try {
|
||||
LOG.info("Waiting for thread pool tasks to terminate...");
|
||||
executor.awaitTermination(10L, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {}
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
if (!executor.isTerminated()) {
|
||||
LOG.warn("Forcing shutdown of interceptor thread pool...");
|
||||
executor.shutdownNow();
|
||||
@@ -94,9 +94,12 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void notifyClientConnected(final MqttConnectMessage msg) {
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) {
|
||||
LOG.debug("Sending MQTT CONNECT message to interceptor. MqttClientId = {}, interceptorId = {}.",
|
||||
msg.payload().clientIdentifier(), handler.getID());
|
||||
LOG.debug(
|
||||
"Sending MQTT CONNECT message to interceptor. MqttClientId = {}, interceptorId = {}.",
|
||||
msg.payload().clientIdentifier(),
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onConnect(new InterceptConnectMessage(msg));
|
||||
@@ -108,9 +111,14 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void notifyClientDisconnected(final String clientID, final String username) {
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) {
|
||||
LOG.debug("Notifying MQTT client disconnection to interceptor. MqttClientId = {}, username = {}, " +
|
||||
"interceptorId = {}.", clientID, username, handler.getID());
|
||||
LOG.debug(
|
||||
"Notifying MQTT client disconnection to interceptor. MqttClientId = {}, username = {}, "
|
||||
+ "interceptorId = {}.",
|
||||
clientID,
|
||||
username,
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onDisconnect(new InterceptDisconnectMessage(clientID, username));
|
||||
@@ -122,9 +130,14 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void notifyClientConnectionLost(final String clientID, final String username) {
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptConnectionLostMessage.class)) {
|
||||
LOG.debug("Notifying unexpected MQTT client disconnection to interceptor. MqttClientId = {}, " +
|
||||
"username = {}, interceptorId = {}.", clientID, username, handler.getID());
|
||||
LOG.debug(
|
||||
"Notifying unexpected MQTT client disconnection to interceptor. MqttClientId = {}, "
|
||||
+ "username = {}, interceptorId = {}.",
|
||||
clientID,
|
||||
username,
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onConnectionLost(new InterceptConnectionLostMessage(clientID, username));
|
||||
@@ -138,9 +151,15 @@ final class BrokerInterceptor implements Interceptor {
|
||||
int messageId = msg.variableHeader().messageId();
|
||||
String topic = msg.variableHeader().topicName();
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) {
|
||||
LOG.debug("Notifying MQTT PUBLISH message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, " +
|
||||
"interceptorId = {}.", clientID, messageId, topic, handler.getID());
|
||||
LOG.debug(
|
||||
"Notifying MQTT PUBLISH message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, "
|
||||
+ "interceptorId = {}.",
|
||||
clientID,
|
||||
messageId,
|
||||
topic,
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onPublish(new InterceptPublishMessage(msg, clientID, username));
|
||||
@@ -152,9 +171,14 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void notifyTopicSubscribed(final Subscription sub, final String username) {
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) {
|
||||
LOG.debug("Notifying MQTT SUBSCRIBE message to interceptor. MqttClientId = {}, topicFilter = {}, " +
|
||||
"interceptorId = {}.", sub.getClientId(), sub.getTopicFilter(), handler.getID());
|
||||
LOG.debug(
|
||||
"Notifying MQTT SUBSCRIBE message to interceptor. MqttClientId = {}, topicFilter = {}, "
|
||||
+ "interceptorId = {}.",
|
||||
sub.getClientId(),
|
||||
sub.getTopicFilter(),
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onSubscribe(new InterceptSubscribeMessage(sub, username));
|
||||
@@ -166,9 +190,14 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) {
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) {
|
||||
LOG.debug("Notifying MQTT UNSUBSCRIBE message to interceptor. MqttClientId = {}, topic = {}, " +
|
||||
"interceptorId = {}.", clientID, topic, handler.getID());
|
||||
LOG.debug(
|
||||
"Notifying MQTT UNSUBSCRIBE message to interceptor. MqttClientId = {}, topic = {}, "
|
||||
+ "interceptorId = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID, username));
|
||||
@@ -180,10 +209,15 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg) {
|
||||
for (final InterceptHandler handler : this.handlers.get(InterceptAcknowledgedMessage.class)) {
|
||||
LOG.debug("Notifying MQTT ACK message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, " +
|
||||
"interceptorId = {}.",
|
||||
msg.getMsg().getClientID(), msg.getMsg().getMessageID(), msg.getTopic(), handler.getID());
|
||||
LOG.debug(
|
||||
"Notifying MQTT ACK message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, "
|
||||
+ "interceptorId = {}.",
|
||||
msg.getMsg().getClientID(),
|
||||
msg.getMsg().getMessageID(),
|
||||
msg.getTopic(),
|
||||
handler.getID());
|
||||
executor.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
handler.onMessageAcknowledged(msg);
|
||||
@@ -195,8 +229,10 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void addInterceptHandler(InterceptHandler interceptHandler) {
|
||||
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
|
||||
LOG.info("Adding MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
|
||||
interceptHandler.getID(), interceptedMessageTypes);
|
||||
LOG.info(
|
||||
"Adding MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
|
||||
interceptHandler.getID(),
|
||||
interceptedMessageTypes);
|
||||
for (Class<?> interceptMessageType : interceptedMessageTypes) {
|
||||
this.handlers.get(interceptMessageType).add(interceptHandler);
|
||||
}
|
||||
@@ -205,15 +241,17 @@ final class BrokerInterceptor implements Interceptor {
|
||||
@Override
|
||||
public void removeInterceptHandler(InterceptHandler interceptHandler) {
|
||||
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
|
||||
LOG.info("Removing MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
|
||||
interceptHandler.getID(), interceptedMessageTypes);
|
||||
LOG.info(
|
||||
"Removing MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
|
||||
interceptHandler.getID(),
|
||||
interceptedMessageTypes);
|
||||
for (Class<?> interceptMessageType : interceptedMessageTypes) {
|
||||
this.handlers.get(interceptMessageType).remove(interceptHandler);
|
||||
}
|
||||
}
|
||||
|
||||
private static Class<?>[] getInterceptedMessageTypes(InterceptHandler interceptHandler) {
|
||||
Class<?> interceptedMessageTypes[] = interceptHandler.getInterceptedMessageTypes();
|
||||
Class<?>[] interceptedMessageTypes = interceptHandler.getInterceptedMessageTypes();
|
||||
if (interceptedMessageTypes == null) {
|
||||
return InterceptHandler.ALL_MESSAGE_TYPES;
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/**
|
||||
@@ -24,6 +24,7 @@ import java.nio.ByteBuffer;
|
||||
* @author andrea
|
||||
*/
|
||||
class DebugUtils {
|
||||
|
||||
static String payload2Str(ByteBuffer content) {
|
||||
byte[] b = new byte[content.remaining()];
|
||||
content.mark();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.spi.ClientSession;
|
||||
import io.moquette.spi.IMessagesStore;
|
||||
@@ -7,7 +7,6 @@ import io.netty.buffer.ByteBuf;
|
||||
import io.netty.handler.codec.mqtt.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
@@ -28,8 +27,13 @@ class InternalRepublisher {
|
||||
// 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. MqttClientId = {}, packetId = {}, messageId = {}, topic = {}.",
|
||||
targetSession.clientID, packetID, storedMsg.getMessageID(), storedMsg.getTopic());
|
||||
LOG.debug(
|
||||
"Adding message to inflight zone. "
|
||||
+ "MqttClientId = {}, packetId = {}, messageId = {}, topic = {}.",
|
||||
targetSession.clientID,
|
||||
packetID,
|
||||
storedMsg.getMessageID(),
|
||||
storedMsg.getTopic());
|
||||
targetSession.inFlightAckWaiting(storedMsg.getGuid(), packetID);
|
||||
}
|
||||
MqttPublishMessage publishMsg = retainedPublish(storedMsg);
|
||||
@@ -41,16 +45,18 @@ class InternalRepublisher {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
void publishStored(ClientSession clientSession, BlockingQueue<IMessagesStore.StoredMessage> publishedEvents) {
|
||||
List<IMessagesStore.StoredMessage> storedPublishes = new ArrayList<>();
|
||||
publishedEvents.drainTo(storedPublishes);
|
||||
|
||||
for (IMessagesStore.StoredMessage pubEvt : storedPublishes) {
|
||||
// put in flight zone
|
||||
LOG.debug("Adding message ot inflight zone. MqttClientId = {}, guid = {}, messageId = {}, topic = {}.",
|
||||
clientSession.clientID, pubEvt.getGuid(), pubEvt.getMessageID(), pubEvt.getTopic());
|
||||
LOG.debug(
|
||||
"Adding message ot inflight zone. MqttClientId = {}, guid = {}, messageId = {}, topic = {}.",
|
||||
clientSession.clientID,
|
||||
pubEvt.getGuid(),
|
||||
pubEvt.getMessageID(),
|
||||
pubEvt.getTopic());
|
||||
clientSession.inFlightAckWaiting(pubEvt.getGuid(), pubEvt.getMessageID());
|
||||
MqttPublishMessage publishMsg = notRetainedPublish(pubEvt);
|
||||
// set the PacketIdentifier only for QoS > 0
|
||||
@@ -62,22 +68,43 @@ class InternalRepublisher {
|
||||
}
|
||||
|
||||
private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage, Integer messageID) {
|
||||
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), false, messageID);
|
||||
return createPublishForQos(
|
||||
storedMessage.getTopic(),
|
||||
storedMessage.getQos(),
|
||||
storedMessage.getMessage(),
|
||||
false,
|
||||
messageID);
|
||||
}
|
||||
|
||||
private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage) {
|
||||
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), false, 0);
|
||||
return createPublishForQos(
|
||||
storedMessage.getTopic(),
|
||||
storedMessage.getQos(),
|
||||
storedMessage.getMessage(),
|
||||
false,
|
||||
0);
|
||||
}
|
||||
|
||||
private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage) {
|
||||
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), true, 0);
|
||||
return createPublishForQos(
|
||||
storedMessage.getTopic(),
|
||||
storedMessage.getQos(),
|
||||
storedMessage.getMessage(),
|
||||
true,
|
||||
0);
|
||||
}
|
||||
|
||||
private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage, Integer packetID) {
|
||||
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), true, packetID);
|
||||
return createPublishForQos(
|
||||
storedMessage.getTopic(),
|
||||
storedMessage.getQos(),
|
||||
storedMessage.getMessage(),
|
||||
true,
|
||||
packetID);
|
||||
}
|
||||
|
||||
public static MqttPublishMessage createPublishForQos(String topic, MqttQoS qos, ByteBuf message, boolean retained, int messageId) {
|
||||
public static MqttPublishMessage createPublishForQos(String topic, MqttQoS qos, ByteBuf message, boolean retained,
|
||||
int messageId) {
|
||||
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0);
|
||||
MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId);
|
||||
return new MqttPublishMessage(fixedHeader, varHeader, message);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.server.ConnectionDescriptorStore;
|
||||
@@ -10,9 +11,7 @@ import io.netty.buffer.ByteBuf;
|
||||
import io.netty.handler.codec.mqtt.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.moquette.spi.impl.ProtocolProcessor.lowerQosToTheSubscriptionDesired;
|
||||
|
||||
class MessagesPublisher {
|
||||
@@ -35,7 +34,8 @@ class MessagesPublisher {
|
||||
return notRetainedPublishWithMessageId(topic, qos, message, 0);
|
||||
}
|
||||
|
||||
private static MqttPublishMessage notRetainedPublishWithMessageId(String topic, MqttQoS qos, ByteBuf message, int messageId) {
|
||||
private static MqttPublishMessage notRetainedPublishWithMessageId(String topic, MqttQoS qos, ByteBuf message,
|
||||
int messageId) {
|
||||
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, false, 0);
|
||||
MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId);
|
||||
return new MqttPublishMessage(fixedHeader, varHeader, message);
|
||||
@@ -59,11 +59,16 @@ class MessagesPublisher {
|
||||
|
||||
boolean targetIsActive = this.connectionDescriptors.isConnected(sub.getClientId());
|
||||
|
||||
//we need to retain because duplicate only copy r/w indexes and don't retain() causing refCnt = 0
|
||||
// we need to retain because duplicate only copy r/w indexes and don't retain() causing
|
||||
// refCnt = 0
|
||||
ByteBuf message = origMessage.retainedDuplicate();
|
||||
if (targetIsActive) {
|
||||
LOG.debug("Sending PUBLISH message to active subscriber. MessageId={}, CId={}, topicFilter={}, qos={}",
|
||||
pubMsg.getMessageID(), sub.getClientId(), sub.getTopicFilter(), qos);
|
||||
LOG.debug(
|
||||
"Sending PUBLISH message to active subscriber. MessageId={}, CId={}, topicFilter={}, qos={}",
|
||||
pubMsg.getMessageID(),
|
||||
sub.getClientId(),
|
||||
sub.getTopicFilter(),
|
||||
qos);
|
||||
MqttPublishMessage publishMsg = notRetainedPublish(topic, qos, message);
|
||||
if (qos != MqttQoS.AT_MOST_ONCE) {
|
||||
// QoS 1 or 2
|
||||
@@ -75,8 +80,12 @@ class MessagesPublisher {
|
||||
this.messageSender.sendPublish(targetSession, publishMsg);
|
||||
} else {
|
||||
if (!targetSession.isCleanSession()) {
|
||||
LOG.debug("Storing pending PUBLISH inactive message. MessageId={}, CId={}, topicFilter={}, qos={}",
|
||||
pubMsg.getMessageID(), sub.getClientId(), sub.getTopicFilter(), qos);
|
||||
LOG.debug(
|
||||
"Storing pending PUBLISH inactive message. MessageId={}, CId={}, topicFilter={}, qos={}",
|
||||
pubMsg.getMessageID(),
|
||||
sub.getClientId(),
|
||||
sub.getTopicFilter(),
|
||||
qos);
|
||||
// store the message in targetSession queue to deliver
|
||||
targetSession.enqueue(pubMsg);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.server.ConnectionDescriptorStore;
|
||||
@@ -6,7 +7,6 @@ import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
import io.netty.handler.codec.mqtt.MqttQoS;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
|
||||
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
|
||||
|
||||
@@ -24,8 +24,12 @@ class PersistentQueueMessageSender {
|
||||
final int messageId = pubMessage.variableHeader().messageId();
|
||||
final String topicName = pubMessage.variableHeader().topicName();
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("Sending PUBLISH message. MessageId={}, CId={}, topic={}, qos={}, payload={}", messageId,
|
||||
clientId, topicName, DebugUtils.payload2Str(pubMessage.payload()));
|
||||
LOG.debug(
|
||||
"Sending PUBLISH message. MessageId={}, CId={}, topic={}, qos={}, payload={}",
|
||||
messageId,
|
||||
clientId,
|
||||
topicName,
|
||||
DebugUtils.payload2Str(pubMessage.payload()));
|
||||
} else {
|
||||
LOG.info("Sending PUBLISH message. MessageId={}, CId={}, topic={}", messageId, clientId, topicName);
|
||||
}
|
||||
@@ -35,13 +39,23 @@ class PersistentQueueMessageSender {
|
||||
MqttQoS qos = pubMessage.fixedHeader().qosLevel();
|
||||
if (!messageDelivered && qos != AT_MOST_ONCE && !clientsession.isCleanSession()) {
|
||||
LOG.warn(
|
||||
"The PUBLISH message could not be delivered. It will be stored. MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.",
|
||||
messageId, clientId, topicName, qos, false);
|
||||
"The PUBLISH message could not be delivered. It will be stored. "
|
||||
+ "MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.",
|
||||
messageId,
|
||||
clientId,
|
||||
topicName,
|
||||
qos,
|
||||
false);
|
||||
clientsession.enqueue(asStoredMessage(pubMessage));
|
||||
} else {
|
||||
LOG.warn(
|
||||
"The PUBLISH message could not be delivered. It will be discarded. MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.",
|
||||
messageId, clientId, topicName, qos, true);
|
||||
"The PUBLISH message could not be delivered. It will be discarded. "
|
||||
+ "MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.",
|
||||
messageId,
|
||||
clientId,
|
||||
topicName,
|
||||
qos,
|
||||
true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.interception.InterceptHandler;
|
||||
@@ -34,7 +35,6 @@ import io.netty.handler.codec.mqtt.*;
|
||||
import io.netty.handler.timeout.IdleStateHandler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -43,7 +43,6 @@ import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static io.moquette.spi.impl.InternalRepublisher.createPublishForQos;
|
||||
import static io.moquette.spi.impl.Utils.messageId;
|
||||
import static io.moquette.spi.impl.Utils.readBytesAndRewind;
|
||||
@@ -52,8 +51,8 @@ import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
|
||||
import static io.netty.handler.codec.mqtt.MqttQoS.*;
|
||||
|
||||
/**
|
||||
* Class responsible to handle the logic of MQTT protocol it's the director of
|
||||
* the protocol execution.
|
||||
* Class responsible to handle the logic of MQTT protocol it's the director of the protocol
|
||||
* execution.
|
||||
*
|
||||
* Used by the front facing class ProtocolProcessorBootstrapper.
|
||||
*
|
||||
@@ -62,6 +61,7 @@ import static io.netty.handler.codec.mqtt.MqttQoS.*;
|
||||
public class ProtocolProcessor {
|
||||
|
||||
static final class WillMessage {
|
||||
|
||||
private final String topic;
|
||||
private final ByteBuffer payload;
|
||||
private final boolean retained;
|
||||
@@ -89,7 +89,6 @@ public class ProtocolProcessor {
|
||||
public MqttQoS getQos() {
|
||||
return qos;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private enum SubscriptionState {
|
||||
@@ -97,6 +96,7 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private class RunningSubscription {
|
||||
|
||||
final String clientID;
|
||||
final long packetId;
|
||||
|
||||
@@ -107,13 +107,15 @@ public class ProtocolProcessor {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
RunningSubscription that = (RunningSubscription) o;
|
||||
|
||||
return packetId == that.packetId && (clientID != null ? clientID.equals(that.clientID) : that.clientID == null);
|
||||
|
||||
return packetId == that.packetId
|
||||
&& (clientID != null ? clientID.equals(that.clientID) : that.clientID == null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -148,49 +150,77 @@ public class ProtocolProcessor {
|
||||
// maps clientID to Will testament, if specified on CONNECT
|
||||
private ConcurrentMap<String, WillMessage> m_willStore = new ConcurrentHashMap<>();
|
||||
|
||||
ProtocolProcessor() {}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor) {
|
||||
init(subscriptions,storageService,sessionsStore,authenticator,allowAnonymous, false, authorizator,interceptor,null);
|
||||
ProtocolProcessor() {
|
||||
}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous,
|
||||
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor) {
|
||||
init(subscriptions,storageService,sessionsStore,authenticator,allowAnonymous, allowZeroByteClientId, authorizator,interceptor,null);
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
|
||||
BrokerInterceptor interceptor) {
|
||||
init(
|
||||
subscriptions,
|
||||
storageService,
|
||||
sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
false,
|
||||
authorizator,
|
||||
interceptor,
|
||||
null);
|
||||
}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous,
|
||||
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
|
||||
init(new ConnectionDescriptorStore(sessionsStore), subscriptions, storageService, sessionsStore, authenticator,
|
||||
allowAnonymous, allowZeroByteClientId, authorizator, interceptor, serverPort);
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
|
||||
IAuthorizator authorizator, BrokerInterceptor interceptor) {
|
||||
init(
|
||||
subscriptions,
|
||||
storageService,
|
||||
sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
allowZeroByteClientId,
|
||||
authorizator,
|
||||
interceptor,
|
||||
null);
|
||||
}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
|
||||
IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
|
||||
init(
|
||||
new ConnectionDescriptorStore(sessionsStore),
|
||||
subscriptions,
|
||||
storageService,
|
||||
sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
allowZeroByteClientId,
|
||||
authorizator,
|
||||
interceptor,
|
||||
serverPort);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param subscriptions the subscription store where are stored all the existing
|
||||
* clients subscriptions.
|
||||
* @param storageService the persistent store to use for save/load of messages
|
||||
* for QoS1 and QoS2 handling.
|
||||
* @param sessionsStore the clients sessions store, used to persist subscriptions.
|
||||
* @param authenticator the authenticator used in connect messages.
|
||||
* @param allowAnonymous true connection to clients without credentials.
|
||||
* @param allowZeroByteClientId true to allow clients connect without a clientid
|
||||
* @param authorizator used to apply ACL policies to publishes and subscriptions.
|
||||
* @param interceptor to notify events to an intercept handler
|
||||
* @param subscriptions
|
||||
* the subscription store where are stored all the existing clients subscriptions.
|
||||
* @param storageService
|
||||
* the persistent store to use for save/load of messages for QoS1 and QoS2 handling.
|
||||
* @param sessionsStore
|
||||
* the clients sessions store, used to persist subscriptions.
|
||||
* @param authenticator
|
||||
* the authenticator used in connect messages.
|
||||
* @param allowAnonymous
|
||||
* true connection to clients without credentials.
|
||||
* @param allowZeroByteClientId
|
||||
* true to allow clients connect without a clientid
|
||||
* @param authorizator
|
||||
* used to apply ACL policies to publishes and subscriptions.
|
||||
* @param interceptor
|
||||
* to notify events to an intercept handler
|
||||
*/
|
||||
void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous,
|
||||
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
|
||||
void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsStore subscriptions,
|
||||
IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator,
|
||||
boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator,
|
||||
BrokerInterceptor interceptor, String serverPort) {
|
||||
LOG.info("Initializing MQTT protocol processor...");
|
||||
this.connectionDescriptors = connectionDescriptors;
|
||||
this.subscriptionInCourse = new ConcurrentHashMap<>();
|
||||
@@ -209,15 +239,36 @@ public class ProtocolProcessor {
|
||||
|
||||
LOG.info("Initializing messages publisher...");
|
||||
final PersistentQueueMessageSender messageSender = new PersistentQueueMessageSender(this.connectionDescriptors);
|
||||
this.messagesPublisher = new MessagesPublisher(connectionDescriptors, sessionsStore, m_messagesStore, messageSender);
|
||||
this.messagesPublisher = new MessagesPublisher(
|
||||
connectionDescriptors,
|
||||
sessionsStore,
|
||||
m_messagesStore,
|
||||
messageSender);
|
||||
|
||||
LOG.info("Initializing QoS publish handlers...");
|
||||
this.qos0PublishHandler = new Qos0PublishHandler(m_authorizator, subscriptions, m_messagesStore,
|
||||
m_interceptor, this.messagesPublisher);
|
||||
this.qos1PublishHandler = new Qos1PublishHandler(m_authorizator, subscriptions, m_messagesStore,
|
||||
m_interceptor, this.connectionDescriptors, m_server_port, this.messagesPublisher);
|
||||
this.qos2PublishHandler = new Qos2PublishHandler(m_authorizator, subscriptions, m_messagesStore,
|
||||
m_interceptor, this.connectionDescriptors, m_sessionsStore, m_server_port, this.messagesPublisher);
|
||||
this.qos0PublishHandler = new Qos0PublishHandler(
|
||||
m_authorizator,
|
||||
subscriptions,
|
||||
m_messagesStore,
|
||||
m_interceptor,
|
||||
this.messagesPublisher);
|
||||
this.qos1PublishHandler = new Qos1PublishHandler(
|
||||
m_authorizator,
|
||||
subscriptions,
|
||||
m_messagesStore,
|
||||
m_interceptor,
|
||||
this.connectionDescriptors,
|
||||
m_server_port,
|
||||
this.messagesPublisher);
|
||||
this.qos2PublishHandler = new Qos2PublishHandler(
|
||||
m_authorizator,
|
||||
subscriptions,
|
||||
m_messagesStore,
|
||||
m_interceptor,
|
||||
this.connectionDescriptors,
|
||||
m_sessionsStore,
|
||||
m_server_port,
|
||||
this.messagesPublisher);
|
||||
|
||||
LOG.info("Initializing internal republisher...");
|
||||
this.internalRepublisher = new InternalRepublisher(messageSender);
|
||||
@@ -228,8 +279,8 @@ public class ProtocolProcessor {
|
||||
String clientId = payload.clientIdentifier();
|
||||
LOG.info("Processing CONNECT message. CId = {}, username = {}", clientId, payload.userName());
|
||||
|
||||
if (msg.variableHeader().version() != MqttVersion.MQTT_3_1.protocolLevel() &&
|
||||
msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) {
|
||||
if (msg.variableHeader().version() != MqttVersion.MQTT_3_1.protocolLevel()
|
||||
&& msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) {
|
||||
MqttConnAckMessage badProto = connAck(CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION);
|
||||
|
||||
LOG.error("The MQTT protocol version is not valid. CId = {}", clientId);
|
||||
@@ -250,8 +301,10 @@ public class ProtocolProcessor {
|
||||
|
||||
// Generating client id.
|
||||
clientId = UUID.randomUUID().toString().replace("-", "");
|
||||
LOG.info("The client has connected with a server generated identifier. CId = {}, username = {}",
|
||||
clientId, payload.userName());
|
||||
LOG.info(
|
||||
"The client has connected with a server generated identifier. CId = {}, username = {}",
|
||||
clientId,
|
||||
payload.userName());
|
||||
}
|
||||
|
||||
if (!login(channel, msg, clientId)) {
|
||||
@@ -259,11 +312,13 @@ public class ProtocolProcessor {
|
||||
return;
|
||||
}
|
||||
|
||||
ConnectionDescriptor descriptor = new ConnectionDescriptor(clientId, channel, msg.variableHeader().isCleanSession());
|
||||
ConnectionDescriptor descriptor = new ConnectionDescriptor(
|
||||
clientId,
|
||||
channel,
|
||||
msg.variableHeader().isCleanSession());
|
||||
ConnectionDescriptor existing = this.connectionDescriptors.addConnection(descriptor);
|
||||
if (existing != null) {
|
||||
LOG.info("The client ID is being used in an existing connection. It will be closed. CId = {}",
|
||||
clientId);
|
||||
LOG.info("The client ID is being used in an existing connection. It will be closed. CId = {}", clientId);
|
||||
existing.abort();
|
||||
return;
|
||||
}
|
||||
@@ -289,7 +344,8 @@ public class ProtocolProcessor {
|
||||
channel.close();
|
||||
return;
|
||||
}
|
||||
final boolean success = descriptor.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED);
|
||||
if (!success) {
|
||||
channel.close();
|
||||
}
|
||||
@@ -306,7 +362,12 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private MqttConnAckMessage connAck(MqttConnectReturnCode returnCode, boolean sessionPresent) {
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0);
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
|
||||
MqttMessageType.CONNACK,
|
||||
false,
|
||||
MqttQoS.AT_MOST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(returnCode, sessionPresent);
|
||||
return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader);
|
||||
}
|
||||
@@ -318,20 +379,25 @@ public class ProtocolProcessor {
|
||||
if (msg.variableHeader().hasPassword()) {
|
||||
pwd = msg.payload().password().getBytes();
|
||||
} else if (!this.allowAnonymous) {
|
||||
LOG.error("The client didn't supply any password and MQTT anonymous mode is disabled. CId = {}.",
|
||||
LOG.error(
|
||||
"The client didn't supply any password and MQTT anonymous mode is disabled. CId = {}.",
|
||||
clientId);
|
||||
failedCredentials(channel);
|
||||
return false;
|
||||
}
|
||||
if (!m_authenticator.checkValid(clientId, msg.payload().userName(), pwd)) {
|
||||
LOG.error("The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.",
|
||||
clientId, msg.payload().userName(), pwd);
|
||||
LOG.error(
|
||||
"The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.",
|
||||
clientId,
|
||||
msg.payload().userName(),
|
||||
pwd);
|
||||
failedCredentials(channel);
|
||||
return false;
|
||||
}
|
||||
NettyUtils.userName(channel, msg.payload().userName());
|
||||
} else if (!this.allowAnonymous) {
|
||||
LOG.error("The client didn't supply any credentials and MQTT anonymous mode is disabled. CId = {}.",
|
||||
LOG.error(
|
||||
"The client didn't supply any credentials and MQTT anonymous mode is disabled. CId = {}.",
|
||||
clientId);
|
||||
failedCredentials(channel);
|
||||
return false;
|
||||
@@ -376,20 +442,33 @@ public class ProtocolProcessor {
|
||||
int idleTime = Math.round(keepAlive * 1.5f);
|
||||
setIdleTime(channel.pipeline(), idleTime);
|
||||
|
||||
LOG.info("The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.",
|
||||
clientId, keepAlive, msg.variableHeader().isCleanSession(), idleTime);
|
||||
LOG.info(
|
||||
"The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.",
|
||||
clientId,
|
||||
keepAlive,
|
||||
msg.variableHeader().isCleanSession(),
|
||||
idleTime);
|
||||
}
|
||||
|
||||
private void storeWillMessage(MqttConnectMessage msg, final String clientId) {
|
||||
// Handle will flag
|
||||
if (msg.variableHeader().isWillFlag()) {
|
||||
MqttQoS willQos = MqttQoS.valueOf(msg.variableHeader().willQos());
|
||||
LOG.info("Configuring MQTT last will and testament. CId = {}, willQos = {}, willTopic = {}, willRetain = {}.",
|
||||
clientId, willQos, msg.payload().willTopic(), msg.variableHeader().isWillRetain());
|
||||
LOG.info(
|
||||
"Configuring MQTT last will and testament. "
|
||||
+ "CId = {}, willQos = {}, willTopic = {}, willRetain = {}.",
|
||||
clientId,
|
||||
willQos,
|
||||
msg.payload().willTopic(),
|
||||
msg.variableHeader().isWillRetain());
|
||||
byte[] willPayload = msg.payload().willMessage().getBytes();
|
||||
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(willPayload.length).put(willPayload).flip();
|
||||
// save the will testament in the clientID store
|
||||
WillMessage will = new WillMessage(msg.payload().willTopic(), bb, msg.variableHeader().isWillRetain(), willQos);
|
||||
WillMessage will = new WillMessage(
|
||||
msg.payload().willTopic(),
|
||||
bb,
|
||||
msg.variableHeader().isWillRetain(),
|
||||
willQos);
|
||||
m_willStore.put(clientId, will);
|
||||
LOG.info("MQTT last will and testament has been configured. CId = {}.", clientId);
|
||||
}
|
||||
@@ -415,7 +494,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean republish(ConnectionDescriptor descriptor, MqttConnectMessage msg, ClientSession clientSession) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.SESSION_CREATED, ConnectionState.MESSAGES_REPUBLISHED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.SESSION_CREATED, ConnectionState.MESSAGES_REPUBLISHED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -443,7 +523,7 @@ public class ProtocolProcessor {
|
||||
|
||||
/**
|
||||
* Republish QoS1 and QoS2 messages stored into the session for the clientID.
|
||||
* */
|
||||
*/
|
||||
private void republishStoredInSession(ClientSession clientSession) {
|
||||
LOG.info("Republishing stored publish events. CId = {}.", clientSession.clientID);
|
||||
BlockingQueue<StoredMessage> publishedEvents = clientSession.queue();
|
||||
@@ -474,15 +554,20 @@ public class ProtocolProcessor {
|
||||
ByteBuf payload = msg.payload();
|
||||
byte[] payloadContent = readBytesAndRewind(payload);
|
||||
|
||||
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(payloadContent,
|
||||
msg.fixedHeader().qosLevel(), msg.variableHeader().topicName());
|
||||
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(
|
||||
payloadContent,
|
||||
msg.fixedHeader().qosLevel(),
|
||||
msg.variableHeader().topicName());
|
||||
stored.setRetained(msg.fixedHeader().isRetain());
|
||||
stored.setMessageID(msg.variableHeader().messageId());
|
||||
return stored;
|
||||
}
|
||||
|
||||
private static IMessagesStore.StoredMessage asStoredMessage(WillMessage will) {
|
||||
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(will.getPayload().array(), will.getQos(), will.getTopic());
|
||||
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(
|
||||
will.getPayload().array(),
|
||||
will.getQos(),
|
||||
will.getTopic());
|
||||
pub.setRetained(will.isRetained());
|
||||
return pub;
|
||||
}
|
||||
@@ -490,8 +575,12 @@ public class ProtocolProcessor {
|
||||
public void processPublish(Channel channel, MqttPublishMessage msg) {
|
||||
final MqttQoS qos = msg.fixedHeader().qosLevel();
|
||||
final String clientId = NettyUtils.clientID(channel);
|
||||
LOG.info("Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.",
|
||||
clientId, msg.variableHeader().topicName(), msg.variableHeader().messageId(), qos);
|
||||
LOG.info(
|
||||
"Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.",
|
||||
clientId,
|
||||
msg.variableHeader().topicName(),
|
||||
msg.variableHeader().messageId(),
|
||||
qos);
|
||||
switch (qos) {
|
||||
case AT_MOST_ONCE:
|
||||
this.qos0PublishHandler.receivedPublishQos0(channel, msg);
|
||||
@@ -508,16 +597,17 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Intended usage is only for embedded versions of the broker, where the hosting application want to use the
|
||||
* broker to send a publish message.
|
||||
* Inspired by {@link #processPublish} but with some changes to avoid security check, and the handshake phases
|
||||
* for Qos1 and Qos2.
|
||||
* It also doesn't notifyTopicPublished because using internally the owner should already know where
|
||||
* it's publishing.
|
||||
* Intended usage is only for embedded versions of the broker, where the hosting application
|
||||
* want to use the broker to send a publish message. Inspired by {@link #processPublish} but
|
||||
* with some changes to avoid security check, and the handshake phases for Qos1 and Qos2. It
|
||||
* also doesn't notifyTopicPublished because using internally the owner should already know
|
||||
* where it's publishing.
|
||||
*
|
||||
* @param msg the message to publish.
|
||||
* @param clientId the clientID
|
||||
* */
|
||||
* @param msg
|
||||
* the message to publish.
|
||||
* @param clientId
|
||||
* the clientID
|
||||
*/
|
||||
public void internalPublish(MqttPublishMessage msg, final String clientId) {
|
||||
final MqttQoS qos = msg.fixedHeader().qosLevel();
|
||||
final String topic = msg.variableHeader().topicName();
|
||||
@@ -581,11 +671,14 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish
|
||||
* to all interested subscribers.
|
||||
* @param channel the channel of the incoming message.
|
||||
* @param msg the decoded pubrel message.
|
||||
* */
|
||||
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored
|
||||
* message and publish to all interested subscribers.
|
||||
*
|
||||
* @param channel
|
||||
* the channel of the incoming message.
|
||||
* @param msg
|
||||
* the decoded pubrel message.
|
||||
*/
|
||||
public void processPubRel(Channel channel, MqttMessage msg) {
|
||||
this.qos2PublishHandler.processPubRel(channel, msg);
|
||||
}
|
||||
@@ -629,8 +722,7 @@ public class ProtocolProcessor {
|
||||
|
||||
if (existingDescriptor.doesNotUseChannel(channel)) {
|
||||
// another client saved it's descriptor, exit
|
||||
LOG.warn("Another client is using the connection descriptor. Closing connection. CId = {}.",
|
||||
clientID);
|
||||
LOG.warn("Another client is using the connection descriptor. Closing connection. CId = {}.", clientID);
|
||||
existingDescriptor.abort();
|
||||
return;
|
||||
}
|
||||
@@ -669,7 +761,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean removeSubscriptions(ConnectionDescriptor descriptor, String clientID) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.ESTABLISHED, ConnectionState.SUBSCRIPTIONS_REMOVED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.ESTABLISHED, ConnectionState.SUBSCRIPTIONS_REMOVED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -683,7 +776,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean dropStoredMessages(ConnectionDescriptor descriptor, String clientID) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.SUBSCRIPTIONS_REMOVED, ConnectionState.MESSAGES_DROPPED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.SUBSCRIPTIONS_REMOVED, ConnectionState.MESSAGES_DROPPED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -697,7 +791,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean cleanWillMessageAndNotifyInterceptor(ConnectionDescriptor descriptor, String clientID) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.MESSAGES_DROPPED, ConnectionState.INTERCEPTORS_NOTIFIED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.MESSAGES_DROPPED, ConnectionState.INTERCEPTORS_NOTIFIED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -726,10 +821,13 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the clientID from topic subscription, if not previously subscribed,
|
||||
* doesn't reply any error.
|
||||
* @param channel the channel of the incoming message.
|
||||
* @param msg the decoded unsubscribe message.
|
||||
* Remove the clientID from topic subscription, if not previously subscribed, doesn't reply any
|
||||
* error.
|
||||
*
|
||||
* @param channel
|
||||
* the channel of the incoming message.
|
||||
* @param msg
|
||||
* the decoded unsubscribe message.
|
||||
*/
|
||||
public void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg) {
|
||||
List<String> topics = msg.payload().topics();
|
||||
@@ -743,8 +841,11 @@ public class ProtocolProcessor {
|
||||
if (!validTopic) {
|
||||
// close the connection, not valid topicFilter is a protocol violation
|
||||
channel.close();
|
||||
LOG.error("The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.",
|
||||
clientID, topics, topic);
|
||||
LOG.error(
|
||||
"The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.",
|
||||
clientID,
|
||||
topics,
|
||||
topic);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -770,18 +871,25 @@ public class ProtocolProcessor {
|
||||
LOG.info("Processing SUBSCRIBE message. CId = {}, messageId = {}.", clientID, messageID);
|
||||
|
||||
RunningSubscription executionKey = new RunningSubscription(clientID, messageID);
|
||||
SubscriptionState currentStatus = this.subscriptionInCourse.putIfAbsent(executionKey, SubscriptionState.VERIFIED);
|
||||
SubscriptionState currentStatus = this.subscriptionInCourse
|
||||
.putIfAbsent(executionKey, SubscriptionState.VERIFIED);
|
||||
if (currentStatus != null) {
|
||||
LOG.warn("The client sent another SUBSCRIBE message while this one was being processed. " +
|
||||
"CId = {}, messageId = {}.", clientID, messageID);
|
||||
LOG.warn(
|
||||
"The client sent another SUBSCRIBE message while this one was being processed. "
|
||||
+ "CId = {}, messageId = {}.",
|
||||
clientID,
|
||||
messageID);
|
||||
return;
|
||||
}
|
||||
String username = NettyUtils.userName(channel);
|
||||
List<MqttTopicSubscription> ackTopics = doVerify(clientID, username, msg);
|
||||
MqttSubAckMessage ackMessage = doAckMessageFromValidateFilters(ackTopics, messageID);
|
||||
if (!this.subscriptionInCourse.replace(executionKey, SubscriptionState.VERIFIED, SubscriptionState.STORED)) {
|
||||
LOG.warn("The client sent another SUBSCRIBE message while the topic filters were being verified. " +
|
||||
"CId = {}, messageId = {}.", clientID, messageID);
|
||||
LOG.warn(
|
||||
"The client sent another SUBSCRIBE message while the topic filters were being verified. "
|
||||
+ "CId = {}, messageId = {}.",
|
||||
clientID,
|
||||
messageID);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -826,11 +934,14 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param clientID the clientID
|
||||
* @param username the username
|
||||
* @param msg the subscribe message to verify
|
||||
* @param clientID
|
||||
* the clientID
|
||||
* @param username
|
||||
* the username
|
||||
* @param msg
|
||||
* the subscribe message to verify
|
||||
* @return the list of verified topics for the given subscribe message.
|
||||
* */
|
||||
*/
|
||||
private List<MqttTopicSubscription> doVerify(String clientID, String username, MqttSubscribeMessage msg) {
|
||||
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
|
||||
List<MqttTopicSubscription> ackTopics = new ArrayList<>();
|
||||
@@ -839,18 +950,32 @@ public class ProtocolProcessor {
|
||||
for (MqttTopicSubscription req : msg.payload().topicSubscriptions()) {
|
||||
if (!m_authorizator.canRead(req.topicName(), username, clientSession.clientID)) {
|
||||
// send SUBACK with 0x80, the user hasn't credentials to read the topic
|
||||
LOG.error("The client does not have read permissions on the topic. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID, username, messageId, req.topicName());
|
||||
LOG.error(
|
||||
"The client does not have read permissions on the topic. "
|
||||
+ "CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID,
|
||||
username,
|
||||
messageId,
|
||||
req.topicName());
|
||||
ackTopics.add(new MqttTopicSubscription(req.topicName(), FAILURE));
|
||||
} else {
|
||||
MqttQoS qos;
|
||||
if (SubscriptionsStore.validate(req.topicName())) {
|
||||
LOG.info("The client will be subscribed to the topic. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID, username, messageId, req.topicName());
|
||||
LOG.info(
|
||||
"The client will be subscribed to the topic. "
|
||||
+ "CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID,
|
||||
username,
|
||||
messageId,
|
||||
req.topicName());
|
||||
qos = req.qualityOfService();
|
||||
} else {
|
||||
LOG.error("The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID, username, messageId, req.topicName());
|
||||
LOG.error(
|
||||
"The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID,
|
||||
username,
|
||||
messageId,
|
||||
req.topicName());
|
||||
qos = FAILURE;
|
||||
}
|
||||
ackTopics.add(new MqttTopicSubscription(req.topicName(), qos));
|
||||
@@ -861,7 +986,7 @@ public class ProtocolProcessor {
|
||||
|
||||
/**
|
||||
* Create the SUBACK response from a list of topicFilters
|
||||
* */
|
||||
*/
|
||||
private MqttSubAckMessage doAckMessageFromValidateFilters(List<MqttTopicSubscription> topicFilters, int messageId) {
|
||||
List<Integer> grantedQoSLevels = new ArrayList<>();
|
||||
for (MqttTopicSubscription req : topicFilters) {
|
||||
@@ -874,12 +999,15 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private void publishRetainedMessagesInSession(final Subscription newSubscription, String username) {
|
||||
LOG.info("Retrieving retained messages. CId = {}, topics = {}.", newSubscription.getClientId(),
|
||||
LOG.info(
|
||||
"Retrieving retained messages. CId = {}, topics = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter());
|
||||
|
||||
// scans retained messages to be published to the new subscription
|
||||
// TODO this is ugly, it does a linear scan on potential big dataset
|
||||
Collection<IMessagesStore.StoredMessage> messages = m_messagesStore.searchMatching(new IMatchingCondition() {
|
||||
|
||||
@Override
|
||||
public boolean match(String key) {
|
||||
return SubscriptionsStore.matchTopics(key, newSubscription.getTopicFilter());
|
||||
@@ -887,8 +1015,11 @@ public class ProtocolProcessor {
|
||||
});
|
||||
|
||||
if (!messages.isEmpty()) {
|
||||
LOG.info("Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.",
|
||||
newSubscription.getClientId(), newSubscription.getTopicFilter(), messages.size());
|
||||
LOG.info(
|
||||
"Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter(),
|
||||
messages.size());
|
||||
}
|
||||
ClientSession targetSession = m_sessionsStore.sessionForClient(newSubscription.getClientId());
|
||||
this.internalRepublisher.publishRetained(targetSession, messages);
|
||||
@@ -908,7 +1039,12 @@ public class ProtocolProcessor {
|
||||
} else {
|
||||
// recreate a publish from stored publish in queue
|
||||
boolean retained = m_messagesStore.getMessageByGuid(msg.getGuid()) != null;
|
||||
MqttPublishMessage pubMsg = createPublishForQos(msg.getTopic(), msg.getQos(), msg.getMessage(), retained, 0);
|
||||
MqttPublishMessage pubMsg = createPublishForQos(
|
||||
msg.getTopic(),
|
||||
msg.getQos(),
|
||||
msg.getMessage(),
|
||||
retained,
|
||||
0);
|
||||
channel.write(pubMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -35,7 +36,6 @@ import io.moquette.spi.security.IAuthenticator;
|
||||
import io.moquette.spi.security.IAuthorizator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.ParseException;
|
||||
@@ -68,17 +68,23 @@ public class ProtocolProcessorBootstrapper {
|
||||
|
||||
/**
|
||||
* Initialize the processing part of the broker.
|
||||
* @param props the properties carrier where some props like port end host could be loaded.
|
||||
* For the full list check of configurable properties check moquette.conf file.
|
||||
* @param embeddedObservers a list of callbacks to be notified of certain events inside the broker.
|
||||
* Could be empty list of null.
|
||||
* @param authenticator an implementation of the authenticator to be used, if null load that specified in config
|
||||
* and fallback on the default one (permit all).
|
||||
* @param authorizator an implementation of the authorizator to be used, if null load that specified in config
|
||||
* and fallback on the default one (permit all).
|
||||
* @param server the serber to init.
|
||||
*
|
||||
* @param props
|
||||
* the properties carrier where some props like port end host could be loaded. For
|
||||
* the full list check of configurable properties check moquette.conf file.
|
||||
* @param embeddedObservers
|
||||
* a list of callbacks to be notified of certain events inside the broker. Could be
|
||||
* empty list of null.
|
||||
* @param authenticator
|
||||
* an implementation of the authenticator to be used, if null load that specified in
|
||||
* config and fallback on the default one (permit all).
|
||||
* @param authorizator
|
||||
* an implementation of the authorizator to be used, if null load that specified in
|
||||
* config and fallback on the default one (permit all).
|
||||
* @param server
|
||||
* the serber to init.
|
||||
* @return the processor created for the broker.
|
||||
* */
|
||||
*/
|
||||
public ProtocolProcessor init(IConfig props, List<? extends InterceptHandler> embeddedObservers,
|
||||
IAuthenticator authenticator, IAuthorizator authorizator, Server server) {
|
||||
subscriptions = new SubscriptionsStore();
|
||||
@@ -136,8 +142,11 @@ public class ProtocolProcessorBootstrapper {
|
||||
LOG.info("Parsing ACL file. Path = {}.", aclFilePath);
|
||||
authorizator = ACLFileParser.parse(resourceLoader.loadResource(aclFilePath));
|
||||
} catch (ParseException pex) {
|
||||
LOG.error("Unable to parse ACL file. Path = {}, cause = {}, errorMessage = {}.", aclFilePath,
|
||||
pex.getCause(), pex.getMessage());
|
||||
LOG.error(
|
||||
"Unable to parse ACL file. Path = {}, cause = {}, errorMessage = {}.",
|
||||
aclFilePath,
|
||||
pex.getCause(),
|
||||
pex.getMessage());
|
||||
}
|
||||
} else {
|
||||
authorizator = new PermitAllAuthorizator();
|
||||
@@ -149,9 +158,21 @@ public class ProtocolProcessorBootstrapper {
|
||||
connectionDescriptors = new ConnectionDescriptorStore(m_sessionsStore);
|
||||
|
||||
LOG.info("Initializing MQTT protocol processor...");
|
||||
boolean allowAnonymous = Boolean.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, "true"));
|
||||
boolean allowZeroByteClientId = Boolean.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME, "false"));
|
||||
m_processor.init(connectionDescriptors, subscriptions, messagesStore, m_sessionsStore, authenticator, allowAnonymous, allowZeroByteClientId, authorizator, m_interceptor, props.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
|
||||
boolean allowAnonymous = Boolean
|
||||
.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, "true"));
|
||||
boolean allowZeroByteClientId = Boolean
|
||||
.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME, "false"));
|
||||
m_processor.init(
|
||||
connectionDescriptors,
|
||||
subscriptions,
|
||||
messagesStore,
|
||||
m_sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
allowZeroByteClientId,
|
||||
authorizator,
|
||||
m_interceptor,
|
||||
props.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
|
||||
return m_processor;
|
||||
}
|
||||
|
||||
@@ -165,38 +186,58 @@ public class ProtocolProcessorBootstrapper {
|
||||
// check if method getInstance exists
|
||||
Method method = clazz.getMethod("getInstance", new Class[]{});
|
||||
try {
|
||||
LOG.info("Invoking getInstance() method. ClassName = {}, interfaceName = {}.", className,
|
||||
LOG.info(
|
||||
"Invoking getInstance() method. ClassName = {}, interfaceName = {}.",
|
||||
className,
|
||||
iface.getName());
|
||||
instance = (T) method.invoke(null, new Object[]{});
|
||||
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) {
|
||||
LOG.error(
|
||||
"Unable to invoke getInstance() method. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
className, iface.getName(), ex.getCause(), ex.getMessage());
|
||||
"Unable to invoke getInstance() method. "
|
||||
+ "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
className,
|
||||
iface.getName(),
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
} catch (NoSuchMethodException nsmex) {
|
||||
try {
|
||||
// check if constructor with constructor arg class parameter
|
||||
// exists
|
||||
LOG.info("Invoking constructor with {} argument. ClassName = {}, interfaceName = {}.",
|
||||
constructorArgClass.getName(), className, iface.getName());
|
||||
LOG.info(
|
||||
"Invoking constructor with {} argument. ClassName = {}, interfaceName = {}.",
|
||||
constructorArgClass.getName(),
|
||||
className,
|
||||
iface.getName());
|
||||
instance = this.getClass().getClassLoader().loadClass(className).asSubclass(iface)
|
||||
.getConstructor(constructorArgClass).newInstance(props);
|
||||
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
|
||||
LOG.warn(
|
||||
"Unable to invoke constructor with {} argument. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
constructorArgClass.getName(), className, iface.getName(), ex.getCause(), ex.getMessage());
|
||||
"Unable to invoke constructor with {} argument. "
|
||||
+ "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
constructorArgClass.getName(),
|
||||
className,
|
||||
iface.getName(),
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
return null;
|
||||
} catch (NoSuchMethodException | InvocationTargetException e) {
|
||||
try {
|
||||
LOG.info("Invoking default constructor. ClassName = {}, interfaceName = {}.", className,
|
||||
LOG.info(
|
||||
"Invoking default constructor. ClassName = {}, interfaceName = {}.",
|
||||
className,
|
||||
iface.getName());
|
||||
// fallback to default constructor
|
||||
instance = this.getClass().getClassLoader().loadClass(className).asSubclass(iface).newInstance();
|
||||
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
|
||||
LOG.error(
|
||||
"Unable to invoke default constructor. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
className, iface.getName(), ex.getCause(), ex.getMessage());
|
||||
"Unable to invoke default constructor. "
|
||||
+ "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
className,
|
||||
iface.getName(),
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -205,8 +246,12 @@ public class ProtocolProcessorBootstrapper {
|
||||
return null;
|
||||
} catch (SecurityException ex) {
|
||||
LOG.error(
|
||||
"Unable to load class due to a security violation. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
className, iface.getName(), ex.getCause(), ex.getMessage());
|
||||
"Unable to load class due to a security violation. "
|
||||
+ "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
|
||||
className,
|
||||
iface.getName(),
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.server.netty.NettyUtils;
|
||||
@@ -9,9 +10,7 @@ import io.netty.channel.Channel;
|
||||
import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
|
||||
|
||||
class Qos0PublishHandler extends QosPublishHandler {
|
||||
@@ -24,8 +23,7 @@ class Qos0PublishHandler extends QosPublishHandler {
|
||||
private final MessagesPublisher publisher;
|
||||
|
||||
public Qos0PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions,
|
||||
IMessagesStore messagesStore, BrokerInterceptor interceptor,
|
||||
MessagesPublisher messagesPublisher) {
|
||||
IMessagesStore messagesStore, BrokerInterceptor interceptor, MessagesPublisher messagesPublisher) {
|
||||
super(authorizator);
|
||||
this.subscriptions = subscriptions;
|
||||
this.m_messagesStore = messagesStore;
|
||||
@@ -48,12 +46,20 @@ class Qos0PublishHandler extends QosPublishHandler {
|
||||
final int messageID = msg.variableHeader().messageId();
|
||||
|
||||
if (LOG.isTraceEnabled()) {
|
||||
LOG.trace("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
|
||||
clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
||||
LOG.trace(
|
||||
"Sending publish message to subscribers. "
|
||||
+ "MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID,
|
||||
DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
||||
subscriptions.dumpTree());
|
||||
} else {
|
||||
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", clientID,
|
||||
topic, messageID);
|
||||
LOG.info(
|
||||
"Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID);
|
||||
}
|
||||
|
||||
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.server.ConnectionDescriptorStore;
|
||||
@@ -14,14 +15,13 @@ import io.netty.handler.codec.mqtt.MqttPubAckMessage;
|
||||
import io.netty.handler.codec.mqtt.MqttPublishMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
|
||||
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
|
||||
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
|
||||
|
||||
class Qos1PublishHandler extends QosPublishHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Qos1PublishHandler.class);
|
||||
|
||||
private final SubscriptionsStore subscriptions;
|
||||
@@ -32,8 +32,7 @@ class Qos1PublishHandler extends QosPublishHandler {
|
||||
|
||||
public Qos1PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions,
|
||||
IMessagesStore messagesStore, BrokerInterceptor interceptor,
|
||||
ConnectionDescriptorStore connectionDescriptors,
|
||||
String brokerPort, MessagesPublisher messagesPublisher) {
|
||||
ConnectionDescriptorStore connectionDescriptors, String brokerPort, MessagesPublisher messagesPublisher) {
|
||||
super(authorizator);
|
||||
this.subscriptions = subscriptions;
|
||||
this.m_messagesStore = messagesStore;
|
||||
@@ -57,12 +56,20 @@ class Qos1PublishHandler extends QosPublishHandler {
|
||||
toStoreMsg.setClientID(clientID);
|
||||
|
||||
if (LOG.isTraceEnabled()) {
|
||||
LOG.trace("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
|
||||
clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
||||
LOG.trace(
|
||||
"Sending publish message to subscribers. "
|
||||
+ "MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID,
|
||||
DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
||||
subscriptions.dumpTree());
|
||||
} else {
|
||||
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", clientID,
|
||||
topic, messageID);
|
||||
LOG.info(
|
||||
"Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID);
|
||||
}
|
||||
|
||||
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
||||
@@ -94,11 +101,17 @@ class Qos1PublishHandler extends QosPublishHandler {
|
||||
|
||||
try {
|
||||
if (connectionDescriptors == null) {
|
||||
throw new RuntimeException("Internal bad error, found connectionDescriptors to null while it should be initialized, somewhere it's overwritten!!");
|
||||
throw new RuntimeException(
|
||||
"Internal bad error, found connectionDescriptors to null while it should be initialized, "
|
||||
+ "somewhere it's overwritten!!");
|
||||
}
|
||||
LOG.debug("clientIDs are {}", connectionDescriptors);
|
||||
if (!connectionDescriptors.isConnected(clientId)) {
|
||||
throw new RuntimeException(String.format("Can't find a ConnectionDescriptor for client %s in cache %s", clientId, connectionDescriptors));
|
||||
throw new RuntimeException(
|
||||
String.format(
|
||||
"Can't find a ConnectionDescriptor for client %s in cache %s",
|
||||
clientId,
|
||||
connectionDescriptors));
|
||||
}
|
||||
connectionDescriptors.sendMessage(pubAckMessage, messageID, clientId);
|
||||
} catch (Throwable t) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.server.ConnectionDescriptorStore;
|
||||
@@ -13,9 +14,7 @@ import io.netty.channel.Channel;
|
||||
import io.netty.handler.codec.mqtt.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
|
||||
import static io.moquette.spi.impl.Utils.messageId;
|
||||
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
|
||||
@@ -34,8 +33,8 @@ class Qos2PublishHandler extends QosPublishHandler {
|
||||
|
||||
public Qos2PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions,
|
||||
IMessagesStore messagesStore, BrokerInterceptor interceptor,
|
||||
ConnectionDescriptorStore connectionDescriptors,
|
||||
ISessionsStore sessionsStore, String brokerPort, MessagesPublisher messagesPublisher) {
|
||||
ConnectionDescriptorStore connectionDescriptors, ISessionsStore sessionsStore, String brokerPort,
|
||||
MessagesPublisher messagesPublisher) {
|
||||
super(authorizator);
|
||||
this.subscriptions = subscriptions;
|
||||
this.m_messagesStore = messagesStore;
|
||||
@@ -58,13 +57,20 @@ class Qos2PublishHandler extends QosPublishHandler {
|
||||
toStoreMsg.setClientID(clientID);
|
||||
|
||||
if (LOG.isTraceEnabled()) {
|
||||
LOG.trace("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, " +
|
||||
"payload = {}, subscriptionTree = {}.",
|
||||
clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
||||
LOG.trace(
|
||||
"Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, "
|
||||
+ "payload = {}, subscriptionTree = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID,
|
||||
DebugUtils.payload2Str(toStoreMsg.getMessage()),
|
||||
subscriptions.dumpTree());
|
||||
} else {
|
||||
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
|
||||
clientID, topic, messageID);
|
||||
LOG.info(
|
||||
"Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID);
|
||||
}
|
||||
|
||||
// QoS2
|
||||
@@ -87,9 +93,9 @@ class Qos2PublishHandler extends QosPublishHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish
|
||||
* to all interested subscribers.
|
||||
* */
|
||||
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored
|
||||
* message and publish to all interested subscribers.
|
||||
*/
|
||||
void processPubRel(Channel channel, MqttMessage msg) {
|
||||
String clientID = NettyUtils.clientID(channel);
|
||||
int messageID = messageId(msg);
|
||||
@@ -100,12 +106,20 @@ class Qos2PublishHandler extends QosPublishHandler {
|
||||
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
|
||||
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
|
||||
clientID, topic, messageID, DebugUtils.payload2Str(evt.getMessage()),
|
||||
LOG.debug(
|
||||
"Sending publish message to subscribers. "
|
||||
+ "MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID,
|
||||
DebugUtils.payload2Str(evt.getMessage()),
|
||||
subscriptions.dumpTree());
|
||||
} else {
|
||||
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", clientID,
|
||||
topic, messageID);
|
||||
LOG.info(
|
||||
"Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
|
||||
clientID,
|
||||
topic,
|
||||
messageID);
|
||||
}
|
||||
this.publisher.publish2Subscribers(evt, topicMatchingSubscriptions);
|
||||
|
||||
@@ -120,7 +134,6 @@ class Qos2PublishHandler extends QosPublishHandler {
|
||||
sendPubComp(clientID, messageID);
|
||||
}
|
||||
|
||||
|
||||
private void sendPubRec(String clientID, int messageID) {
|
||||
LOG.debug("Sending PUBREC message. MqttClientId = {}, messageId = {}.", clientID, messageID);
|
||||
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, AT_MOST_ONCE, false, 0);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.moquette.server.netty.NettyUtils;
|
||||
import io.moquette.spi.security.IAuthorizator;
|
||||
import io.netty.channel.Channel;
|
||||
@@ -21,7 +21,9 @@ abstract class QosPublishHandler {
|
||||
String clientID = NettyUtils.clientID(channel);
|
||||
String username = NettyUtils.userName(channel);
|
||||
if (!m_authorizator.canWrite(topic, username, clientID)) {
|
||||
LOG.error("The MQTT client is not authorized to publish on topic. MqttClientId = {}, topic = {}.", clientID,
|
||||
LOG.error(
|
||||
"The MQTT client is not authorized to publish on topic. MqttClientId = {}, topic = {}.",
|
||||
clientID,
|
||||
topic);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.handler.codec.mqtt.MqttMessage;
|
||||
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,29 +13,32 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.text.ParseException;
|
||||
|
||||
/**
|
||||
* Parses the acl configuration file.
|
||||
* If a line starts with # it's comment.
|
||||
* Blank lines are skipped. The format is "topic [read|write|readwrite] {topic name}"
|
||||
* Parses the acl configuration file. If a line starts with # it's comment. Blank lines are skipped.
|
||||
* The format is "topic [read|write|readwrite] {topic name}"
|
||||
*
|
||||
* @author andrea
|
||||
* */
|
||||
*/
|
||||
public class ACLFileParser {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ACLFileParser.class);
|
||||
|
||||
/**
|
||||
* Parse the configuration from file.
|
||||
* @param file to parse
|
||||
*
|
||||
* @param file
|
||||
* to parse
|
||||
* @return the collector of authorizations form reader passed into.
|
||||
* @throws ParseException if the format is not compliant.
|
||||
* @throws ParseException
|
||||
* if the format is not compliant.
|
||||
*/
|
||||
public static AuthorizationsCollector parse(File file) throws ParseException {
|
||||
if (file == null) {
|
||||
@@ -43,23 +46,33 @@ public class ACLFileParser {
|
||||
return AuthorizationsCollector.emptyImmutableCollector();
|
||||
}
|
||||
if (!file.exists()) {
|
||||
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()));
|
||||
LOG.warn(
|
||||
String.format(
|
||||
"parsing not existing file %s, so fallback on default configuration!",
|
||||
file.getAbsolutePath()));
|
||||
return AuthorizationsCollector.emptyImmutableCollector();
|
||||
}
|
||||
try {
|
||||
FileReader reader = new FileReader(file);
|
||||
return parse(reader);
|
||||
} catch (FileNotFoundException fex) {
|
||||
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex);
|
||||
LOG.warn(
|
||||
String.format(
|
||||
"parsing not existing file %s, so fallback on default configuration!",
|
||||
file.getAbsolutePath()),
|
||||
fex);
|
||||
return AuthorizationsCollector.emptyImmutableCollector();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the ACL configuration file
|
||||
* @param reader to parse
|
||||
*
|
||||
* @param reader
|
||||
* to parse
|
||||
* @return the collector of authorizations form reader passed into.
|
||||
* @throws ParseException if the format is not compliant.
|
||||
* @throws ParseException
|
||||
* if the format is not compliant.
|
||||
*/
|
||||
public static AuthorizationsCollector parse(Reader reader) throws ParseException {
|
||||
if (reader == null) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.spi.security.IAuthenticator;
|
||||
@@ -6,6 +7,7 @@ import io.moquette.spi.security.IAuthenticator;
|
||||
* Created by andrea on 8/23/14.
|
||||
*/
|
||||
public class AcceptAllAuthenticator implements IAuthenticator {
|
||||
|
||||
public boolean checkValid(String clientId, String username, byte[] password) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import static io.moquette.spi.impl.security.Authorization.Permission.READWRITE;
|
||||
@@ -23,12 +24,13 @@ import static io.moquette.spi.impl.security.Authorization.Permission.READWRITE;
|
||||
* @author andrea
|
||||
*/
|
||||
public class Authorization {
|
||||
|
||||
protected final String topic;
|
||||
protected final Permission permission;
|
||||
|
||||
/**
|
||||
* Access rights
|
||||
* */
|
||||
*/
|
||||
enum Permission {
|
||||
READ, WRITE, READWRITE
|
||||
}
|
||||
@@ -48,13 +50,17 @@ public class Authorization {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
Authorization that = (Authorization) o;
|
||||
|
||||
if (permission != that.permission) return false;
|
||||
if (!topic.equals(that.topic)) return false;
|
||||
if (permission != that.permission)
|
||||
return false;
|
||||
if (!topic.equals(that.topic))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -13,19 +13,19 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
|
||||
import io.moquette.spi.security.IAuthorizator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Used by the ACLFileParser to push all authorizations it finds.
|
||||
* ACLAuthorizator uses it in read mode to check it topics matches the ACLs.
|
||||
* Used by the ACLFileParser to push all authorizations it finds. ACLAuthorizator uses it in read
|
||||
* mode to check it topics matches the ACLs.
|
||||
*
|
||||
* Not thread safe.
|
||||
*
|
||||
@@ -57,7 +57,8 @@ class AuthorizationsCollector implements IAuthorizator {
|
||||
return;
|
||||
}
|
||||
if (m_parsingUsersSpecificSection) {
|
||||
//TODO in java 8 switch to m_userAuthorizations.putIfAbsent(m_currentUser, new ArrayList());
|
||||
// TODO in java 8 switch to m_userAuthorizations.putIfAbsent(m_currentUser, new
|
||||
// ArrayList());
|
||||
if (!m_userAuthorizations.containsKey(m_currentUser)) {
|
||||
m_userAuthorizations.put(m_currentUser, new ArrayList<Authorization>());
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -6,14 +7,12 @@ import io.moquette.spi.security.IAuthenticator;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.*;
|
||||
|
||||
/**
|
||||
* Load user credentials from a SQL database.
|
||||
* sql driver must be provided at runtime
|
||||
* Load user credentials from a SQL database. sql driver must be provided at runtime
|
||||
*
|
||||
* @author mackristof
|
||||
*/
|
||||
@@ -25,21 +24,25 @@ public class DBAuthenticator implements IAuthenticator {
|
||||
private final MessageDigest messageDigest;
|
||||
private final PreparedStatement preparedStatement;
|
||||
|
||||
|
||||
|
||||
|
||||
public DBAuthenticator(IConfig conf) {
|
||||
this(conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DRIVER, ""),
|
||||
this(
|
||||
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DRIVER, ""),
|
||||
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_URL, ""),
|
||||
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_QUERY, ""),
|
||||
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DIGEST, ""));
|
||||
}
|
||||
|
||||
/** provide authenticator from SQL database
|
||||
* @param driver : jdbc driver class like : "org.postgresql.Driver"
|
||||
* @param jdbcUrl : jdbc url like : "jdbc:postgresql://host:port/dbname"
|
||||
* @param sqlQuery : sql query like : "SELECT PASSWORD FROM USER WHERE LOGIN=?"
|
||||
* @param digestMethod : password encoding algorithm : "MD5", "SHA-1", "SHA-256"
|
||||
/**
|
||||
* provide authenticator from SQL database
|
||||
*
|
||||
* @param driver
|
||||
* : jdbc driver class like : "org.postgresql.Driver"
|
||||
* @param jdbcUrl
|
||||
* : jdbc url like : "jdbc:postgresql://host:port/dbname"
|
||||
* @param sqlQuery
|
||||
* : sql query like : "SELECT PASSWORD FROM USER WHERE LOGIN=?"
|
||||
* @param digestMethod
|
||||
* : password encoding algorithm : "MD5", "SHA-1", "SHA-256"
|
||||
*/
|
||||
public DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod) {
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.spi.security.IAuthorizator;
|
||||
@@ -21,6 +22,7 @@ import io.moquette.spi.security.IAuthorizator;
|
||||
* @author andrea
|
||||
*/
|
||||
public class DenyAllAuthorizator implements IAuthorizator {
|
||||
|
||||
@Override
|
||||
public boolean canWrite(String topic, String user, String client) {
|
||||
return true;
|
||||
|
||||
@@ -13,19 +13,23 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.server.config.FileResourceLoader;
|
||||
|
||||
/**
|
||||
* Load user credentials from a text file.
|
||||
* Each line of the file is formatted as "[username]:[sha256(password)]". The username mustn't contains : char.
|
||||
* Load user credentials from a text file. Each line of the file is formatted as
|
||||
* "[username]:[sha256(password)]". The username mustn't contains : char.
|
||||
*
|
||||
* To encode your password from command line on Linux systems, you could use:
|
||||
*
|
||||
* <pre>
|
||||
* echo -n "yourpassword" | sha256sum
|
||||
* </pre>
|
||||
* NB -n is important because echo append a newline by default at the of string. -n avoid this behaviour.
|
||||
*
|
||||
* NB -n is important because echo append a newline by default at the of string. -n avoid this
|
||||
* behaviour.
|
||||
*
|
||||
* @author andrea
|
||||
* @deprecated user {@link ResourceAuthenticator} instead
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.spi.security.IAuthorizator;
|
||||
@@ -21,6 +22,7 @@ import io.moquette.spi.security.IAuthorizator;
|
||||
* @author andrea
|
||||
*/
|
||||
public class PermitAllAuthorizator implements IAuthorizator {
|
||||
|
||||
@Override
|
||||
public boolean canWrite(String topic, String user, String client) {
|
||||
return true;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.security;
|
||||
|
||||
import io.moquette.server.config.IResourceLoader;
|
||||
@@ -20,7 +21,6 @@ import io.moquette.spi.security.IAuthenticator;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
@@ -31,14 +31,17 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Load user credentials from a text resource.
|
||||
* Each line of the file is formatted as "[username]:[sha256(password)]". The username mustn't contains : char.
|
||||
* Load user credentials from a text resource. Each line of the file is formatted as
|
||||
* "[username]:[sha256(password)]". The username mustn't contains : char.
|
||||
*
|
||||
* To encode your password from command line on Linux systems, you could use:
|
||||
*
|
||||
* <pre>
|
||||
* echo -n "yourpassword" | sha256sum
|
||||
* </pre>
|
||||
* NB -n is important because echo append a newline by default at the of string. -n avoid this behaviour.
|
||||
*
|
||||
* NB -n is important because echo append a newline by default at the of string. -n avoid this
|
||||
* behaviour.
|
||||
*
|
||||
* @author andrea
|
||||
*/
|
||||
@@ -63,16 +66,15 @@ public class ResourceAuthenticator implements IAuthenticator {
|
||||
reader = resourceLoader.loadResource(resourceName);
|
||||
if (reader == null) {
|
||||
LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName));
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
parse(reader);
|
||||
}
|
||||
}
|
||||
catch (IResourceLoader.ResourceIsDirectoryException e) {
|
||||
} catch (IResourceLoader.ResourceIsDirectoryException e) {
|
||||
LOG.warn(String.format("Trying to parse directory %s", resourceName));
|
||||
}
|
||||
catch (ParseException pex) {
|
||||
LOG.warn(String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName), pex);
|
||||
} catch (ParseException pex) {
|
||||
LOG.warn(
|
||||
String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName),
|
||||
pex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,16 +13,15 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.subscriptions;
|
||||
|
||||
import io.moquette.spi.ISessionsStore.ClientTopicCouple;
|
||||
import io.netty.handler.codec.mqtt.MqttQoS;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Maintain the information about which Topic a certain ClientID is subscribed
|
||||
* and at which QoS
|
||||
* Maintain the information about which Topic a certain ClientID is subscribed and at which QoS
|
||||
*
|
||||
*
|
||||
* @author andrea
|
||||
@@ -67,14 +66,16 @@ public final class Subscription implements Serializable {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
Subscription that = (Subscription) o;
|
||||
|
||||
if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) return false;
|
||||
if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null)
|
||||
return false;
|
||||
return !(topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -86,8 +87,12 @@ public final class Subscription implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("[filter:%s, cliID: %s, qos: %s, active: %s]", this.topicFilter, this.clientId,
|
||||
this.requestedQos, this.active);
|
||||
return String.format(
|
||||
"[filter:%s, cliID: %s, qos: %s, active: %s]",
|
||||
this.topicFilter,
|
||||
this.clientId,
|
||||
this.requestedQos,
|
||||
this.active);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -13,13 +13,13 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.subscriptions;
|
||||
|
||||
import io.moquette.spi.ISessionsStore;
|
||||
import io.moquette.spi.ISessionsStore.ClientTopicCouple;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.LinkedBlockingDeque;
|
||||
@@ -33,6 +33,7 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
public class SubscriptionsStore {
|
||||
|
||||
public static class NodeCouple {
|
||||
|
||||
final TreeNode root;
|
||||
final TreeNode createdNode;
|
||||
|
||||
@@ -44,21 +45,27 @@ public class SubscriptionsStore {
|
||||
|
||||
/**
|
||||
* Check if the topic filter of the subscription is well formed
|
||||
* @param topicFilter the filter to validate
|
||||
*
|
||||
* @param topicFilter
|
||||
* the filter to validate
|
||||
* @return true if it's correct.
|
||||
* */
|
||||
*/
|
||||
public static boolean validate(String topicFilter) {
|
||||
try {
|
||||
parseTopic(topicFilter);
|
||||
return true;
|
||||
} catch (ParseException pex) {
|
||||
LOG.warn("The topic filter is malformed. TopicFilter = {}, cause = {}, errorMessage = {}.", topicFilter,
|
||||
pex.getCause(), pex.getMessage());
|
||||
LOG.warn(
|
||||
"The topic filter is malformed. TopicFilter = {}, cause = {}, errorMessage = {}.",
|
||||
topicFilter,
|
||||
pex.getCause(),
|
||||
pex.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IVisitor<T> {
|
||||
|
||||
void visit(TreeNode node, int deep);
|
||||
|
||||
T getResult();
|
||||
@@ -76,7 +83,8 @@ public class SubscriptionsStore {
|
||||
subScriptionsStr += indentTabs + couple.toString() + "\n";
|
||||
}
|
||||
s += node.getToken() == null ? "" : node.getToken().toString();
|
||||
s += "\n" + (node.m_subscriptions.isEmpty() ? indentTabs : "") + subScriptionsStr /*+ "\n"*/;
|
||||
s += "\n" + (node.m_subscriptions.isEmpty() ? indentTabs : "")
|
||||
+ subScriptionsStr /* + "\n" */;
|
||||
}
|
||||
|
||||
private String indentTabs(int deep) {
|
||||
@@ -99,9 +107,11 @@ public class SubscriptionsStore {
|
||||
private volatile ISessionsStore m_sessionsStore;
|
||||
|
||||
/**
|
||||
* Initialize the subscription tree with the list of subscriptions.
|
||||
* Maintained for compatibility reasons.
|
||||
* @param sessionsStore to be used as backing store from the subscription store.
|
||||
* Initialize the subscription tree with the list of subscriptions. Maintained for compatibility
|
||||
* reasons.
|
||||
*
|
||||
* @param sessionsStore
|
||||
* to be used as backing store from the subscription store.
|
||||
*/
|
||||
public void init(ISessionsStore sessionsStore) {
|
||||
LOG.info("Initializing subscriptions store...");
|
||||
@@ -113,7 +123,10 @@ public class SubscriptionsStore {
|
||||
}
|
||||
|
||||
for (ClientTopicCouple clientTopic : subscriptions) {
|
||||
LOG.info("Re-subscribing client to topic. ClientId = {}, topicFilter = {}.", clientTopic.clientID, clientTopic.topicFilter);
|
||||
LOG.info(
|
||||
"Re-subscribing client to topic. ClientId = {}, topicFilter = {}.",
|
||||
clientTopic.clientID,
|
||||
clientTopic.topicFilter);
|
||||
add(clientTopic);
|
||||
}
|
||||
if (LOG.isTraceEnabled()) {
|
||||
@@ -123,7 +136,8 @@ public class SubscriptionsStore {
|
||||
|
||||
public void add(ClientTopicCouple newSubscription) {
|
||||
/*
|
||||
* The topic filters have already been validated at the ProtocolProcessor. We can assume they are valid.
|
||||
* The topic filters have already been validated at the ProtocolProcessor. We can assume
|
||||
* they are valid.
|
||||
*/
|
||||
TreeNode oldRoot;
|
||||
NodeCouple couple;
|
||||
@@ -136,14 +150,16 @@ public class SubscriptionsStore {
|
||||
LOG.debug("A subscription has been added. Root = {}, oldRoot = {}.", couple.root, oldRoot);
|
||||
}
|
||||
|
||||
|
||||
protected NodeCouple recreatePath(String topic, final TreeNode oldRoot) {
|
||||
List<Token> tokens;
|
||||
try {
|
||||
tokens = parseTopic(topic);
|
||||
} catch (ParseException ex) {
|
||||
// TODO handle the parse exception
|
||||
LOG.error("The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.", topic, ex.getCause(),
|
||||
LOG.error(
|
||||
"The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.",
|
||||
topic,
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
throw new IllegalArgumentException(ex.getMessage());
|
||||
}
|
||||
@@ -174,7 +190,8 @@ public class SubscriptionsStore {
|
||||
|
||||
public void removeSubscription(String topic, String clientID) {
|
||||
/*
|
||||
* The topic filters have already been validated at the ProtocolProcessor. We can assume they are valid.
|
||||
* The topic filters have already been validated at the ProtocolProcessor. We can assume
|
||||
* they are valid.
|
||||
*/
|
||||
TreeNode oldRoot;
|
||||
NodeCouple couple;
|
||||
@@ -188,9 +205,11 @@ public class SubscriptionsStore {
|
||||
}
|
||||
|
||||
/**
|
||||
* Visit the topics tree to remove matching subscriptions with clientID.
|
||||
* It's a mutating structure operation so create a new subscription tree (partial or total).
|
||||
* @param clientID the client ID to remove.
|
||||
* Visit the topics tree to remove matching subscriptions with clientID. It's a mutating
|
||||
* structure operation so create a new subscription tree (partial or total).
|
||||
*
|
||||
* @param clientID
|
||||
* the client ID to remove.
|
||||
*/
|
||||
public void removeForClient(String clientID) {
|
||||
TreeNode oldRoot;
|
||||
@@ -202,13 +221,13 @@ public class SubscriptionsStore {
|
||||
} while (!subscriptions.compareAndSet(oldRoot, newRoot));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Given a topic string return the clients subscriptions that matches it.
|
||||
* Topic string can't contain character # and + because they are reserved to
|
||||
* listeners subscriptions, and not topic publishing.
|
||||
* Given a topic string return the clients subscriptions that matches it. Topic string can't
|
||||
* contain character # and + because they are reserved to listeners subscriptions, and not topic
|
||||
* publishing.
|
||||
*
|
||||
* @param topic to use fo searching matching subscriptions.
|
||||
* @param topic
|
||||
* to use fo searching matching subscriptions.
|
||||
* @return the list of matching subscriptions, or empty if not matching.
|
||||
*/
|
||||
public List<Subscription> matches(String topic) {
|
||||
@@ -217,7 +236,11 @@ public class SubscriptionsStore {
|
||||
tokens = parseTopic(topic);
|
||||
} catch (ParseException ex) {
|
||||
// TODO handle the parse exception
|
||||
LOG.warn("The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.", topic, ex.getCause(), ex.getMessage());
|
||||
LOG.warn(
|
||||
"The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.",
|
||||
topic,
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@@ -268,8 +291,11 @@ public class SubscriptionsStore {
|
||||
|
||||
/**
|
||||
* Verify if the 2 topics matching respecting the rules of MQTT Appendix A
|
||||
* @param msgTopic the topic to match from the message
|
||||
* @param subscriptionTopic the topic filter of the subscription
|
||||
*
|
||||
* @param msgTopic
|
||||
* the topic to match from the message
|
||||
* @param subscriptionTopic
|
||||
* the topic filter of the subscription
|
||||
* @return true if the two topics match.
|
||||
*/
|
||||
// TODO reimplement with iterators or with queues
|
||||
@@ -304,8 +330,12 @@ public class SubscriptionsStore {
|
||||
return i == msgTokens.size();
|
||||
} catch (ParseException ex) {
|
||||
LOG.error(
|
||||
"The message topic, the subscription topic or both are malformed. MsgTopic = {}, subscriptionTopic = {}, cause = {}, errorMessage = {}.",
|
||||
msgTopic, subscriptionTopic, ex.getCause(), ex.getMessage());
|
||||
"The message topic, the subscription topic or both are malformed. "
|
||||
+ "MsgTopic = {}, subscriptionTopic = {}, cause = {}, errorMessage = {}.",
|
||||
msgTopic,
|
||||
subscriptionTopic,
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
throw new IllegalStateException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -330,13 +360,16 @@ public class SubscriptionsStore {
|
||||
String s = splitted[i];
|
||||
if (s.isEmpty()) {
|
||||
// if (i != 0) {
|
||||
// throw new ParseException("Bad format of topic, expetec topic name between separators", i);
|
||||
// throw new ParseException("Bad format of topic, expetec topic name between
|
||||
// separators", i);
|
||||
// }
|
||||
res.add(Token.EMPTY);
|
||||
} else if (s.equals("#")) {
|
||||
// check that multi is the last symbol
|
||||
if (i != splitted.length - 1) {
|
||||
throw new ParseException("Bad format of topic, the multi symbol (#) has to be the last one after a separator", i);
|
||||
throw new ParseException(
|
||||
"Bad format of topic, the multi symbol (#) has to be the last one after a separator",
|
||||
i);
|
||||
}
|
||||
res.add(Token.MULTI);
|
||||
} else if (s.contains("#")) {
|
||||
|
||||
@@ -13,11 +13,12 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.subscriptions;
|
||||
|
||||
/**
|
||||
* Internal use only class.
|
||||
* */
|
||||
*/
|
||||
public class Token {
|
||||
|
||||
static final Token EMPTY = new Token("");
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl.subscriptions;
|
||||
|
||||
import io.moquette.spi.ISessionsStore.ClientTopicCouple;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
@@ -47,9 +47,8 @@ class TreeNode {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a shallow copy of the current node.
|
||||
* Copy the token and the children.
|
||||
* */
|
||||
* Creates a shallow copy of the current node. Copy the token and the children.
|
||||
*/
|
||||
TreeNode copy() {
|
||||
final TreeNode copy = new TreeNode();
|
||||
copy.m_children = new ArrayList<>(m_children);
|
||||
@@ -59,8 +58,7 @@ class TreeNode {
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for children that has the specified token, if not found return
|
||||
* null;
|
||||
* Search for children that has the specified token, if not found return null;
|
||||
*/
|
||||
TreeNode childWithToken(Token token) {
|
||||
for (TreeNode child : m_children) {
|
||||
@@ -131,7 +129,7 @@ class TreeNode {
|
||||
|
||||
/**
|
||||
* Create a copied subtree rooted on this node but purged of clientID's subscriptions.
|
||||
* */
|
||||
*/
|
||||
TreeNode removeClientSubscriptions(String clientID) {
|
||||
// collect what to delete and then delete to avoid ConcurrentModification
|
||||
TreeNode newSubRoot = this.copy();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.persistence;
|
||||
|
||||
import io.moquette.spi.IMatchingCondition;
|
||||
@@ -21,7 +22,6 @@ import io.moquette.spi.MessageGUID;
|
||||
import org.mapdb.DB;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
@@ -41,7 +41,6 @@ class MapDBMessagesStore implements IMessagesStore {
|
||||
// maps guid to message, it's message store
|
||||
private ConcurrentMap<MessageGUID, IMessagesStore.StoredMessage> m_persistentMessageStore;
|
||||
|
||||
|
||||
MapDBMessagesStore(DB db) {
|
||||
m_db = db;
|
||||
}
|
||||
@@ -83,10 +82,15 @@ class MapDBMessagesStore implements IMessagesStore {
|
||||
assert storedMessage.getClientID() != null : "The message to be persisted must have a valid client ID";
|
||||
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
|
||||
storedMessage.setGuid(guid);
|
||||
LOG.debug("Storing publish event. MqttClientId = {}, messageId = {}, guid = {}, topic = {}.",
|
||||
storedMessage.getClientID(), storedMessage.getMessageID(), guid, storedMessage.getTopic());
|
||||
LOG.debug(
|
||||
"Storing publish event. MqttClientId = {}, messageId = {}, guid = {}, topic = {}.",
|
||||
storedMessage.getClientID(),
|
||||
storedMessage.getMessageID(),
|
||||
guid,
|
||||
storedMessage.getTopic());
|
||||
m_persistentMessageStore.put(guid, storedMessage);
|
||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(storedMessage.getClientID()));
|
||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db
|
||||
.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(storedMessage.getClientID()));
|
||||
messageIdToGuid.put(storedMessage.getMessageID(), guid);
|
||||
return guid;
|
||||
}
|
||||
@@ -94,7 +98,8 @@ class MapDBMessagesStore implements IMessagesStore {
|
||||
@Override
|
||||
public void dropMessagesInSession(String clientID) {
|
||||
LOG.debug("Dropping stored messages. ClientId = {}.", clientID);
|
||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(clientID));
|
||||
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db
|
||||
.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(clientID));
|
||||
for (MessageGUID guid : messageIdToGuid.values()) {
|
||||
removeStoredMessage(guid);
|
||||
}
|
||||
@@ -105,8 +110,12 @@ class MapDBMessagesStore implements IMessagesStore {
|
||||
// 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());
|
||||
LOG.debug(
|
||||
"Dropping stored message. ClientId = {}, messageId = {}, guid = {}, topic = {}.",
|
||||
storedMessage.getClientID(),
|
||||
storedMessage.getMessageID(),
|
||||
guid,
|
||||
storedMessage.getTopic());
|
||||
m_persistentMessageStore.remove(guid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,14 +23,12 @@ import org.mapdb.DB;
|
||||
import org.mapdb.DBMaker;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.moquette.BrokerConstants.AUTOSAVE_INTERVAL_PROPERTY_NAME;
|
||||
import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
|
||||
|
||||
@@ -40,10 +38,11 @@ import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
|
||||
public class MapDBPersistentStore {
|
||||
|
||||
/**
|
||||
* This is a DTO used to persist minimal status (clean session and activation status) of
|
||||
* a session.
|
||||
* */
|
||||
* This is a DTO used to persist minimal status (clean session and activation status) of a
|
||||
* session.
|
||||
*/
|
||||
public static class PersistentSession implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 5052054783220481854L;
|
||||
public final boolean cleanSession;
|
||||
|
||||
@@ -69,8 +68,9 @@ public class MapDBPersistentStore {
|
||||
|
||||
/**
|
||||
* Factory method to create message store backed by MapDB
|
||||
*
|
||||
* @return the message store instance.
|
||||
* */
|
||||
*/
|
||||
public IMessagesStore messagesStore() {
|
||||
return m_messageStore;
|
||||
}
|
||||
@@ -92,13 +92,20 @@ public class MapDBPersistentStore {
|
||||
boolean fileNewlyCreated = tmpFile.createNewFile();
|
||||
LOG.warn("Using {} MapDB store file. Path = {}.", fileNewlyCreated ? "fresh" : "existing", m_storePath);
|
||||
} catch (IOException ex) {
|
||||
LOG.error("Unable to open MapDB store file. Path = {}, cause = {}, errorMessage = {}.", m_storePath, ex.getCause(), ex.getMessage());
|
||||
throw new RuntimeException("Can't create temp file for subscriptions storage [" + m_storePath + "]", ex);
|
||||
LOG.error(
|
||||
"Unable to open MapDB store file. Path = {}, cause = {}, errorMessage = {}.",
|
||||
m_storePath,
|
||||
ex.getCause(),
|
||||
ex.getMessage());
|
||||
throw new RuntimeException(
|
||||
"Can't create temp file for subscriptions storage [" + m_storePath + "]",
|
||||
ex);
|
||||
}
|
||||
m_db = DBMaker.newFileDB(tmpFile).make();
|
||||
}
|
||||
LOG.info("Scheduling MapDB commit task...");
|
||||
m_scheduler.scheduleWithFixedDelay(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Committing to MapDB...");
|
||||
@@ -127,7 +134,8 @@ public class MapDBPersistentStore {
|
||||
this.m_scheduler.shutdown();
|
||||
try {
|
||||
m_scheduler.awaitTermination(10L, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {}
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
if (!m_scheduler.isTerminated()) {
|
||||
LOG.warn("Forcing shutdown of MapDB commit tasks...");
|
||||
m_scheduler.shutdown();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.persistence;
|
||||
|
||||
import io.moquette.spi.ClientSession;
|
||||
@@ -25,7 +26,6 @@ import io.moquette.spi.persistence.MapDBPersistentStore.PersistentSession;
|
||||
import org.mapdb.DB;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -66,14 +66,18 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
|
||||
@Override
|
||||
public void addNewSubscription(Subscription newSubscription) {
|
||||
LOG.info("Adding new subscription. CId= {}, topics = {}.", newSubscription.getClientId(),
|
||||
LOG.info(
|
||||
"Adding new subscription. CId= {}, topics = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter());
|
||||
final String clientID = newSubscription.getClientId();
|
||||
m_db.getHashMap("subscriptions_" + clientID).put(newSubscription.getTopicFilter(), newSubscription);
|
||||
|
||||
if (LOG.isTraceEnabled()) {
|
||||
LOG.trace("The subscription has been added. CId= {}, topics = {}, clientSubscriptions = {}.",
|
||||
newSubscription.getClientId(), newSubscription.getTopicFilter(),
|
||||
LOG.trace(
|
||||
"The subscription has been added. CId= {}, topics = {}, clientSubscriptions = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter(),
|
||||
m_db.getHashMap("subscriptions_" + clientID));
|
||||
}
|
||||
}
|
||||
@@ -86,8 +90,11 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
}
|
||||
m_db.getHashMap("subscriptions_" + clientID).remove(topicFilter);
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("The subscription has been removed. CId= {}, topics = {}, clientSubscriptions = {}.",
|
||||
clientID, topicFilter, m_db.getHashMap("subscriptions_" + clientID));
|
||||
LOG.debug(
|
||||
"The subscription has been removed. CId= {}, topics = {}, clientSubscriptions = {}.",
|
||||
clientID,
|
||||
topicFilter,
|
||||
m_db.getHashMap("subscriptions_" + clientID));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +103,9 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
LOG.info("Wiping subscriptions. CId= {}.", clientID);
|
||||
m_db.delete("subscriptions_" + clientID);
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("The subscriptions have been removed. CId= {}, clientSubscriptions = {}.", clientID,
|
||||
LOG.debug(
|
||||
"The subscriptions have been removed. CId= {}, clientSubscriptions = {}.",
|
||||
clientID,
|
||||
m_db.getHashMap("subscriptions_" + clientID));
|
||||
}
|
||||
}
|
||||
@@ -120,8 +129,7 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
@Override
|
||||
public Subscription getSubscription(ClientTopicCouple couple) {
|
||||
ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID);
|
||||
LOG.info("Retrieving subscriptions. CId= {}, subscriptions = {}.", couple.clientID,
|
||||
clientSubscriptions);
|
||||
LOG.info("Retrieving subscriptions. CId= {}, subscriptions = {}.", couple.clientID, clientSubscriptions);
|
||||
return clientSubscriptions.get(couple.topicFilter);
|
||||
}
|
||||
|
||||
@@ -147,7 +155,8 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
if (m_persistentSessions.containsKey(clientID)) {
|
||||
LOG.error(
|
||||
"Unable to create a new session: the client ID is already in use. CId= {}, cleanSession = {}.",
|
||||
clientID, cleanSession);
|
||||
clientID,
|
||||
cleanSession);
|
||||
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
|
||||
}
|
||||
LOG.info("Creating new session. CId= {}, cleanSession = {}.", clientID, cleanSession);
|
||||
@@ -169,7 +178,7 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
|
||||
@Override
|
||||
public Collection<ClientSession> getAllSessions() {
|
||||
Collection<ClientSession> result = new ArrayList<ClientSession>();
|
||||
Collection<ClientSession> result = new ArrayList<>();
|
||||
for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) {
|
||||
result.add(new ClientSession(entry.getKey(), m_messagesStore, this, entry.getValue().cleanSession));
|
||||
}
|
||||
@@ -184,7 +193,7 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
|
||||
/**
|
||||
* Return the next valid packetIdentifier for the given client session.
|
||||
* */
|
||||
*/
|
||||
@Override
|
||||
public int nextPacketID(String clientID) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
@@ -268,7 +277,8 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
inFlightForClient.remove(messageID);
|
||||
}
|
||||
|
||||
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>());
|
||||
Map<Integer, MessageGUID> messageIDs = Utils
|
||||
.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>());
|
||||
messageIDs.put(messageID, guid);
|
||||
m_secondPhaseStore.put(clientID, messageIDs);
|
||||
}
|
||||
@@ -278,7 +288,8 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("Processing second phase ACK CId={}, messageId={}", clientID, messageID);
|
||||
}
|
||||
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>());
|
||||
Map<Integer, MessageGUID> messageIDs = Utils
|
||||
.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>());
|
||||
MessageGUID guid = messageIDs.remove(messageID);
|
||||
m_secondPhaseStore.put(clientID, messageIDs);
|
||||
return guid;
|
||||
@@ -307,8 +318,7 @@ class MapDBSessionsStore implements ISessionsStore {
|
||||
}
|
||||
MessageGUID guid = clientEntries.get(messageID);
|
||||
if (guid == null) {
|
||||
LOG.warn("The message ID does not have an associated GUID. CId= {}, messageId = {}.", clientID,
|
||||
messageID);
|
||||
LOG.warn("The message ID does not have an associated GUID. CId= {}, messageId = {}.", clientID, messageID);
|
||||
return null;
|
||||
}
|
||||
return m_messagesStore.getMessageByGuid(guid);
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.security;
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,14 +13,14 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.security;
|
||||
|
||||
/**
|
||||
* ACL checker.
|
||||
*
|
||||
* Create an authorizator that matches topic names with same grammar of subscriptions.
|
||||
* The # is always a terminator and its the multilevel matcher.
|
||||
* The + sign is the single level matcher.
|
||||
* Create an authorizator that matches topic names with same grammar of subscriptions. The # is
|
||||
* always a terminator and its the multilevel matcher. The + sign is the single level matcher.
|
||||
*
|
||||
* @author andrea
|
||||
*/
|
||||
@@ -28,11 +28,15 @@ public interface IAuthorizator {
|
||||
|
||||
/**
|
||||
* Ask the implementation of the authorizator if the topic can be used in a publish.
|
||||
* @param topic the topic to write to.
|
||||
* @param user the user
|
||||
* @param client the client
|
||||
*
|
||||
* @param topic
|
||||
* the topic to write to.
|
||||
* @param user
|
||||
* the user
|
||||
* @param client
|
||||
* the client
|
||||
* @return true if the user from client can publish data on topic.
|
||||
* */
|
||||
*/
|
||||
boolean canWrite(String topic, String user, String client);
|
||||
|
||||
boolean canRead(String topic, String user, String client);
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.security;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
@@ -23,7 +24,6 @@ import io.netty.util.Attribute;
|
||||
import io.netty.util.AttributeKey;
|
||||
import io.netty.util.AttributeMap;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
/**
|
||||
@@ -66,8 +66,7 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the variable remaining length as defined in MQTT v3.1 specification
|
||||
* (section 2.1).
|
||||
* Decode the variable remaining length as defined in MQTT v3.1 specification (section 2.1).
|
||||
*
|
||||
* @return the decoded length or -1 if needed more data to decode the length field.
|
||||
*/
|
||||
@@ -87,11 +86,10 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the value in the format defined in specification as variable length
|
||||
* array.
|
||||
* Encode the value in the format defined in specification as variable length array.
|
||||
*
|
||||
* @throws IllegalArgumentException if the value is not in the specification bounds
|
||||
* [0..268435455].
|
||||
* @throws IllegalArgumentException
|
||||
* if the value is not in the specification bounds [0..268435455].
|
||||
*/
|
||||
static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException {
|
||||
if (value > MAX_LENGTH_LIMIT || value < 0) {
|
||||
@@ -113,8 +111,8 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a string from the given buffer, reading first the two bytes of len
|
||||
* and then the UTF-8 bytes of the string.
|
||||
* Load a string from the given buffer, reading first the two bytes of len and then the UTF-8
|
||||
* bytes of the string.
|
||||
*
|
||||
* @return the decoded string or null if NEED_DATA
|
||||
*/
|
||||
@@ -123,8 +121,9 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a byte array from the buffer, use two bytes as length information followed by length bytes.
|
||||
* */
|
||||
* Read a byte array from the buffer, use two bytes as length information followed by length
|
||||
* bytes.
|
||||
*/
|
||||
static byte[] readFixedLengthContent(ByteBuf in) throws UnsupportedEncodingException {
|
||||
if (in.readableBytes() < 2) {
|
||||
return null;
|
||||
@@ -140,8 +139,7 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded
|
||||
* string content.
|
||||
* Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded string content.
|
||||
*/
|
||||
public static ByteBuf encodeString(String str) {
|
||||
byte[] raw;
|
||||
@@ -170,10 +168,14 @@ public class Utils {
|
||||
* Return the number of bytes to encode the given remaining length value
|
||||
*/
|
||||
static int numBytesToEncode(int len) {
|
||||
if (0 <= len && len <= 127) return 1;
|
||||
if (128 <= len && len <= 16383) return 2;
|
||||
if (16384 <= len && len <= 2097151) return 3;
|
||||
if (2097152 <= len && len <= 268435455) return 4;
|
||||
if (0 <= len && len <= 127)
|
||||
return 1;
|
||||
if (128 <= len && len <= 16383)
|
||||
return 2;
|
||||
if (16384 <= len && len <= 2097151)
|
||||
return 3;
|
||||
if (2097152 <= len && len <= 268435455)
|
||||
return 4;
|
||||
throw new IllegalArgumentException("value shoul be in the range [0..268435455]");
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -22,11 +23,9 @@ import io.moquette.spi.security.IAuthenticator;
|
||||
import io.moquette.spi.security.IAuthorizator;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
@@ -34,6 +33,7 @@ import static org.junit.Assert.*;
|
||||
* @author luca <luca.capra@create-net.org>
|
||||
*/
|
||||
public class ConfigurationClassLoaderTest implements IAuthenticator, IAuthorizator {
|
||||
|
||||
Server m_server;
|
||||
IConfig m_config;
|
||||
|
||||
@@ -43,7 +43,6 @@ public class ConfigurationClassLoaderTest implements IAuthenticator, IAuthorizat
|
||||
m_server.startServer(m_config);
|
||||
}
|
||||
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
m_server.stopServer();
|
||||
|
||||
@@ -13,13 +13,12 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Properties;
|
||||
|
||||
import static io.moquette.BrokerConstants.DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
|
||||
import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
|
||||
import static io.moquette.BrokerConstants.PORT_PROPERTY_NAME;
|
||||
@@ -31,6 +30,7 @@ import static org.junit.Assert.assertFalse;
|
||||
* Created by andrea on 4/7/15.
|
||||
*/
|
||||
public class IntegrationUtils {
|
||||
|
||||
static String localMapDBPath() {
|
||||
String currentDir = System.getProperty("user.dir");
|
||||
return currentDir + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -68,8 +69,7 @@ public class MQTTWebSocket {
|
||||
|
||||
ByteBuffer msg = ByteBuffer.wrap(new byte[]{0x10, // message type
|
||||
0x0C, // remaining lenght 12 bytes
|
||||
'M', 'Q','I','s','d','p',
|
||||
0x03, //protocol version
|
||||
'M', 'Q', 'I', 's', 'd', 'p', 0x03, // protocol version
|
||||
0x32, // flags
|
||||
0x02, 0x00// keepAlive Timer, 2 seconds
|
||||
});
|
||||
|
||||
@@ -13,12 +13,12 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
@@ -27,6 +27,7 @@ import java.util.concurrent.*;
|
||||
public class MessageCollector implements MqttCallback {
|
||||
|
||||
private class ReceivedMessage {
|
||||
|
||||
private final MqttMessage message;
|
||||
private final String topic;
|
||||
|
||||
@@ -41,7 +42,7 @@ public class MessageCollector implements MqttCallback {
|
||||
|
||||
/**
|
||||
* Return the message from the queue if not empty, else return null with wait period.
|
||||
* */
|
||||
*/
|
||||
public MqttMessage getMessageImmediate() {
|
||||
if (m_messages.isEmpty()) {
|
||||
return null;
|
||||
@@ -94,7 +95,7 @@ public class MessageCollector implements MqttCallback {
|
||||
|
||||
/**
|
||||
* Invoked when the message sent to a server is ACKED (PUBACK or PUBCOMP by the server)
|
||||
* */
|
||||
*/
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
// try {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -10,19 +11,18 @@ import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
|
||||
import org.junit.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Created by mackristof on 13/05/2016.
|
||||
*/
|
||||
public class ServerIntegrationDBAuthenticatorTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationDBAuthenticatorTest.class);
|
||||
|
||||
static MqttClientPersistence s_dataStore;
|
||||
@@ -35,8 +35,6 @@ public class ServerIntegrationDBAuthenticatorTest {
|
||||
MessageCollector m_messagesCollector;
|
||||
IConfig m_config;
|
||||
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() throws NoSuchAlgorithmException, SQLException, ClassNotFoundException {
|
||||
String tmpDir = System.getProperty("java.io.tmpdir");
|
||||
@@ -53,7 +51,6 @@ public class ServerIntegrationDBAuthenticatorTest {
|
||||
m_server.startServer(m_config);
|
||||
}
|
||||
|
||||
|
||||
private void stopServer() {
|
||||
m_server.stopServer();
|
||||
IntegrationUtils.cleanPersistenceFile(m_config);
|
||||
@@ -111,7 +108,6 @@ public class ServerIntegrationDBAuthenticatorTest {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void connectWithWrongCredentials() {
|
||||
LOG.info("*** connectWithWrongCredentials ***");
|
||||
@@ -131,8 +127,6 @@ public class ServerIntegrationDBAuthenticatorTest {
|
||||
}
|
||||
}
|
||||
assertTrue("must not be connected. cause : wrong password given to client", false);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.netty.MessageBuilder;
|
||||
@@ -28,11 +29,9 @@ import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ServerIntegrationEmbeddedPublishTest {
|
||||
@@ -89,12 +88,8 @@ public class ServerIntegrationEmbeddedPublishTest {
|
||||
}
|
||||
|
||||
private void internalPublishToWithQosAndRetained(String topic, MqttQoS qos, boolean retained) {
|
||||
MqttPublishMessage message = MessageBuilder.publish()
|
||||
.topicName(topic)
|
||||
.retained(retained)
|
||||
.qos(qos)
|
||||
.payload("Hello world MQTT!!".getBytes())
|
||||
.build();
|
||||
MqttPublishMessage message = MessageBuilder.publish().topicName(topic).retained(retained).qos(qos)
|
||||
.payload("Hello world MQTT!!".getBytes()).build();
|
||||
m_server.internalPublish(message, "INTRPUBL");
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
@@ -23,11 +24,9 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
@@ -35,6 +34,7 @@ import static org.junit.Assert.*;
|
||||
* @author andrea
|
||||
*/
|
||||
public class ServerIntegrationFuseTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationPahoTest.class);
|
||||
|
||||
Server m_server;
|
||||
|
||||
+13
-7
@@ -1,3 +1,4 @@
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -12,16 +13,15 @@ import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
|
||||
import org.junit.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ServerIntegrationHazelcastHandlerInterceptorTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationHazelcastHandlerInterceptorTest.class);
|
||||
|
||||
static MqttClientPersistence s_dataStore;
|
||||
@@ -55,7 +55,9 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest{
|
||||
|
||||
private Properties addHazelCastConf(Properties properties, int port, String hazelcastConfigurationFile) {
|
||||
properties.put(BrokerConstants.PORT_PROPERTY_NAME, port);
|
||||
properties.put(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, HazelcastInterceptHandler.class.getCanonicalName());
|
||||
properties.put(
|
||||
BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME,
|
||||
HazelcastInterceptHandler.class.getCanonicalName());
|
||||
properties.put(BrokerConstants.HAZELCAST_CONFIGURATION, hazelcastConfigurationFile);
|
||||
return properties;
|
||||
}
|
||||
@@ -65,14 +67,18 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest{
|
||||
String dbPath = IntegrationUtils.localMapDBPath();
|
||||
IntegrationUtils.cleanPersistenceFile(dbPath);
|
||||
|
||||
final Properties configProps = addHazelCastConf(IntegrationUtils.prepareTestClusterProperties(1883),
|
||||
1883, "config/hazelcast.xml");
|
||||
final Properties configProps = addHazelCastConf(
|
||||
IntegrationUtils.prepareTestClusterProperties(1883),
|
||||
1883,
|
||||
"config/hazelcast.xml");
|
||||
m_config_1883 = new MemoryConfig(configProps);
|
||||
|
||||
server1883 = startServer(1883, m_config_1883);
|
||||
|
||||
final Properties configProps1884 = addHazelCastConf(IntegrationUtils.prepareTestClusterProperties(1884),
|
||||
1883, "config/hazelcast.xml");
|
||||
final Properties configProps1884 = addHazelCastConf(
|
||||
IntegrationUtils.prepareTestClusterProperties(1884),
|
||||
1883,
|
||||
"config/hazelcast.xml");
|
||||
m_config_1884 = new MemoryConfig(configProps1884);
|
||||
server1884 = startServer(1884, m_config_1884);
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
@@ -22,11 +23,9 @@ import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
|
||||
import org.junit.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ServerIntegrationPahoTest {
|
||||
@@ -114,7 +113,6 @@ public class ServerIntegrationPahoTest {
|
||||
assertEquals("/topic", m_messagesCollector.getTopic());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCleanSession_maintainClientSubscriptions() throws Exception {
|
||||
LOG.info("*** testCleanSession_maintainClientSubscriptions ***");
|
||||
@@ -134,7 +132,6 @@ public class ServerIntegrationPahoTest {
|
||||
assertEquals("/topic", m_messagesCollector.getTopic());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCleanSession_maintainClientSubscriptions_againstClientDestruction() throws Exception {
|
||||
LOG.info("*** testCleanSession_maintainClientSubscriptions_againstClientDestruction ***");
|
||||
@@ -152,9 +149,9 @@ public class ServerIntegrationPahoTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that after a client has connected with clean session false, subscribed
|
||||
* to some topic and exited, if it reconnects with clean session true, the m_server
|
||||
* correctly cleanup every previous subscription
|
||||
* Check that after a client has connected with clean session false, subscribed to some topic
|
||||
* and exited, if it reconnects with clean session true, the m_server correctly cleanup every
|
||||
* previous subscription
|
||||
*/
|
||||
@Test
|
||||
public void testCleanSession_correctlyClientSubscriptions() throws Exception {
|
||||
@@ -283,7 +280,6 @@ public class ServerIntegrationPahoTest {
|
||||
assertEquals("Hello MQTT", m_messagesCollector.waitMessage(1).toString());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession() throws Exception {
|
||||
LOG.info("*** checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession ***");
|
||||
@@ -383,11 +379,9 @@ public class ServerIntegrationPahoTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* subscriber A connect and subscribe on "a/b" QoS 1
|
||||
* subscriber B connect and subscribe on "a/+" BUT with QoS 2
|
||||
* publisher connects and send a message "hello" on "a/b"
|
||||
* subscriber A must receive a notification with QoS1
|
||||
* subscriber B must receive a notification with QoS2
|
||||
* subscriber A connect and subscribe on "a/b" QoS 1 subscriber B connect and subscribe on "a/+"
|
||||
* BUT with QoS 2 publisher connects and send a message "hello" on "a/b" subscriber A must
|
||||
* receive a notification with QoS1 subscriber B must receive a notification with QoS2
|
||||
*/
|
||||
@Test
|
||||
public void checkSubscribersGetCorrectQosNotifications() throws Exception {
|
||||
@@ -410,7 +404,6 @@ public class ServerIntegrationPahoTest {
|
||||
subscriberB.connect();
|
||||
subscriberB.subscribe("a/+", 2);
|
||||
|
||||
|
||||
m_client.connect();
|
||||
m_client.publish("a/b", "Hello world MQTT!!".getBytes(), 2, false);
|
||||
|
||||
@@ -430,7 +423,8 @@ public class ServerIntegrationPahoTest {
|
||||
LOG.info("*** testSubcriptionDoesntStayActiveAfterARestart ***");
|
||||
String tmpDir = System.getProperty("java.io.tmpdir");
|
||||
// clientForSubscribe1 connect and subscribe to /topic QoS2
|
||||
MqttClientPersistence dsSubscriberA = new MqttDefaultFilePersistence(tmpDir + File.separator + "clientForSubscribe1");
|
||||
MqttClientPersistence dsSubscriberA = new MqttDefaultFilePersistence(
|
||||
tmpDir + File.separator + "clientForSubscribe1");
|
||||
|
||||
MqttClient clientForSubscribe1 = new MqttClient("tcp://localhost:1883", "clientForSubscribe1", dsSubscriberA);
|
||||
MessageCollector cbSubscriber1 = new MessageCollector();
|
||||
@@ -445,7 +439,8 @@ public class ServerIntegrationPahoTest {
|
||||
startServer();
|
||||
|
||||
// clientForSubscribe2 connect and subscribe to /topic QoS2
|
||||
MqttClientPersistence dsSubscriberB = new MqttDefaultFilePersistence(tmpDir + File.separator + "clientForSubscribe2");
|
||||
MqttClientPersistence dsSubscriberB = new MqttDefaultFilePersistence(
|
||||
tmpDir + File.separator + "clientForSubscribe2");
|
||||
MqttClient clientForSubscribe2 = new MqttClient("tcp://localhost:1883", "clientForSubscribe2", dsSubscriberB);
|
||||
MessageCollector cbSubscriber2 = new MessageCollector();
|
||||
clientForSubscribe2.setCallback(cbSubscriber2);
|
||||
@@ -453,7 +448,8 @@ public class ServerIntegrationPahoTest {
|
||||
clientForSubscribe2.subscribe("topic", 0);
|
||||
|
||||
// clientForPublish publish on /topic with QoS2 a message
|
||||
MqttClientPersistence dsSubscriberPUB = new MqttDefaultFilePersistence(tmpDir + File.separator + "clientForPublish");
|
||||
MqttClientPersistence dsSubscriberPUB = new MqttDefaultFilePersistence(
|
||||
tmpDir + File.separator + "clientForPublish");
|
||||
MqttClient clientForPublish = new MqttClient("tcp://localhost:1883", "clientForPublish", dsSubscriberPUB);
|
||||
clientForPublish.connect();
|
||||
clientForPublish.publish("topic", "Hello".getBytes(), 2, true);
|
||||
@@ -572,10 +568,9 @@ public class ServerIntegrationPahoTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* subscriber connect and subscribe on "topic"
|
||||
* subscriber disconnects
|
||||
* publisher connects and send two message "hello1" "hello2" to "topic"
|
||||
* subscriber connects again and receive "hello1" "hello2"
|
||||
* subscriber connect and subscribe on "topic" subscriber disconnects publisher connects and
|
||||
* send two message "hello1" "hello2" to "topic" subscriber connects again and receive "hello1"
|
||||
* "hello2"
|
||||
*/
|
||||
@Test
|
||||
public void checkQoS2SubscriberDisconnectReceivePersistedPublishes() throws Exception {
|
||||
@@ -605,9 +600,8 @@ public class ServerIntegrationPahoTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* subscriber connect and subscribe on "a/b" QoS 1 and "a/+" QoS 2
|
||||
* publisher connects and send a message "hello" on "a/b"
|
||||
* subscriber must receive only a single message not twice
|
||||
* subscriber connect and subscribe on "a/b" QoS 1 and "a/+" QoS 2 publisher connects and send a
|
||||
* message "hello" on "a/b" subscriber must receive only a single message not twice
|
||||
*/
|
||||
@Test
|
||||
public void checkSinglePublishOnOverlappingSubscriptions() throws Exception {
|
||||
@@ -634,7 +628,6 @@ public class ServerIntegrationPahoTest {
|
||||
assertNull(msg);
|
||||
}
|
||||
|
||||
|
||||
protected MqttClient createClient(String clientName, String storeSuffix) throws MqttException {
|
||||
return createClient(clientName, storeSuffix, null);
|
||||
}
|
||||
@@ -642,7 +635,8 @@ public class ServerIntegrationPahoTest {
|
||||
protected MqttClient createClient(String clientName, String storeSuffix, MessageCollector cb) throws MqttException {
|
||||
String tmpDir = System.getProperty("java.io.tmpdir");
|
||||
// clientX connect and subscribe to /topic QoS2
|
||||
MqttClientPersistence dsClient = new MqttDefaultFilePersistence(tmpDir + File.separator + storeSuffix + clientName);
|
||||
MqttClientPersistence dsClient = new MqttDefaultFilePersistence(
|
||||
tmpDir + File.separator + storeSuffix + clientName);
|
||||
MqttClient client = new MqttClient("tcp://localhost:1883", clientName, dsClient);
|
||||
if (cb != null) {
|
||||
client.setCallback(cb);
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
package io.moquette.server;
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
import io.moquette.server.config.MemoryConfig;
|
||||
@@ -29,11 +29,9 @@ import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -27,13 +27,11 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
@@ -53,6 +51,7 @@ import org.slf4j.LoggerFactory;
|
||||
*
|
||||
* <p>
|
||||
* Create certificates needed for client authentication
|
||||
*
|
||||
* <pre>
|
||||
* # generate server certificate chain (valid for 10000 days)
|
||||
* keytool -genkeypair -alias signedtestserver -dname cn=moquette.eclipse.org -keyalg RSA -keysize 2048 -keystore signedserverkeystore.jks -keypass passw0rdsrv -storepass passw0rdsrv -validity 10000
|
||||
@@ -87,9 +86,11 @@ import org.slf4j.LoggerFactory;
|
||||
* keytool -importcert -trustcacerts -noprompt -alias signedtestserver_sub -keystore unsignedclientkeystore.jks -keypass passw0rd -storepass passw0rd
|
||||
* </pre>
|
||||
* </p>
|
||||
*
|
||||
* @author andrea / konradm
|
||||
*/
|
||||
public class ServerIntegrationSSLClientAuthTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationSSLClientAuthTest.class);
|
||||
|
||||
Server m_server;
|
||||
@@ -173,14 +174,14 @@ public class ServerIntegrationSSLClientAuthTest {
|
||||
// actual a "Broken pipe" is thrown, this is not very specific.
|
||||
try {
|
||||
m_client.connect(options);
|
||||
}catch(MqttException e)
|
||||
{
|
||||
} catch (MqttException e) {
|
||||
e.printStackTrace();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private SSLSocketFactory configureSSLSocketFactory(String keystore) throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
|
||||
private SSLSocketFactory configureSSLSocketFactory(String keystore) throws KeyManagementException,
|
||||
NoSuchAlgorithmException, UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
|
||||
KeyStore ks = KeyStore.getInstance("JKS");
|
||||
InputStream jksInputStream = getClass().getClassLoader().getResourceAsStream(keystore);
|
||||
ks.load(jksInputStream, "passw0rd".toCharArray());
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -27,13 +27,11 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
@@ -55,6 +53,7 @@ import org.slf4j.LoggerFactory;
|
||||
* @author andrea
|
||||
*/
|
||||
public class ServerIntegrationSSLTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationSSLTest.class);
|
||||
|
||||
Server m_server;
|
||||
@@ -146,23 +145,23 @@ public class ServerIntegrationSSLTest {
|
||||
|
||||
m_client.disconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* keystore generated into test/resources with command:
|
||||
*
|
||||
* keytool -keystore clientkeystore.jks -alias testclient -genkey -keyalg RSA
|
||||
* -> mandatory to put the name surname
|
||||
* -> password is passw0rd
|
||||
* -> type yes at the end
|
||||
* keytool -keystore clientkeystore.jks -alias testclient -genkey -keyalg RSA -> mandatory to
|
||||
* put the name surname -> password is passw0rd -> type yes at the end
|
||||
*
|
||||
* to generate the crt file from the keystore
|
||||
* -- keytool -certreq -alias testclient -keystore clientkeystore.jks -file testclient.csr
|
||||
* to generate the crt file from the keystore -- keytool -certreq -alias testclient -keystore
|
||||
* clientkeystore.jks -file testclient.csr
|
||||
*
|
||||
* keytool -export -alias testclient -keystore clientkeystore.jks -file testclient.crt
|
||||
*
|
||||
* to import an existing certificate:
|
||||
* keytool -keystore clientkeystore.jks -import -alias testclient -file testclient.crt -trustcacerts
|
||||
* to import an existing certificate: keytool -keystore clientkeystore.jks -import -alias
|
||||
* testclient -file testclient.crt -trustcacerts
|
||||
*/
|
||||
private SSLSocketFactory configureSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
|
||||
private SSLSocketFactory configureSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException,
|
||||
UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
|
||||
KeyStore ks = KeyStore.getInstance("JKS");
|
||||
InputStream jksInputStream = getClass().getClassLoader().getResourceAsStream("clientkeystore.jks");
|
||||
ks.load(jksInputStream, "passw0rd".toCharArray());
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.BrokerConstants;
|
||||
@@ -25,21 +26,19 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
|
||||
/**
|
||||
* Integration test to check the function of Moquette with a WebSocket channel.
|
||||
*
|
||||
* @author andrea
|
||||
*/
|
||||
public class ServerIntegrationWebSocketTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationWebSocketTest.class);
|
||||
|
||||
Server m_server;
|
||||
@@ -49,7 +48,8 @@ public class ServerIntegrationWebSocketTest {
|
||||
protected void startServer() throws IOException {
|
||||
m_server = new Server();
|
||||
final Properties configProps = IntegrationUtils.prepareTestProperties();
|
||||
configProps.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT));
|
||||
configProps
|
||||
.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT));
|
||||
m_config = new MemoryConfig(configProps);
|
||||
m_server.startServer(m_config);
|
||||
}
|
||||
|
||||
+14
-8
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
@@ -26,7 +27,6 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.*;
|
||||
@@ -37,6 +37,7 @@ import static org.junit.Assert.*;
|
||||
* @author andrea
|
||||
*/
|
||||
public class ServerLowlevelMessagesIntegrationTests {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServerLowlevelMessagesIntegrationTests.class);
|
||||
static MqttClientPersistence s_dataStore;
|
||||
Server m_server;
|
||||
@@ -78,10 +79,11 @@ public class ServerLowlevelMessagesIntegrationTests {
|
||||
|
||||
MqttConnectMessage connectMessage = createConnectMessage("FAKECLNT", keepAlive);
|
||||
|
||||
/*ConnectMessage connectMessage = new ConnectMessage();
|
||||
connectMessage.setProtocolVersion((byte) 3);
|
||||
connectMessage.setClientID("FAKECLNT");
|
||||
connectMessage.setKeepAlive(keepAlive);*/
|
||||
/*
|
||||
* ConnectMessage connectMessage = new ConnectMessage();
|
||||
* connectMessage.setProtocolVersion((byte) 3); connectMessage.setClientID("FAKECLNT");
|
||||
* connectMessage.setKeepAlive(keepAlive);
|
||||
*/
|
||||
m_client.sendMessage(connectMessage);
|
||||
|
||||
// wait 2 times the keepAlive
|
||||
@@ -91,9 +93,13 @@ public class ServerLowlevelMessagesIntegrationTests {
|
||||
}
|
||||
|
||||
private static MqttConnectMessage createConnectMessage(String clientID, int keepAlive) {
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0);
|
||||
MqttConnectVariableHeader mqttConnectVariableHeader =
|
||||
new MqttConnectVariableHeader(
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
|
||||
MqttMessageType.CONNECT,
|
||||
false,
|
||||
MqttQoS.AT_MOST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(
|
||||
MqttVersion.MQTT_3_1.protocolName(),
|
||||
MqttVersion.MQTT_3_1.protocolLevel(),
|
||||
false,
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.server;
|
||||
|
||||
import io.moquette.server.config.IConfig;
|
||||
@@ -23,7 +24,6 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
@@ -88,7 +88,6 @@ public class ServerRestartIntegrationTest {
|
||||
IntegrationUtils.cleanPersistenceFile(m_config);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkRestartCleanSubscriptionTree() throws Exception {
|
||||
// subscribe to /topic
|
||||
@@ -118,7 +117,6 @@ public class ServerRestartIntegrationTest {
|
||||
assertNull(m_messageCollector.waitMessage(1));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkDontPublishInactiveClientsAfterServerRestart() throws Exception {
|
||||
IMqttClient conn = subscribeAndPublish("/topic");
|
||||
@@ -166,7 +164,7 @@ public class ServerRestartIntegrationTest {
|
||||
|
||||
/**
|
||||
* Connect subscribe to topic and publish on the same topic
|
||||
* */
|
||||
*/
|
||||
private IMqttClient subscribeAndPublish(String topic) throws Exception {
|
||||
IMqttClient client = new MqttClient("tcp://localhost:1883", "SubPub");
|
||||
MessageCollector collector = new MessageCollector();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user