Copilot commented on code in PR #16428:
URL: https://github.com/apache/iotdb/pull/16428#discussion_r2355030704


##########
iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift:
##########
@@ -642,6 +642,19 @@ struct TFetchTimeseriesResp {
   6: optional list<binary> tsDataset
   7: optional bool hasMoreData
 }
+
+struct TAuditLogReq {
+  1: required string username,
+  2: required string cliHostname,
+  3: required string auditEventType,
+  4: required string operationType,
+  5: required string privilegeType,
+  6: required bool result,
+  7: required string database,
+  8: required string sqlString,

Review Comment:
   Remove trailing commas from the struct field definitions. Thrift struct 
fields should not have trailing commas after the field definitions.
   ```suggestion
     1: required string username
     2: required string cliHostname
     3: required string auditEventType
     4: required string operationType
     5: required string privilegeType
     6: required bool result
     7: required string database
     8: required string sqlString
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/audit/DNAuditLogger.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.commons.audit.AbstractAuditLogger;
+import org.apache.iotdb.commons.audit.AuditEventType;
+import org.apache.iotdb.commons.audit.AuditLogFields;
+import org.apache.iotdb.commons.audit.AuditLogOperation;
+import org.apache.iotdb.commons.audit.PrivilegeLevel;
+import org.apache.iotdb.commons.auth.entity.PrivilegeType;
+import org.apache.iotdb.commons.exception.IllegalPathException;
+import org.apache.iotdb.commons.pipe.config.constant.SystemConstant;
+import org.apache.iotdb.commons.utils.CommonDateTimeUtils;
+import org.apache.iotdb.db.auth.AuthorityChecker;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.protocol.session.IClientSession;
+import org.apache.iotdb.db.protocol.session.SessionManager;
+import org.apache.iotdb.db.queryengine.common.SessionInfo;
+import org.apache.iotdb.db.queryengine.plan.Coordinator;
+import org.apache.iotdb.db.queryengine.plan.analyze.ClusterPartitionFetcher;
+import 
org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.DataNodeDevicePathCache;
+import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult;
+import org.apache.iotdb.db.queryengine.plan.parser.StatementGenerator;
+import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner;
+import org.apache.iotdb.db.queryengine.plan.relational.metadata.Metadata;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser;
+import org.apache.iotdb.db.queryengine.plan.statement.Statement;
+import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.utils.Binary;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.validation.constraints.NotNull;
+
+import java.time.ZoneId;
+import java.util.List;
+
+import static 
org.apache.iotdb.db.pipe.receiver.protocol.legacy.loader.ILoader.SCHEMA_FETCHER;
+
+public class DNAuditLogger extends AbstractAuditLogger {
+  private static final Logger logger = 
LoggerFactory.getLogger(DNAuditLogger.class);
+
+  private static final String LOG = "log";
+  private static final String USERNAME = "username";
+  private static final String CLI_HOSTNAME = "cli_hostname";
+  private static final String RESULT = "result";
+  private static final String AUDIT_EVENT_TYPE = "audit_event_type";
+  private static final String OPERATION_TYPE = "operation_type";
+  private static final String PRIVILEGE_TYPE = "privilege_type";
+  private static final String PRIVILEGE_LEVEL = "privilege_level";
+  private static final String DATABASE = "database";
+  private static final String SQL_STRING = "sql_string";
+
+  private static final String AUDIT_LOG_DEVICE = "root.__audit.log.%s.%s";
+  private static final String AUDIT_LOGIN_LOG_DEVICE = 
"root.__audit.login.%s.%s";
+  private static final Coordinator COORDINATOR = Coordinator.getInstance();
+  private static final IoTDBConfig config = 
IoTDBDescriptor.getInstance().getConfig();
+  private static final SessionInfo sessionInfo =
+      new SessionInfo(0, AuthorityChecker.SUPER_USER, ZoneId.systemDefault());
+
+  private static final List<AuditLogOperation> auditLogOperationList =
+      config.getAuditableOperationType();
+
+  private static final PrivilegeLevel auditablePrivilegeLevel = 
config.getAuditableOperationLevel();
+
+  private static final String auditableOperationResult = 
config.getAuditableOperationResult();
+
+  private static final SessionManager SESSION_MANAGER = 
SessionManager.getInstance();
+
+  private static final DataNodeDevicePathCache DEVICE_PATH_CACHE =
+      DataNodeDevicePathCache.getInstance();
+  private static boolean tableViewisInitialized = false;
+
+  private DNAuditLogger() {
+    // Empty constructor
+  }
+
+  @NotNull
+  private static InsertRowStatement generateInsertStatement(
+      AuditLogFields auditLogFields, String log) throws IllegalPathException {
+    String username = auditLogFields.getUsername();
+    String address = auditLogFields.getCliHostname();
+    AuditEventType type = auditLogFields.getAuditType();
+    AuditLogOperation operation = auditLogFields.getOperationType();
+    PrivilegeType privilegeType = auditLogFields.getPrivilegeType();
+    PrivilegeLevel privilegeLevel = judgePrivilegeLevel(privilegeType);
+    String dataNodeId = String.valueOf(config.getDataNodeId());
+    InsertRowStatement insertStatement = new InsertRowStatement();
+    insertStatement.setDevicePath(
+        DEVICE_PATH_CACHE.getPartialPath(String.format(AUDIT_LOG_DEVICE, 
dataNodeId, username)));
+    insertStatement.setTime(CommonDateTimeUtils.currentTime());
+    insertStatement.setMeasurements(
+        new String[] {
+          USERNAME,
+          CLI_HOSTNAME,
+          AUDIT_EVENT_TYPE,
+          OPERATION_TYPE,
+          PRIVILEGE_TYPE,
+          PRIVILEGE_LEVEL,
+          RESULT,
+          DATABASE,
+          SQL_STRING,
+          LOG
+        });
+    insertStatement.setAligned(false);
+    insertStatement.setValues(
+        new Object[] {
+          new Binary(username == null ? "null" : username, 
TSFileConfig.STRING_CHARSET),
+          new Binary(address == null ? "null" : address, 
TSFileConfig.STRING_CHARSET),
+          new Binary(type == null ? "null" : type.toString(), 
TSFileConfig.STRING_CHARSET),
+          new Binary(
+              operation == null ? "null" : operation.toString(), 
TSFileConfig.STRING_CHARSET),
+          new Binary(
+              privilegeType == null ? "null" : privilegeType.toString(),
+              TSFileConfig.STRING_CHARSET),
+          new Binary(
+              privilegeLevel == null ? "null" : privilegeLevel.toString(),
+              TSFileConfig.STRING_CHARSET),
+          auditLogFields.isResult(),
+          new Binary(
+              auditLogFields.getDatabase() == null ? "null" : 
auditLogFields.getDatabase(),
+              TSFileConfig.STRING_CHARSET),
+          new Binary(
+              auditLogFields.getSqlString() == null ? "null" : 
auditLogFields.getSqlString(),
+              TSFileConfig.STRING_CHARSET),
+          new Binary(log == null ? "null" : log, TSFileConfig.STRING_CHARSET)
+        });
+    insertStatement.setDataTypes(
+        new TSDataType[] {
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.BOOLEAN,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT
+        });
+    return insertStatement;
+  }
+
+  public static void log(AuditLogFields auditLogFields, String log) throws 
IllegalPathException {
+    if (!tableViewisInitialized) {
+      Statement statement =
+          StatementGenerator.createStatement(
+              "CREATE DATABASE " + SystemConstant.AUDIT_DATABASE, 
ZoneId.systemDefault());
+      ExecutionResult result =
+          COORDINATOR.executeForTreeModel(
+              statement,
+              SESSION_MANAGER.requestQueryId(),
+              sessionInfo,
+              "",
+              ClusterPartitionFetcher.getInstance(),
+              SCHEMA_FETCHER);
+      if (result.status.getCode() == 
TSStatusCode.SUCCESS_STATUS.getStatusCode()
+          || result.status.getCode() == 
TSStatusCode.DATABASE_ALREADY_EXISTS.getStatusCode()) {
+        statement =
+            StatementGenerator.createStatement(
+                "CREATE VIEW __view_system.audit_log (\n"
+                    + "    dn_id STRING TAG,\n"
+                    + "    user_name STRING TAG,\n"
+                    + "    cli_hostname STRING FIELD,\n"
+                    + "    audit_event_type INT32 FIELD,\n"
+                    + "    operation_type INT32 FIELD,\n"
+                    + "    privilege_type INT32 FIELD,\n"
+                    + "    privilege_level INT32 FIELD,\n"
+                    + "    result BOOLEAN FIELD,\n"
+                    + "    database STRING FIELD,\n"
+                    + "    log STRING FIELD\n"
+                    + ") AS root.__audit.log",

Review Comment:
   The CREATE VIEW statement defines field types as INT32 for enum values, but 
the actual insertion uses STRING values (Binary with STRING_CHARSET). This type 
mismatch will cause runtime errors.



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/audit/CNAuditLogger.java:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.confignode.audit;
+
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
+import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
+import org.apache.iotdb.commons.audit.AbstractAuditLogger;
+import org.apache.iotdb.commons.audit.AuditLogFields;
+import org.apache.iotdb.confignode.client.async.CnToDnAsyncRequestType;
+import 
org.apache.iotdb.confignode.client.async.CnToDnInternalServiceAsyncRequestManager;
+import 
org.apache.iotdb.confignode.client.async.handlers.DataNodeAsyncRequestContext;
+import 
org.apache.iotdb.confignode.consensus.request.read.region.GetRegionIdPlan;
+import 
org.apache.iotdb.confignode.consensus.response.partition.GetRegionIdResp;
+import org.apache.iotdb.confignode.manager.ConfigManager;
+import org.apache.iotdb.confignode.manager.IManager;
+import org.apache.iotdb.consensus.exception.ConsensusException;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.mpp.rpc.thrift.TAuditLogReq;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class CNAuditLogger extends AbstractAuditLogger {
+  private static final Logger logger = 
LoggerFactory.getLogger(CNAuditLogger.class);
+  private static final IoTDBConfig config = 
IoTDBDescriptor.getInstance().getConfig();
+
+  private static final String AUDIT_LOG_DEVICE = "root.__audit.log.%s.%s";
+
+  protected final IManager configManager;
+
+  public CNAuditLogger(ConfigManager configManager) {
+    this.configManager = configManager;
+  }
+
+  public void log(AuditLogFields auditLogFields, String log) {
+    // find database "__audit"'s data_region
+    final GetRegionIdPlan plan = new 
GetRegionIdPlan(TConsensusGroupType.DataRegion);
+    plan.setDatabase("root.__audit");
+    plan.setStartTimeSlotId(new TTimePartitionSlot(0));
+    plan.setEndTimeSlotId(new TTimePartitionSlot(Long.MAX_VALUE));
+    TConsensusGroupId regionId;
+    try {
+      GetRegionIdResp resp = (GetRegionIdResp) 
configManager.getConsensusManager().read(plan);
+      List<TConsensusGroupId> dataRegionIdList = resp.getDataRegionIdList();
+      if (resp.getStatus().getCode() != 
TSStatusCode.SUCCESS_STATUS.getStatusCode()
+          || dataRegionIdList.isEmpty()) {
+        logger.error("Failed to get regionId of database root.__audit: {}", 
resp.getStatus());
+        return;
+      }
+      regionId = dataRegionIdList.get(0);
+    } catch (ConsensusException e) {
+      logger.error("Failed to get regionId of database root.__audit", e);

Review Comment:
   Replace hardcoded database name in error message with 
SystemConstant.AUDIT_DATABASE for consistency.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/audit/DNAuditLogger.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.commons.audit.AbstractAuditLogger;
+import org.apache.iotdb.commons.audit.AuditEventType;
+import org.apache.iotdb.commons.audit.AuditLogFields;
+import org.apache.iotdb.commons.audit.AuditLogOperation;
+import org.apache.iotdb.commons.audit.PrivilegeLevel;
+import org.apache.iotdb.commons.auth.entity.PrivilegeType;
+import org.apache.iotdb.commons.exception.IllegalPathException;
+import org.apache.iotdb.commons.pipe.config.constant.SystemConstant;
+import org.apache.iotdb.commons.utils.CommonDateTimeUtils;
+import org.apache.iotdb.db.auth.AuthorityChecker;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.protocol.session.IClientSession;
+import org.apache.iotdb.db.protocol.session.SessionManager;
+import org.apache.iotdb.db.queryengine.common.SessionInfo;
+import org.apache.iotdb.db.queryengine.plan.Coordinator;
+import org.apache.iotdb.db.queryengine.plan.analyze.ClusterPartitionFetcher;
+import 
org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.DataNodeDevicePathCache;
+import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult;
+import org.apache.iotdb.db.queryengine.plan.parser.StatementGenerator;
+import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner;
+import org.apache.iotdb.db.queryengine.plan.relational.metadata.Metadata;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser;
+import org.apache.iotdb.db.queryengine.plan.statement.Statement;
+import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.utils.Binary;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.validation.constraints.NotNull;
+
+import java.time.ZoneId;
+import java.util.List;
+
+import static 
org.apache.iotdb.db.pipe.receiver.protocol.legacy.loader.ILoader.SCHEMA_FETCHER;
+
+public class DNAuditLogger extends AbstractAuditLogger {
+  private static final Logger logger = 
LoggerFactory.getLogger(DNAuditLogger.class);
+
+  private static final String LOG = "log";
+  private static final String USERNAME = "username";
+  private static final String CLI_HOSTNAME = "cli_hostname";
+  private static final String RESULT = "result";
+  private static final String AUDIT_EVENT_TYPE = "audit_event_type";
+  private static final String OPERATION_TYPE = "operation_type";
+  private static final String PRIVILEGE_TYPE = "privilege_type";
+  private static final String PRIVILEGE_LEVEL = "privilege_level";
+  private static final String DATABASE = "database";
+  private static final String SQL_STRING = "sql_string";
+
+  private static final String AUDIT_LOG_DEVICE = "root.__audit.log.%s.%s";
+  private static final String AUDIT_LOGIN_LOG_DEVICE = 
"root.__audit.login.%s.%s";
+  private static final Coordinator COORDINATOR = Coordinator.getInstance();
+  private static final IoTDBConfig config = 
IoTDBDescriptor.getInstance().getConfig();
+  private static final SessionInfo sessionInfo =
+      new SessionInfo(0, AuthorityChecker.SUPER_USER, ZoneId.systemDefault());
+
+  private static final List<AuditLogOperation> auditLogOperationList =
+      config.getAuditableOperationType();
+
+  private static final PrivilegeLevel auditablePrivilegeLevel = 
config.getAuditableOperationLevel();
+
+  private static final String auditableOperationResult = 
config.getAuditableOperationResult();
+
+  private static final SessionManager SESSION_MANAGER = 
SessionManager.getInstance();
+
+  private static final DataNodeDevicePathCache DEVICE_PATH_CACHE =
+      DataNodeDevicePathCache.getInstance();
+  private static boolean tableViewisInitialized = false;
+
+  private DNAuditLogger() {
+    // Empty constructor
+  }
+
+  @NotNull
+  private static InsertRowStatement generateInsertStatement(
+      AuditLogFields auditLogFields, String log) throws IllegalPathException {
+    String username = auditLogFields.getUsername();
+    String address = auditLogFields.getCliHostname();
+    AuditEventType type = auditLogFields.getAuditType();
+    AuditLogOperation operation = auditLogFields.getOperationType();
+    PrivilegeType privilegeType = auditLogFields.getPrivilegeType();
+    PrivilegeLevel privilegeLevel = judgePrivilegeLevel(privilegeType);
+    String dataNodeId = String.valueOf(config.getDataNodeId());
+    InsertRowStatement insertStatement = new InsertRowStatement();
+    insertStatement.setDevicePath(
+        DEVICE_PATH_CACHE.getPartialPath(String.format(AUDIT_LOG_DEVICE, 
dataNodeId, username)));
+    insertStatement.setTime(CommonDateTimeUtils.currentTime());
+    insertStatement.setMeasurements(
+        new String[] {
+          USERNAME,
+          CLI_HOSTNAME,
+          AUDIT_EVENT_TYPE,
+          OPERATION_TYPE,
+          PRIVILEGE_TYPE,
+          PRIVILEGE_LEVEL,
+          RESULT,
+          DATABASE,
+          SQL_STRING,
+          LOG
+        });
+    insertStatement.setAligned(false);
+    insertStatement.setValues(
+        new Object[] {
+          new Binary(username == null ? "null" : username, 
TSFileConfig.STRING_CHARSET),
+          new Binary(address == null ? "null" : address, 
TSFileConfig.STRING_CHARSET),
+          new Binary(type == null ? "null" : type.toString(), 
TSFileConfig.STRING_CHARSET),
+          new Binary(
+              operation == null ? "null" : operation.toString(), 
TSFileConfig.STRING_CHARSET),
+          new Binary(
+              privilegeType == null ? "null" : privilegeType.toString(),
+              TSFileConfig.STRING_CHARSET),
+          new Binary(
+              privilegeLevel == null ? "null" : privilegeLevel.toString(),
+              TSFileConfig.STRING_CHARSET),
+          auditLogFields.isResult(),
+          new Binary(
+              auditLogFields.getDatabase() == null ? "null" : 
auditLogFields.getDatabase(),
+              TSFileConfig.STRING_CHARSET),
+          new Binary(
+              auditLogFields.getSqlString() == null ? "null" : 
auditLogFields.getSqlString(),
+              TSFileConfig.STRING_CHARSET),
+          new Binary(log == null ? "null" : log, TSFileConfig.STRING_CHARSET)
+        });
+    insertStatement.setDataTypes(
+        new TSDataType[] {
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.BOOLEAN,
+          TSDataType.TEXT,
+          TSDataType.TEXT,
+          TSDataType.TEXT
+        });
+    return insertStatement;
+  }
+
+  public static void log(AuditLogFields auditLogFields, String log) throws 
IllegalPathException {
+    if (!tableViewisInitialized) {
+      Statement statement =
+          StatementGenerator.createStatement(
+              "CREATE DATABASE " + SystemConstant.AUDIT_DATABASE, 
ZoneId.systemDefault());
+      ExecutionResult result =
+          COORDINATOR.executeForTreeModel(
+              statement,
+              SESSION_MANAGER.requestQueryId(),
+              sessionInfo,
+              "",
+              ClusterPartitionFetcher.getInstance(),
+              SCHEMA_FETCHER);
+      if (result.status.getCode() == 
TSStatusCode.SUCCESS_STATUS.getStatusCode()
+          || result.status.getCode() == 
TSStatusCode.DATABASE_ALREADY_EXISTS.getStatusCode()) {
+        statement =
+            StatementGenerator.createStatement(
+                "CREATE VIEW __view_system.audit_log (\n"
+                    + "    dn_id STRING TAG,\n"
+                    + "    user_name STRING TAG,\n"
+                    + "    cli_hostname STRING FIELD,\n"
+                    + "    audit_event_type INT32 FIELD,\n"
+                    + "    operation_type INT32 FIELD,\n"
+                    + "    privilege_type INT32 FIELD,\n"
+                    + "    privilege_level INT32 FIELD,\n"
+                    + "    result BOOLEAN FIELD,\n"
+                    + "    database STRING FIELD,\n"
+                    + "    log STRING FIELD\n"
+                    + ") AS root.__audit.log",
+                ZoneId.systemDefault());
+        SqlParser relationSqlParser = new SqlParser();
+        IClientSession session = SESSION_MANAGER.getCurrSession();
+        Metadata metadata = LocalExecutionPlanner.getInstance().metadata;
+        COORDINATOR.executeForTableModel(
+            statement,
+            relationSqlParser,
+            session,
+            SESSION_MANAGER.requestQueryId(),
+            SESSION_MANAGER.getSessionInfoOfTableModel(session),
+            "",
+            metadata,
+            config.getQueryTimeoutThreshold());
+        tableViewisInitialized = true;
+      } else {
+        logger.error("Failed to create database {} for audit log", 
SystemConstant.AUDIT_DATABASE);
+      }
+    }
+    String username = auditLogFields.getUsername();
+    String address = auditLogFields.getCliHostname();
+    AuditEventType type = auditLogFields.getAuditType();
+    AuditLogOperation operation = auditLogFields.getOperationType();
+    PrivilegeType privilegeType = auditLogFields.getPrivilegeType();
+    PrivilegeLevel privilegeLevel = judgePrivilegeLevel(privilegeType);
+    boolean result = auditLogFields.isResult();
+    String dataNodeId = String.valueOf(config.getDataNodeId());
+
+    // to do: check whether this event should be logged.
+    // if whitelist or blacklist is used, only ip on the whitelist or 
blacklist can be logged

Review Comment:
   Remove or implement the TODO comment. Leaving unimplemented TODO comments in 
production code can be confusing and suggests incomplete functionality.
   ```suggestion
       // Check whether this event should be logged based on 
whitelist/blacklist configuration.
       // If whitelist or blacklist is used, only IPs on the whitelist or 
blacklist can be logged.
       List<String> whitelist = config.getAuditLogWhitelist();
       List<String> blacklist = config.getAuditLogBlacklist();
       boolean whitelistEnabled = config.isAuditLogWhitelistEnabled();
       boolean blacklistEnabled = config.isAuditLogBlacklistEnabled();
       if (whitelistEnabled && (whitelist == null || 
!whitelist.contains(address))) {
         return;
       }
       if (blacklistEnabled && blacklist != null && 
blacklist.contains(address)) {
         return;
       }
   ```



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/audit/CNAuditLogger.java:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.confignode.audit;
+
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
+import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
+import org.apache.iotdb.commons.audit.AbstractAuditLogger;
+import org.apache.iotdb.commons.audit.AuditLogFields;
+import org.apache.iotdb.confignode.client.async.CnToDnAsyncRequestType;
+import 
org.apache.iotdb.confignode.client.async.CnToDnInternalServiceAsyncRequestManager;
+import 
org.apache.iotdb.confignode.client.async.handlers.DataNodeAsyncRequestContext;
+import 
org.apache.iotdb.confignode.consensus.request.read.region.GetRegionIdPlan;
+import 
org.apache.iotdb.confignode.consensus.response.partition.GetRegionIdResp;
+import org.apache.iotdb.confignode.manager.ConfigManager;
+import org.apache.iotdb.confignode.manager.IManager;
+import org.apache.iotdb.consensus.exception.ConsensusException;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.mpp.rpc.thrift.TAuditLogReq;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class CNAuditLogger extends AbstractAuditLogger {
+  private static final Logger logger = 
LoggerFactory.getLogger(CNAuditLogger.class);
+  private static final IoTDBConfig config = 
IoTDBDescriptor.getInstance().getConfig();
+
+  private static final String AUDIT_LOG_DEVICE = "root.__audit.log.%s.%s";
+
+  protected final IManager configManager;
+
+  public CNAuditLogger(ConfigManager configManager) {
+    this.configManager = configManager;
+  }
+
+  public void log(AuditLogFields auditLogFields, String log) {
+    // find database "__audit"'s data_region
+    final GetRegionIdPlan plan = new 
GetRegionIdPlan(TConsensusGroupType.DataRegion);
+    plan.setDatabase("root.__audit");

Review Comment:
   Replace hardcoded database name with the constant 
SystemConstant.AUDIT_DATABASE for consistency and maintainability.



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/audit/CNAuditLogger.java:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.confignode.audit;
+
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
+import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
+import org.apache.iotdb.commons.audit.AbstractAuditLogger;
+import org.apache.iotdb.commons.audit.AuditLogFields;
+import org.apache.iotdb.confignode.client.async.CnToDnAsyncRequestType;
+import 
org.apache.iotdb.confignode.client.async.CnToDnInternalServiceAsyncRequestManager;
+import 
org.apache.iotdb.confignode.client.async.handlers.DataNodeAsyncRequestContext;
+import 
org.apache.iotdb.confignode.consensus.request.read.region.GetRegionIdPlan;
+import 
org.apache.iotdb.confignode.consensus.response.partition.GetRegionIdResp;
+import org.apache.iotdb.confignode.manager.ConfigManager;
+import org.apache.iotdb.confignode.manager.IManager;
+import org.apache.iotdb.consensus.exception.ConsensusException;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.mpp.rpc.thrift.TAuditLogReq;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class CNAuditLogger extends AbstractAuditLogger {
+  private static final Logger logger = 
LoggerFactory.getLogger(CNAuditLogger.class);
+  private static final IoTDBConfig config = 
IoTDBDescriptor.getInstance().getConfig();
+
+  private static final String AUDIT_LOG_DEVICE = "root.__audit.log.%s.%s";
+
+  protected final IManager configManager;
+
+  public CNAuditLogger(ConfigManager configManager) {
+    this.configManager = configManager;
+  }
+
+  public void log(AuditLogFields auditLogFields, String log) {
+    // find database "__audit"'s data_region
+    final GetRegionIdPlan plan = new 
GetRegionIdPlan(TConsensusGroupType.DataRegion);
+    plan.setDatabase("root.__audit");
+    plan.setStartTimeSlotId(new TTimePartitionSlot(0));
+    plan.setEndTimeSlotId(new TTimePartitionSlot(Long.MAX_VALUE));
+    TConsensusGroupId regionId;
+    try {
+      GetRegionIdResp resp = (GetRegionIdResp) 
configManager.getConsensusManager().read(plan);
+      List<TConsensusGroupId> dataRegionIdList = resp.getDataRegionIdList();
+      if (resp.getStatus().getCode() != 
TSStatusCode.SUCCESS_STATUS.getStatusCode()
+          || dataRegionIdList.isEmpty()) {
+        logger.error("Failed to get regionId of database root.__audit: {}", 
resp.getStatus());

Review Comment:
   Replace hardcoded database name in error message with 
SystemConstant.AUDIT_DATABASE for consistency.



-- 
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