HTHou commented on code in PR #18569:
URL: https://github.com/apache/iotdb/pull/18569#discussion_r3913491132


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/audit/DataNodeUserDataTransferAuditor.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.audit;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.audit.UserDataTransferAuditEvent;
+import org.apache.iotdb.commons.audit.UserDataTransferProtectionMethod;
+import org.apache.iotdb.commons.conf.CommonConfig;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.consensus.DataRegionId;
+import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNode;
+import 
org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType;
+import org.apache.iotdb.commons.request.IConsensusRequest;
+import org.apache.iotdb.commons.schema.table.Audit;
+import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IoTConsensusRequest;
+import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertNode;
+import org.apache.iotdb.db.storageengine.StorageEngine;
+import org.apache.iotdb.db.storageengine.dataregion.DataRegion;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.WALEntry;
+
+import javax.annotation.Nullable;
+
+public final class DataNodeUserDataTransferAuditor {
+
+  private static final CommonConfig COMMON_CONFIG = 
CommonDescriptor.getInstance().getConfig();
+
+  private DataNodeUserDataTransferAuditor() {}
+
+  public static boolean isEnabled() {
+    return COMMON_CONFIG.isEnableAuditLog();
+  }
+
+  public static void record(
+      TEndPoint initiator,
+      TEndPoint source,
+      TEndPoint target,
+      boolean success,
+      @Nullable String errorCode,
+      @Nullable Throwable error) {
+    try {
+      if (!isEnabled()) {
+        return;
+      }
+      DNAuditLogger.getInstance()
+          .recordUserDataTransferAuditLog(
+              new UserDataTransferAuditEvent(
+                  initiator,
+                  source,
+                  target,
+                  UserDataTransferProtectionMethod.fromTlsEnabled(
+                      COMMON_CONFIG.isEnableInternalSSL()),
+                  success,
+                  errorCode != null
+                      ? errorCode
+                      : error == null ? null : error.getClass().getName()));
+    } catch (RuntimeException ignored) {
+      // Audit recording must not affect user data transfer.
+    }
+  }
+
+  public static boolean containsUserData(
+      ConsensusGroupId consensusGroupId, IConsensusRequest request) {
+    if (!(consensusGroupId instanceof DataRegionId)) {
+      return false;
+    }
+    final DataRegion dataRegion =
+        StorageEngine.getInstance().getDataRegion((DataRegionId) 
consensusGroupId);
+    return dataRegion != null && 
containsUserData(dataRegion.getDatabaseName(), request);
+  }
+
+  public static boolean containsUserData(ConsensusGroupId consensusGroupId) {
+    if (!(consensusGroupId instanceof DataRegionId)) {
+      return false;
+    }
+    final DataRegion dataRegion =
+        StorageEngine.getInstance().getDataRegion((DataRegionId) 
consensusGroupId);
+    return dataRegion != null && 
containsUserData(dataRegion.getDatabaseName());
+  }
+
+  static boolean containsUserData(String database) {
+    return !Audit.isAuditDatabase(database);
+  }
+
+  static boolean containsUserData(String database, IConsensusRequest request) {
+    if (!containsUserData(database)) {
+      return false;
+    }
+    try {
+      final PlanNode planNode;
+      if (request instanceof PlanNode) {
+        planNode = (PlanNode) request;
+      } else if (request instanceof IoTConsensusRequest) {
+        planNode = 
WALEntry.deserializeForConsensus(request.serializeToByteBuffer().duplicate());
+      } else if (request instanceof ByteBufferConsensusRequest) {
+        planNode = 
PlanNodeType.deserialize(request.serializeToByteBuffer().duplicate());

Review Comment:
   Addressed in 9e6cbee1b3. The live sender path classifies a `PlanNode` once 
and stores the bit on `IndexedConsensusRequest`. During WAL reconstruction, the 
bit is now restored directly from `WALEntryType`, then combined with the 
consensus-group classifier to preserve the audit-database exclusion. The remote 
receiver no longer classifies the serialized request because auditing is 
sender-side. This removes the 
`IoTConsensusRequest`/`ByteBufferConsensusRequest` serialization and 
deserialization branches, without adding a wire-format field. A test also 
verifies that a generic `IConsensusRequest` is not serialized solely for audit 
classification.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/sink/protocol/iotconsensusv2/handler/IoTConsensusV2TabletBatchEventHandler.java:
##########
@@ -84,6 +85,16 @@ public void onComplete(final 
TIoTConsensusV2BatchTransferResp response) {
           response.getBatchResps().stream()
               .map(TIoTConsensusV2TransferResp::getStatus)
               .collect(Collectors.toList());
+      final TSStatus failedStatus =
+          status.stream()
+              .filter(tsStatus -> tsStatus.getCode() != 
TSStatusCode.SUCCESS_STATUS.getStatusCode())
+              .findFirst()
+              .orElse(null);
+      connector.recordUserDataTransferAudit(
+          failedStatus == null,
+          failedStatus == null ? null : String.valueOf(failedStatus.getCode()),
+          null);
+      transferAuditRecorded = true;

Review Comment:
   I kept one representative error intentionally and clarified it in 
9e6cbee1b3. The batch RPC is one physical transfer attempt, so it produces one 
audit event. The event result is failure if any sub-response fails, and the 
first failed status code fills the minimum schema single error value. 
Concatenating every sub-status would make the audit payload grow with batch 
size; detailed per-item failures are still processed by the existing status 
handler.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/audit/DataNodeUserDataTransferAuditor.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.audit;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.audit.UserDataTransferAuditEvent;
+import org.apache.iotdb.commons.audit.UserDataTransferProtectionMethod;
+import org.apache.iotdb.commons.conf.CommonConfig;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.consensus.DataRegionId;
+import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNode;
+import 
org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType;
+import org.apache.iotdb.commons.request.IConsensusRequest;
+import org.apache.iotdb.commons.schema.table.Audit;
+import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IoTConsensusRequest;
+import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertNode;
+import org.apache.iotdb.db.storageengine.StorageEngine;
+import org.apache.iotdb.db.storageengine.dataregion.DataRegion;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.WALEntry;
+
+import javax.annotation.Nullable;
+
+public final class DataNodeUserDataTransferAuditor {
+
+  private static final CommonConfig COMMON_CONFIG = 
CommonDescriptor.getInstance().getConfig();
+
+  private DataNodeUserDataTransferAuditor() {}
+
+  public static boolean isEnabled() {
+    return COMMON_CONFIG.isEnableAuditLog();
+  }
+
+  public static void record(
+      TEndPoint initiator,
+      TEndPoint source,
+      TEndPoint target,
+      boolean success,
+      @Nullable String errorCode,
+      @Nullable Throwable error) {
+    try {
+      if (!isEnabled()) {
+        return;
+      }
+      DNAuditLogger.getInstance()
+          .recordUserDataTransferAuditLog(
+              new UserDataTransferAuditEvent(
+                  initiator,
+                  source,
+                  target,
+                  UserDataTransferProtectionMethod.fromTlsEnabled(
+                      COMMON_CONFIG.isEnableInternalSSL()),
+                  success,
+                  errorCode != null
+                      ? errorCode
+                      : error == null ? null : error.getClass().getName()));
+    } catch (RuntimeException ignored) {
+      // Audit recording must not affect user data transfer.
+    }
+  }
+
+  public static boolean containsUserData(
+      ConsensusGroupId consensusGroupId, IConsensusRequest request) {
+    if (!(consensusGroupId instanceof DataRegionId)) {
+      return false;
+    }
+    final DataRegion dataRegion =
+        StorageEngine.getInstance().getDataRegion((DataRegionId) 
consensusGroupId);
+    return dataRegion != null && 
containsUserData(dataRegion.getDatabaseName(), request);
+  }
+
+  public static boolean containsUserData(ConsensusGroupId consensusGroupId) {
+    if (!(consensusGroupId instanceof DataRegionId)) {
+      return false;
+    }
+    final DataRegion dataRegion =
+        StorageEngine.getInstance().getDataRegion((DataRegionId) 
consensusGroupId);
+    return dataRegion != null && 
containsUserData(dataRegion.getDatabaseName());
+  }

Review Comment:
   Agreed that schema and attribute data are user data. In IoTDB, SchemaRegion 
supports Ratis (and SimpleConsensus when the replication factor is 1); 
IoTConsensus and IoTConsensusV2 are rejected for SchemaRegion, and this PR 
wires the IoTConsensus classifier only into `DataRegionConsensusImpl`. The 
Ratis-side transfer audit hook needs to be implemented inside Ratis and will be 
handled under [RATIS-2681](https://issues.apache.org/jira/browse/RATIS-2681), 
so this PR intentionally does not add a non-functional SchemaRegion classifier 
branch.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/sink/protocol/iotconsensusv2/handler/IoTConsensusV2TabletBatchEventHandler.java:
##########
@@ -118,6 +129,10 @@ public void onComplete(final 
TIoTConsensusV2BatchTransferResp response) {
 
   @Override
   public void onError(final Exception exception) {
+    if (!transferAuditRecorded) {
+      connector.recordUserDataTransferAudit(false, null, exception);
+      transferAuditRecorded = true;
+    }

Review Comment:
   Clarified in 9e6cbee1b3. `onError` receives one exception for that physical 
RPC attempt. A retry is sent with a new handler and therefore emits a new audit 
event. `transferAuditRecorded` only prevents double-recording when `onComplete` 
has already recorded the response and later response-processing code throws 
into `onError`.



##########
iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/client/DispatchLogHandler.java:
##########
@@ -172,4 +186,47 @@ private void completeBatch(Batch batch) {
     // removeBatch
     thread.updateSafelyDeletedSearchIndex();
   }
+
+  private void recordTransferAttempt(boolean success, String errorCode, 
Throwable error) {
+    try {
+      recordTransferAttempt(
+          thread.getImpl().getUserDataTransferAuditHandler(),
+          batch,
+          thread.getImpl().getThisNode().getEndpoint(),
+          thread.getPeer().getEndpoint(),
+          UserDataTransferProtectionMethod.fromTlsEnabled(
+              thread.getConfig().getRpc().isEnableSSL()),
+          success,
+          errorCode,
+          error);
+    } catch (RuntimeException ignored) {
+      // Audit recording must not affect consensus replication.
+    }
+  }
+
+  static void recordTransferAttempt(
+      UserDataTransferAuditHandler auditHandler,
+      Batch batch,
+      TEndPoint source,
+      TEndPoint target,
+      UserDataTransferProtectionMethod protectionMethod,
+      boolean success,
+      String errorCode,
+      Throwable error) {
+    try {
+      if (!batch.containsUserData() || !auditHandler.isEnabled()) {
+        return;
+      }
+      auditHandler.onAttempt(
+          new UserDataTransferAuditEvent(
+              source,
+              source,
+              target,
+              protectionMethod,
+              success,
+              errorCode != null ? errorCode : error == null ? null : 
error.getClass().getName()));
+    } catch (RuntimeException ignored) {
+      // Audit recording must not affect consensus replication.
+    }

Review Comment:
   Addressed in 9e6cbee1b3. Audit callback/classification `RuntimeException`s 
remain isolated from consensus replication, but now emit a WARN with the stack 
trace for diagnosis. The new operator-facing message is localized in both en/zh.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to