You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by ju...@apache.org on 2025/08/22 12:25:45 UTC
(iotdb) branch master updated: Pipe: fix MQTT Source Session logic & Enhanced error reporting for MQTT port and data path conflicts (#16229)
This is an automated email from the ASF dual-hosted git repository.
justinchen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 63284330d28 Pipe: fix MQTT Source Session logic & Enhanced error reporting for MQTT port and data path conflicts (#16229)
63284330d28 is described below
commit 63284330d2838aadd20b75f18833ccd968065a50
Author: nanxiang xia <16...@users.noreply.github.com>
AuthorDate: Fri Aug 22 20:25:39 2025 +0800
Pipe: fix MQTT Source Session logic & Enhanced error reporting for MQTT port and data path conflicts (#16229)
* fix
* change check logic
* update
* fix
* update file check
* update file check
* update
* better format
* update format
* fix dependency
---
.../db/pipe/source/mqtt/MQTTPublishHandler.java | 21 ++---
.../iotdb/db/pipe/source/mqtt/MQTTSource.java | 102 +++++++++++++++++++--
.../pipe/config/constant/PipeSourceConstant.java | 3 +-
3 files changed, 104 insertions(+), 22 deletions(-)
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTPublishHandler.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTPublishHandler.java
index f103cc4c705..9e42ede3194 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTPublishHandler.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTPublishHandler.java
@@ -23,13 +23,11 @@ import org.apache.iotdb.commons.conf.IoTDBConstant.ClientVersion;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.pipe.agent.task.connection.UnboundedBlockingPendingQueue;
import org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta;
-import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant;
import org.apache.iotdb.commons.pipe.config.plugin.env.PipeTaskExtractorRuntimeEnvironment;
import org.apache.iotdb.commons.pipe.event.EnrichedEvent;
import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
import org.apache.iotdb.db.pipe.event.common.statement.PipeStatementInsertionEvent;
import org.apache.iotdb.db.protocol.mqtt.Message;
-import org.apache.iotdb.db.protocol.mqtt.PayloadFormatManager;
import org.apache.iotdb.db.protocol.mqtt.PayloadFormatter;
import org.apache.iotdb.db.protocol.mqtt.TableMessage;
import org.apache.iotdb.db.protocol.mqtt.TreeMessage;
@@ -42,7 +40,6 @@ import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement;
import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertTabletStatement;
import org.apache.iotdb.db.utils.CommonUtils;
import org.apache.iotdb.db.utils.TimestampPrecisionUtils;
-import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters;
import org.apache.iotdb.service.rpc.thrift.TSProtocolVersion;
import io.moquette.interception.AbstractInterceptHandler;
@@ -79,14 +76,10 @@ public class MQTTPublishHandler extends AbstractInterceptHandler {
private final PipeTaskMeta pipeTaskMeta;
public MQTTPublishHandler(
- final PipeParameters pipeParameters,
+ final PayloadFormatter payloadFormat,
final PipeTaskExtractorRuntimeEnvironment environment,
final UnboundedBlockingPendingQueue<EnrichedEvent> pendingQueue) {
- this.payloadFormat =
- PayloadFormatManager.getPayloadFormat(
- pipeParameters.getStringOrDefault(
- PipeSourceConstant.MQTT_PAYLOAD_FORMATTER_KEY,
- PipeSourceConstant.MQTT_PAYLOAD_FORMATTER_DEFAULT_VALUE));
+ this.payloadFormat = payloadFormat;
useTableInsert = PayloadFormatter.TABLE_TYPE.equals(this.payloadFormat.getType());
pipeName = environment.getPipeName();
creationTime = environment.getCreationTime();
@@ -101,6 +94,10 @@ public class MQTTPublishHandler extends AbstractInterceptHandler {
@Override
public void onConnect(InterceptConnectMessage msg) {
+ if (msg.getClientID() == null || msg.getClientID().trim().isEmpty()) {
+ LOGGER.error(
+ "Connection refused: client_id is missing or empty. A valid client_id is required to establish a connection.");
+ }
if (!clientIdToSessionMap.containsKey(msg.getClientID())) {
final MqttClientSession session = new MqttClientSession(msg.getClientID());
sessionManager.login(
@@ -111,7 +108,7 @@ public class MQTTPublishHandler extends AbstractInterceptHandler {
TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V3,
ClientVersion.V_1_0,
useTableInsert ? IClientSession.SqlDialect.TABLE : IClientSession.SqlDialect.TREE);
- sessionManager.registerSession(session);
+ sessionManager.registerSessionForMqtt(session);
clientIdToSessionMap.put(msg.getClientID(), session);
}
}
@@ -120,7 +117,7 @@ public class MQTTPublishHandler extends AbstractInterceptHandler {
public void onDisconnect(InterceptDisconnectMessage msg) {
final MqttClientSession session = clientIdToSessionMap.remove(msg.getClientID());
if (null != session) {
- sessionManager.removeCurrSession();
+ sessionManager.removeCurrSessionForMqtt(session);
sessionManager.closeSession(session, Coordinator.getInstance()::cleanupQueryExecution);
}
}
@@ -186,7 +183,7 @@ public class MQTTPublishHandler extends AbstractInterceptHandler {
session.getUsername(),
true,
true,
- message.getDatabase(),
+ message.getDatabase().toLowerCase(),
insertTabletStatement);
if (!event.increaseReferenceCount(MQTTPublishHandler.class.getName())) {
LOGGER.warn("The reference count of the event {} cannot be increased, skipping it.", event);
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTSource.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTSource.java
index f8d32dda83b..a754fc536af 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTSource.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/mqtt/MQTTSource.java
@@ -22,10 +22,13 @@ package org.apache.iotdb.db.pipe.source.mqtt;
import org.apache.iotdb.commons.pipe.agent.task.connection.UnboundedBlockingPendingQueue;
import org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta;
import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant;
+import org.apache.iotdb.commons.pipe.config.constant.SystemConstant;
import org.apache.iotdb.commons.pipe.config.plugin.env.PipeTaskExtractorRuntimeEnvironment;
import org.apache.iotdb.commons.pipe.event.EnrichedEvent;
import org.apache.iotdb.db.pipe.metric.source.PipeDataRegionEventCounter;
import org.apache.iotdb.db.protocol.mqtt.BrokerAuthenticator;
+import org.apache.iotdb.db.protocol.mqtt.PayloadFormatManager;
+import org.apache.iotdb.db.protocol.mqtt.PayloadFormatter;
import org.apache.iotdb.pipe.api.PipeExtractor;
import org.apache.iotdb.pipe.api.annotation.TableModel;
import org.apache.iotdb.pipe.api.annotation.TreeModel;
@@ -33,6 +36,7 @@ import org.apache.iotdb.pipe.api.customizer.configuration.PipeExtractorRuntimeCo
import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameterValidator;
import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters;
import org.apache.iotdb.pipe.api.event.Event;
+import org.apache.iotdb.pipe.api.exception.PipeException;
import org.apache.iotdb.pipe.api.exception.PipeParameterNotValidException;
import io.moquette.BrokerConstants;
@@ -44,7 +48,14 @@ import io.moquette.interception.InterceptHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.File;
import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -68,12 +79,14 @@ public class MQTTSource implements PipeExtractor {
protected final UnboundedBlockingPendingQueue<EnrichedEvent> pendingQueue =
new UnboundedBlockingPendingQueue<>(new PipeDataRegionEventCounter());
- protected IConfig config;
+ protected PayloadFormatter payloadFormat;
+ protected IConfig brokerConfig;
protected List<InterceptHandler> handlers;
protected IAuthenticator authenticator;
private final Server server = new Server();
protected final AtomicBoolean isClosed = new AtomicBoolean(false);
+ private final AtomicBoolean hasBeenStarted = new AtomicBoolean(false);
@Override
public void validate(final PipeParameterValidator validator) throws Exception {
@@ -86,6 +99,66 @@ public class MQTTSource implements PipeExtractor {
PipeSourceConstant.EXTERNAL_EXTRACTOR_SINGLE_INSTANCE_PER_NODE_DEFAULT_VALUE)) {
throw new PipeParameterNotValidException("single mode should be true in MQTT extractor");
}
+
+ validateMoquetteConfig(validator.getParameters());
+ }
+
+ public void validateMoquetteConfig(final PipeParameters parameters) {
+ final String sqlDialect =
+ parameters.getStringOrDefault(
+ SystemConstant.SQL_DIALECT_KEY, SystemConstant.SQL_DIALECT_TREE_VALUE);
+ final String formatType =
+ parameters.getStringOrDefault(
+ PipeSourceConstant.MQTT_PAYLOAD_FORMATTER_KEY,
+ SystemConstant.SQL_DIALECT_TREE_VALUE.equals(sqlDialect)
+ ? PipeSourceConstant.MQTT_PAYLOAD_FORMATTER_TREE_DIALECT_VALUE
+ : PipeSourceConstant.MQTT_PAYLOAD_FORMATTER_TABLE_DIALECT_VALUE);
+ try {
+ payloadFormat = PayloadFormatManager.getPayloadFormat(formatType);
+ } catch (IllegalArgumentException e) {
+ throw new PipeParameterNotValidException("Invalid payload format type: " + formatType);
+ }
+
+ final String ip =
+ parameters.getStringOrDefault(
+ PipeSourceConstant.MQTT_BROKER_HOST_KEY,
+ PipeSourceConstant.MQTT_BROKER_HOST_DEFAULT_VALUE);
+ final int port =
+ Integer.parseInt(
+ parameters.getStringOrDefault(
+ PipeSourceConstant.MQTT_BROKER_PORT_KEY,
+ PipeSourceConstant.MQTT_BROKER_PORT_DEFAULT_VALUE));
+ try (ServerSocket socket = new ServerSocket()) {
+ socket.bind(new InetSocketAddress(ip, port));
+ } catch (IOException e) {
+ throw new PipeParameterNotValidException(
+ "Cannot bind MQTT broker to "
+ + ip
+ + ":"
+ + port
+ + ". The port might already be in use, or the IP address is invalid.");
+ }
+
+ final String dataPath =
+ parameters.getStringOrDefault(
+ PipeSourceConstant.MQTT_DATA_PATH_PROPERTY_NAME_KEY,
+ PipeSourceConstant.MQTT_DATA_PATH_PROPERTY_NAME_DEFAULT_VALUE);
+ final File file = Paths.get(dataPath).resolve("moquette_store.h2").toAbsolutePath().toFile();
+ if (file.exists()) {
+ try (RandomAccessFile raf = new RandomAccessFile(file, "rw");
+ FileChannel channel = raf.getChannel();
+ FileLock lock = channel.tryLock()) {
+ if (lock == null) {
+ throw new PipeParameterNotValidException(
+ " The data file is used by another MQTT Source or MQTT Service. "
+ + "Please use another data path");
+ }
+ } catch (Exception e) {
+ throw new PipeParameterNotValidException(
+ " The data file is used by another MQTT Source or MQTT Service. "
+ + "Please use another data path");
+ }
+ }
}
@Override
@@ -97,9 +170,9 @@ public class MQTTSource implements PipeExtractor {
pipeName = environment.getPipeName();
creationTime = environment.getCreationTime();
pipeTaskMeta = environment.getPipeTaskMeta();
- config = createBrokerConfig(parameters);
+ brokerConfig = createBrokerConfig(parameters);
handlers = new ArrayList<>(1);
- handlers.add(new MQTTPublishHandler(parameters, environment, pendingQueue));
+ handlers.add(new MQTTPublishHandler(payloadFormat, environment, pendingQueue));
authenticator = new BrokerAuthenticator();
}
@@ -153,16 +226,27 @@ public class MQTTSource implements PipeExtractor {
@Override
public void start() throws Exception {
+ if (hasBeenStarted.get()) {
+ return;
+ }
+ hasBeenStarted.set(true);
+
try {
- server.startServer(config, handlers, null, authenticator, null);
- } catch (IOException e) {
- throw new RuntimeException("Exception while starting server", e);
+ server.startServer(brokerConfig, handlers, null, authenticator, null);
+ } catch (Exception e) {
+ throw new PipeException(
+ "Failed to start MQTT Extractor "
+ + pipeName
+ + ". Possible reasons: the data file might be used by another MQTT Source or MQTT Service, "
+ + "the port might already be in use, or there could be other issues. "
+ + "Please check the logs for more details.",
+ e);
}
LOGGER.info(
"Start MQTT Extractor successfully, listening on ip {}, port {}",
- config.getProperty(BrokerConstants.HOST_PROPERTY_NAME),
- config.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
+ brokerConfig.getProperty(BrokerConstants.HOST_PROPERTY_NAME),
+ brokerConfig.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
}
@Override
@@ -172,7 +256,7 @@ public class MQTTSource implements PipeExtractor {
@Override
public void close() throws Exception {
- if (!isClosed.get()) {
+ if (!isClosed.get() && hasBeenStarted.get()) {
server.stopServer();
isClosed.set(true);
}
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java
index 43ba83bb113..3887599ac54 100644
--- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java
+++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java
@@ -195,7 +195,8 @@ public class PipeSourceConstant {
public static final long MQTT_NETTY_MAX_BYTES_PROPERTY_NAME_DEFAULT_VALUE = 1048576;
public static final String MQTT_PAYLOAD_FORMATTER_KEY = "mqtt.payload-formatter";
- public static final String MQTT_PAYLOAD_FORMATTER_DEFAULT_VALUE = "json";
+ public static final String MQTT_PAYLOAD_FORMATTER_TREE_DIALECT_VALUE = "json";
+ public static final String MQTT_PAYLOAD_FORMATTER_TABLE_DIALECT_VALUE = "line";
///////////////////// pipe consensus /////////////////////