github-actions[bot] commented on code in PR #61325: URL: https://github.com/apache/doris/pull/61325#discussion_r3047808807
########## be/src/load/routine_load/kinesis_conf.cpp: ########## @@ -0,0 +1,169 @@ +// 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. + +#include "load/routine_load/kinesis_conf.h" + +#include <glog/logging.h> + +namespace doris { + +KinesisConf::ConfResult KinesisConf::set(const std::string& name, const std::string& value, + std::string& errstr) { + // Determine which API(s) this parameter belongs to based on its semantic meaning + // All parameters come in as simple names (e.g., "max_records", "stream_arn") + // after "aws.kinesis." prefix is removed in data_consumer.cpp + + if (name == "max_records") { + // GetRecords API parameter + int max_records; + if (!parse_int(value, max_records, errstr)) { + return CONF_INVALID; + } + if (max_records < 1 || max_records > 10000) { + errstr = "max_records must be between 1 and 10000"; + return CONF_INVALID; + } + _get_records_params[name] = value; + return CONF_OK; + } else if (name == "stream_arn") { + // Used by all three APIs + _get_records_params[name] = value; + _get_shard_iterator_params[name] = value; + _list_shards_params[name] = value; + return CONF_OK; + } else if (name == "timestamp") { + // GetShardIterator API parameter (for AT_TIMESTAMP iterator type) + long timestamp; + if (!parse_long(value, timestamp, errstr)) { + return CONF_INVALID; + } + _get_shard_iterator_params[name] = value; + return CONF_OK; + } else if (name == "max_results") { + // ListShards API parameter + int max_results; + if (!parse_int(value, max_results, errstr)) { + return CONF_INVALID; + } + if (max_results < 1 || max_results > 10000) { + errstr = "max_results must be between 1 and 10000"; + return CONF_INVALID; + } + _list_shards_params[name] = value; + return CONF_OK; + } + + VLOG_NOTICE << "Unknown Kinesis configuration: " << name; + return CONF_UNKNOWN; +} + +Status KinesisConf::apply_to_get_records_request(Aws::Kinesis::Model::GetRecordsRequest& request, + const std::string& shard_iterator) const { + request.SetShardIterator(shard_iterator); + + auto it = _get_records_params.find("max_records"); + if (it != _get_records_params.end()) { + try { + request.SetLimit(std::stoi(it->second)); + } catch (const std::exception&) { + return Status::InternalError("Failed to apply get_records.max_records: {}", it->second); + } + } + + it = _get_records_params.find("stream_arn"); + if (it != _get_records_params.end() && !it->second.empty()) { + request.SetStreamARN(it->second); + } + + return Status::OK(); +} + +Status KinesisConf::apply_to_get_shard_iterator_request( + Aws::Kinesis::Model::GetShardIteratorRequest& request, const std::string& stream_name, + const std::string& shard_id, const std::string& sequence_number) const { + request.SetStreamName(stream_name); + request.SetShardId(shard_id); + + if (sequence_number.empty() || sequence_number == "TRIM_HORIZON" || sequence_number == "-2") { + request.SetShardIteratorType(Aws::Kinesis::Model::ShardIteratorType::TRIM_HORIZON); + } else if (sequence_number == "LATEST" || sequence_number == "-1") { + request.SetShardIteratorType(Aws::Kinesis::Model::ShardIteratorType::LATEST); + } else { + request.SetShardIteratorType(Aws::Kinesis::Model::ShardIteratorType::AFTER_SEQUENCE_NUMBER); Review Comment: High: explicit sequence-number starts become exclusive here. FE forwards a configured shard position verbatim, but BE always maps any concrete sequence number to `AFTER_SEQUENCE_NUMBER`, so `kinesis_shards_pos = "12345"` starts after record `12345` instead of at it. That drops the first requested record unless the contract is made explicitly exclusive end-to-end. ########## fe/fe-core/src/main/java/org/apache/doris/load/routineload/KinesisRoutineLoadJob.java: ########## @@ -0,0 +1,866 @@ +// 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.doris.load.routineload; + +import org.apache.doris.analysis.ExprToSqlVisitor; +import org.apache.doris.analysis.ImportColumnDesc; +import org.apache.doris.analysis.ToSqlParams; +import org.apache.doris.analysis.UserIdentity; +import org.apache.doris.catalog.Database; +import org.apache.doris.catalog.Env; +import org.apache.doris.catalog.OlapTable; +import org.apache.doris.catalog.RandomDistributionInfo; +import org.apache.doris.common.Config; +import org.apache.doris.common.DdlException; +import org.apache.doris.common.InternalErrorCode; +import org.apache.doris.common.LoadException; +import org.apache.doris.common.Pair; +import org.apache.doris.common.UserException; +import org.apache.doris.common.util.DebugUtil; +import org.apache.doris.common.util.LogBuilder; +import org.apache.doris.common.util.LogKey; +import org.apache.doris.datasource.kinesis.KinesisUtil; +import org.apache.doris.load.routineload.kinesis.KinesisDataSourceProperties; +import org.apache.doris.nereids.load.NereidsImportColumnDesc; +import org.apache.doris.nereids.load.NereidsLoadTaskInfo; +import org.apache.doris.nereids.load.NereidsLoadUtils; +import org.apache.doris.nereids.load.NereidsRoutineLoadTaskInfo; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.plans.commands.AlterRoutineLoadCommand; +import org.apache.doris.nereids.trees.plans.commands.info.CreateRoutineLoadInfo; +import org.apache.doris.persist.AlterRoutineLoadJobOperationLog; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.thrift.TFileCompressType; +import org.apache.doris.thrift.TPartialUpdateNewRowPolicy; +import org.apache.doris.transaction.TransactionState; +import org.apache.doris.transaction.TransactionStatus; + +import com.google.common.base.Joiner; +import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * KinesisRoutineLoadJob is a RoutineLoadJob that fetches data from AWS Kinesis streams. + * + * Key concepts: + * - Stream: Named collection of data records (similar to Kafka topic) + * - Shard: Sequence of data records in a stream (similar to Kafka partition) + * - Sequence Number: Unique identifier for each record within a shard (similar to Kafka offset) + * - Consumer: Application that reads from a stream + * + * The progress tracks sequence numbers for each shard, represented as: + * {"shardId-000000000000": "49590338271490256608559692538361571095921575989136588802", ...} + */ +public class KinesisRoutineLoadJob extends RoutineLoadJob { + private static final Logger LOG = LogManager.getLogger(KinesisRoutineLoadJob.class); + + public static final String KINESIS_FILE_CATALOG = "kinesis"; + + @SerializedName("rg") + private String region; + @SerializedName("stm") + private String stream; + @SerializedName("ep") + private String endpoint; + + // optional, user want to load shards(Kafka's cskp). + @SerializedName("csks") + private List<String> customKinesisShards = Lists.newArrayList(); + + // OPEN shards - actively receiving new data + @SerializedName("opks") + private List<String> openKinesisShards = Lists.newArrayList(); + + // CLOSED shards with unconsumed data - no longer receiving new data but still have data to consume + @SerializedName("clks") + private List<String> closedKinesisShards = Lists.newArrayList(); + + // Default starting position for new shards. + // Values: TRIM_HORIZON, LATEST, or a timestamp string. + private String kinesisDefaultPosition = ""; + + // custom Kinesis properties including AWS credentials and client settings. + @SerializedName("prop") + private Map<String, String> customProperties = Maps.newHashMap(); + private Map<String, String> convertedCustomProperties = Maps.newHashMap(); + + // The latest offset of each partition fetched from kinesis server. + // Will be updated periodically by calling hasMoreDataToConsume() + private Map<String, Long> cachedShardWithMillsBehindLatest = Maps.newConcurrentMap(); + + // newly discovered shards from Kinesis. + private List<String> newCurrentKinesisShards = Lists.newArrayList(); + + public KinesisRoutineLoadJob() { + // For serialization + super(-1, LoadDataSourceType.KINESIS); + } + + public KinesisRoutineLoadJob(Long id, String name, long dbId, long tableId, + String region, String stream, UserIdentity userIdentity) { + super(id, name, dbId, tableId, LoadDataSourceType.KINESIS, userIdentity); + this.region = region; + this.stream = stream; + this.progress = new KinesisProgress(); + } + + public KinesisRoutineLoadJob(Long id, String name, long dbId, + String region, String stream, + UserIdentity userIdentity, boolean isMultiTable) { + super(id, name, dbId, LoadDataSourceType.KINESIS, userIdentity); + this.region = region; + this.stream = stream; + this.progress = new KinesisProgress(); + setMultiTable(isMultiTable); + } + + public String getRegion() { + return region; + } + + public String getStream() { + return stream; + } + + public String getEndpoint() { + return endpoint; + } + + public Map<String, String> getConvertedCustomProperties() { + return convertedCustomProperties; + } + + @Override + public void prepare() throws UserException { + // should reset converted properties each time the job being prepared. + // because the file info can be changed anytime. + convertCustomProperties(true); + } + + private void convertCustomProperties(boolean rebuild) throws DdlException { + if (customProperties.isEmpty()) { + return; + } + + if (!rebuild && !convertedCustomProperties.isEmpty()) { + return; + } + + if (rebuild) { + convertedCustomProperties.clear(); + } + + for (Map.Entry<String, String> entry : customProperties.entrySet()) { + convertedCustomProperties.put(entry.getKey(), entry.getValue()); + } + + // Handle default position + if (convertedCustomProperties.containsKey("kinesis_default_pos")) { + kinesisDefaultPosition = convertedCustomProperties.get("kinesis_default_pos"); + // Keep it in convertedCustomProperties so BE can use it + } + } + + private String convertedDefaultPosition() { + if (this.kinesisDefaultPosition.isEmpty()) { + return KinesisProgress.POSITION_LATEST; + } + return this.kinesisDefaultPosition; + } + + @Override + public void divideRoutineLoadJob(int currentConcurrentTaskNum) throws UserException { + List<RoutineLoadTaskInfo> result = new ArrayList<>(); + writeLock(); + try { + if (state == JobState.NEED_SCHEDULE) { + // Combine open and closed shards for task assignment + List<String> allShards = Lists.newArrayList(); + allShards.addAll(openKinesisShards); + allShards.addAll(closedKinesisShards); + + // Divide shards into tasks + for (int i = 0; i < currentConcurrentTaskNum; i++) { + Map<String, String> taskKinesisProgress = Maps.newHashMap(); + for (int j = i; j < allShards.size(); j = j + currentConcurrentTaskNum) { + String shardId = allShards.get(j); + taskKinesisProgress.put(shardId, + ((KinesisProgress) progress).getSequenceNumberByShard(shardId)); + } + KinesisTaskInfo kinesisTaskInfo = new KinesisTaskInfo(UUID.randomUUID(), id, + getTimeout() * 1000, taskKinesisProgress, isMultiTable(), -1, false); + routineLoadTaskInfoList.add(kinesisTaskInfo); + result.add(kinesisTaskInfo); + } + // Change job state to running + if (!result.isEmpty()) { + unprotectUpdateState(JobState.RUNNING, null, false); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("Ignore to divide routine load job while job state {}", state); + } + } + // Save task into queue of needScheduleTasks + Env.getCurrentEnv().getRoutineLoadTaskScheduler().addTasksInQueue(result); + } finally { + writeUnlock(); + } + } + + @Override + public int calculateCurrentConcurrentTaskNum() { + int shardNum = openKinesisShards.size() + closedKinesisShards.size(); + if (desireTaskConcurrentNum == 0) { + desireTaskConcurrentNum = Config.max_routine_load_task_concurrent_num; + } + + if (LOG.isDebugEnabled()) { + LOG.debug("current concurrent task number is min" + + "(shard num: {}, desire task concurrent num: {}, config: {})", + shardNum, desireTaskConcurrentNum, Config.max_routine_load_task_concurrent_num); + } + currentTaskConcurrentNum = Math.min(shardNum, Math.min(desireTaskConcurrentNum, + Config.max_routine_load_task_concurrent_num)); + return currentTaskConcurrentNum; + } + + @Override + protected boolean checkCommitInfo(RLTaskTxnCommitAttachment rlTaskTxnCommitAttachment, + TransactionState txnState, + TransactionState.TxnStatusChangeReason txnStatusChangeReason) { + if (txnState.getTransactionStatus() == TransactionStatus.COMMITTED + || txnState.getTransactionStatus() == TransactionStatus.VISIBLE) { + return true; + } + + if (LOG.isDebugEnabled()) { + LOG.debug("no need to update the progress of kinesis routine load. txn status: {}, " + + "txnStatusChangeReason: {}, task: {}, job: {}", + txnState.getTransactionStatus(), txnStatusChangeReason, + DebugUtil.printId(rlTaskTxnCommitAttachment.getTaskId()), id); + } + return false; + } + + private void updateProgressAndOffsetsCache(RLTaskTxnCommitAttachment attachment) { + KinesisProgress taskProgress = (KinesisProgress) attachment.getProgress(); + + // Update cachedShardWithMillsBehindLatest + taskProgress.getShardIdToMillsBehindLatest().forEach((shardId, millis) -> + cachedShardWithMillsBehindLatest.merge(shardId, millis, Math::max)); + + // Handle closed shards: move from open to closed list + if (taskProgress.getClosedShardIds() != null && !taskProgress.getClosedShardIds().isEmpty()) { + for (String closedShardId : taskProgress.getClosedShardIds()) { + if (openKinesisShards.remove(closedShardId)) { + if (!closedKinesisShards.contains(closedShardId)) { + closedKinesisShards.add(closedShardId); + LOG.info("Moved shard from open to closed: {}, job: {}", closedShardId, id); + } + } + } + } + + // Update progress (this will remove fully consumed shards from progress) + this.progress.update(attachment); + + // Remove fully consumed shards from closed list + closedKinesisShards.removeIf(shardId -> !((KinesisProgress) progress).containsShard(shardId)); + } + + @Override + protected void updateProgress(RLTaskTxnCommitAttachment attachment) throws UserException { + updateProgressAndOffsetsCache(attachment); + super.updateProgress(attachment); + } + + @Override + protected void replayUpdateProgress(RLTaskTxnCommitAttachment attachment) { + super.replayUpdateProgress(attachment); + updateProgressAndOffsetsCache(attachment); + } + + @Override + protected RoutineLoadTaskInfo unprotectRenewTask(RoutineLoadTaskInfo routineLoadTaskInfo, boolean delaySchedule) { + KinesisTaskInfo oldKinesisTaskInfo = (KinesisTaskInfo) routineLoadTaskInfo; + // Add new task + KinesisTaskInfo kinesisTaskInfo = new KinesisTaskInfo(oldKinesisTaskInfo, + ((KinesisProgress) progress).getShardIdToSequenceNumber(oldKinesisTaskInfo.getShards()), + isMultiTable()); + kinesisTaskInfo.setDelaySchedule(delaySchedule); + // Remove old task + routineLoadTaskInfoList.remove(routineLoadTaskInfo); + // Add new task + routineLoadTaskInfoList.add(kinesisTaskInfo); + return kinesisTaskInfo; + } + + @Override + protected void unprotectUpdateProgress() throws UserException { + updateNewShardProgress(); + } + + @Override + protected boolean refreshKafkaPartitions(boolean needAutoResume) throws UserException { + // For Kinesis, we refresh shards instead of Kafka partitions + if (this.state == JobState.RUNNING || this.state == JobState.NEED_SCHEDULE || needAutoResume) { + if (customKinesisShards != null && !customKinesisShards.isEmpty()) { + return true; + } + return updateKinesisShards(); + } + return true; + } + + private boolean updateKinesisShards() throws UserException { + try { + this.newCurrentKinesisShards = getAllKinesisShards(); + } catch (Exception e) { + String msg = e.getMessage() + + " may be Kinesis properties set in job is error" + + " or no shard in this stream that should check Kinesis"; + LOG.warn(new LogBuilder(LogKey.ROUTINE_LOAD_JOB, id) + .add("error_msg", msg) + .build(), e); + if (this.state == JobState.NEED_SCHEDULE) { + unprotectUpdateState(JobState.PAUSED, + new ErrorReason(InternalErrorCode.PARTITIONS_ERR, msg), + false /* not replay */); + } + return false; + } + return true; + } + + @Override + protected boolean unprotectNeedReschedule() throws UserException { + if (this.state == JobState.RUNNING || this.state == JobState.NEED_SCHEDULE) { + return isKinesisShardsChanged(); + } + return false; + } + + private boolean isKinesisShardsChanged() throws UserException { + if (CollectionUtils.isNotEmpty(customKinesisShards)) { + if (Config.isCloudMode() && (openKinesisShards.isEmpty() && closedKinesisShards.isEmpty())) { + updateCloudProgress(); + } + openKinesisShards = customKinesisShards; + closedKinesisShards.clear(); + return false; + } + + Preconditions.checkNotNull(this.newCurrentKinesisShards); + + // newCurrentKinesisShards contains only OPEN shards (BE ListShards returns OPEN only). + // Compare against openKinesisShards only; closedKinesisShards is managed separately + // via BE task progress reports and must not be included here to avoid false positives. + Set<String> newShards = new HashSet<>(this.newCurrentKinesisShards); + Set<String> currentOpenShards = new HashSet<>(openKinesisShards); + + // Detect new shards + if (!newShards.equals(currentOpenShards)) { + openKinesisShards = new ArrayList<>(newShards); + + if (LOG.isDebugEnabled()) { + LOG.debug(new LogBuilder(LogKey.ROUTINE_LOAD_JOB, id) + .add("open_kinesis_shards", Joiner.on(",").join(openKinesisShards)) + .add("closed_kinesis_shards", Joiner.on(",").join(closedKinesisShards)) + .add("msg", "kinesis shards changed") + .build()); + } + return true; + } + + // Check if progress is consistent for all tracked shards (open + closed) + Set<String> allTrackedShards = new HashSet<>(currentOpenShards); + allTrackedShards.addAll(closedKinesisShards); + for (String shardId : allTrackedShards) { + if (!((KinesisProgress) progress).containsShard(shardId)) { + return true; + } + } + return false; + } + + @Override + protected boolean needAutoResume() { + writeLock(); + try { + if (this.state == JobState.PAUSED) { + return ScheduleRule.isNeedAutoSchedule(this); + } + return false; + } finally { + writeUnlock(); + } + } + + @Override + public String getStatistic() { + Map<String, Object> summary = this.jobStatistic.summary(); + readLock(); + try { + summary.put("openShardNum", openKinesisShards.size()); + summary.put("closedShardNum", closedKinesisShards.size()); + summary.put("trackedShardNum", ((KinesisProgress) progress).getShardIdToSequenceNumber().size()); + summary.put("cachedMillisBehindLatestShardNum", cachedShardWithMillsBehindLatest.size()); + summary.put("totalMillisBehindLatest", totalLag()); + long maxMillisBehindLatest = cachedShardWithMillsBehindLatest.values().stream() + .filter(lag -> lag >= 0) + .mapToLong(v -> v) + .max() + .orElse(-1L); + summary.put("maxMillisBehindLatest", maxMillisBehindLatest); + } finally { + readUnlock(); + } + Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + return gson.toJson(summary); + } + + /** + * Get all shards from the Kinesis stream. + * Delegates to a BE node via gRPC, which calls AWS ListShards API using the SDK. + */ + private List<String> getAllKinesisShards() throws UserException { + convertCustomProperties(false); + if (!customKinesisShards.isEmpty()) { + return customKinesisShards; + } + return KinesisUtil.getAllKinesisShards(region, stream, endpoint, convertedCustomProperties); + } + + /** + * Create a KinesisRoutineLoadJob from CreateRoutineLoadInfo. + */ + public static KinesisRoutineLoadJob fromCreateInfo(CreateRoutineLoadInfo info, ConnectContext ctx) + throws UserException { + if (Config.isCloudMode()) { + throw new DdlException("Kinesis routine load does not support cloud mode"); + } + Database db = Env.getCurrentInternalCatalog().getDbOrDdlException(info.getDBName()); + + long id = Env.getCurrentEnv().getNextId(); + KinesisDataSourceProperties kinesisProperties = + (KinesisDataSourceProperties) info.getDataSourceProperties(); + KinesisRoutineLoadJob kinesisRoutineLoadJob; + + if (kinesisProperties.isMultiTable()) { + kinesisRoutineLoadJob = new KinesisRoutineLoadJob(id, info.getName(), + db.getId(), + kinesisProperties.getRegion(), kinesisProperties.getStream(), + ctx.getCurrentUserIdentity(), true); + } else { + OlapTable olapTable = db.getOlapTableOrDdlException(info.getTableName()); + checkMeta(olapTable, info.getRoutineLoadDesc()); + // Check load_to_single_tablet compatibility + if (info.isLoadToSingleTablet() + && !(olapTable.getDefaultDistributionInfo() instanceof RandomDistributionInfo)) { + throw new DdlException( + "if load_to_single_tablet set to true, the olap table must be with random distribution"); + } + long tableId = olapTable.getId(); + kinesisRoutineLoadJob = new KinesisRoutineLoadJob(id, info.getName(), + db.getId(), tableId, + kinesisProperties.getRegion(), kinesisProperties.getStream(), + ctx.getCurrentUserIdentity()); + } + + kinesisRoutineLoadJob.setOptional(info); + kinesisRoutineLoadJob.checkCustomProperties(); + + return kinesisRoutineLoadJob; + } + + private void checkCustomProperties() throws DdlException { + // Validate custom properties if needed + } + + private void updateNewShardProgress() throws UserException { + // Check if this is initial setup (no shards in progress yet) + boolean isInitialSetup = !((KinesisProgress) progress).hasShards(); + + // Combine open and closed shards + List<String> allShards = Lists.newArrayList(); + allShards.addAll(openKinesisShards); + allShards.addAll(closedKinesisShards); + + for (String shardId : allShards) { + if (!((KinesisProgress) progress).containsShard(shardId)) { + String startPosition; + + if (isInitialSetup) { + // Initial shards: use user-configured default position + startPosition = convertedDefaultPosition(); + } else { + // New shards discovered later: always use TRIM_HORIZON to avoid data loss + startPosition = KinesisProgress.TRIM_HORIZON_VAL; + LOG.info("New shard detected: {}, starting from TRIM_HORIZON to avoid data loss", + shardId); + } + + ((KinesisProgress) progress).addShardPosition(Pair.of(shardId, startPosition)); + if (LOG.isDebugEnabled()) { + LOG.debug(new LogBuilder(LogKey.ROUTINE_LOAD_JOB, id) + .add("kinesis_shard_id", shardId) + .add("begin_position", startPosition) + .add("is_initial_setup", isInitialSetup) + .add("msg", "The new shard has been added in job")); + } + } + } + } + + private List<Pair<String, String>> getNewShardPositionsFromDefault(List<String> newShards) + throws UserException { + List<Pair<String, String>> shardPositions = Lists.newArrayList(); + String defaultPosition = convertedDefaultPosition(); + for (String shardId : newShards) { + shardPositions.add(Pair.of(shardId, defaultPosition)); + } + return shardPositions; + } + + protected void setOptional(CreateRoutineLoadInfo info) throws UserException { + super.setOptional(info); + KinesisDataSourceProperties kinesisDataSourceProperties = + (KinesisDataSourceProperties) info.getDataSourceProperties(); + + // Set endpoint if provided + if (kinesisDataSourceProperties.getEndpoint() != null) { + this.endpoint = kinesisDataSourceProperties.getEndpoint(); + } + + // Set custom shards and positions + if (CollectionUtils.isNotEmpty(kinesisDataSourceProperties.getKinesisShardPositions())) { + setCustomKinesisShards(kinesisDataSourceProperties); + } + + // Set custom properties + if (MapUtils.isNotEmpty(kinesisDataSourceProperties.getCustomKinesisProperties())) { + setCustomKinesisProperties(kinesisDataSourceProperties.getCustomKinesisProperties()); + } + } + + private void setCustomKinesisShards(KinesisDataSourceProperties kinesisDataSourceProperties) throws LoadException { + List<Pair<String, String>> shardPositions = kinesisDataSourceProperties.getKinesisShardPositions(); + for (Pair<String, String> shardPosition : shardPositions) { + this.customKinesisShards.add(shardPosition.first); + ((KinesisProgress) progress).addShardPosition(shardPosition); + } + } + + private void setCustomKinesisProperties(Map<String, String> kinesisProperties) { + this.customProperties = kinesisProperties; + } + + @Override + public String dataSourcePropertiesJsonToString() { + Map<String, String> dataSourceProperties = Maps.newHashMap(); + dataSourceProperties.put("region", region); + dataSourceProperties.put("stream", stream); + if (endpoint != null) { + dataSourceProperties.put("endpoint", endpoint); + } + List<String> sortedOpenShards = Lists.newArrayList(openKinesisShards); + Collections.sort(sortedOpenShards); + dataSourceProperties.put("openKinesisShards", Joiner.on(",").join(sortedOpenShards)); + + List<String> sortedClosedShards = Lists.newArrayList(closedKinesisShards); + Collections.sort(sortedClosedShards); + dataSourceProperties.put("closedKinesisShards", Joiner.on(",").join(sortedClosedShards)); + + Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + return gson.toJson(dataSourceProperties); + } + + @Override + public String customPropertiesJsonToString() { + Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + // Mask sensitive information + Map<String, String> maskedProperties = new HashMap<>(customProperties); + if (maskedProperties.containsKey("aws.secret_key")) { + maskedProperties.put("aws.secret_key", "******"); + } + if (maskedProperties.containsKey("aws.session_key")) { + maskedProperties.put("aws.session_key", "******"); + } + return gson.toJson(maskedProperties); + } + + @Override + public Map<String, String> getDataSourceProperties() { + Map<String, String> dataSourceProperties = Maps.newHashMap(); + dataSourceProperties.put("kinesis_region", region); Review Comment: Medium: `SHOW CREATE ROUTINE LOAD` is no longer round-trippable here. `getDataSourceProperties()` emits `kinesis_region` / `kinesis_stream` / `kinesis_endpoint`, but the analyzer for this PR accepts `aws.region`, `aws.kinesis.stream`, and `aws.endpoint`/`kinesis_endpoint`. Re-executing the SQL returned by `SHOW CREATE` will fail with an invalid-property error instead of recreating the job. ########## be/src/load/routine_load/data_consumer.cpp: ########## @@ -560,4 +575,536 @@ bool KafkaDataConsumer::match(std::shared_ptr<StreamLoadContext> ctx) { return true; } +// ==================== AWS Kinesis Data Consumer Implementation ==================== + +KinesisDataConsumer::KinesisDataConsumer(std::shared_ptr<StreamLoadContext> ctx) + : _region(ctx->kinesis_info->region), + _stream(ctx->kinesis_info->stream), + _endpoint(ctx->kinesis_info->endpoint) { + VLOG_NOTICE << "construct Kinesis consumer: stream=" << _stream << ", region=" << _region; +} + +KinesisDataConsumer::~KinesisDataConsumer() { + VLOG_NOTICE << "destruct Kinesis consumer: stream=" << _stream; + // AWS SDK client managed by shared_ptr, will be automatically cleaned up +} + +Status KinesisDataConsumer::init(std::shared_ptr<StreamLoadContext> ctx) { + std::unique_lock<std::mutex> l(_lock); + if (_init) { + return Status::OK(); // Already initialized (idempotent) + } + + // Store custom properties (AWS credentials, etc.) + _custom_properties.insert(ctx->kinesis_info->properties.begin(), + ctx->kinesis_info->properties.end()); + + // Create KinesisConf and configure it + _kinesis_conf = std::make_unique<KinesisConf>(); + std::string errstr; + + // Parse and categorize aws.kinesis.* properties into three types + for (auto& item : _custom_properties) { + if (starts_with(item.first, "aws.kinesis.")) { + std::string conf_key = item.first.substr(12); // Remove "aws.kinesis." prefix + + // Type 2: Frequently-used parameters (explicit members) + if (conf_key == "shards") { + std::vector<std::string> parts = + absl::StrSplit(item.second, ",", absl::SkipWhitespace()); + _explicit_shards = std::move(parts); + VLOG_NOTICE << "Set explicit shards: " << item.second; + } else if (conf_key == "default.pos") { + _default_position = item.second; + VLOG_NOTICE << "Set default position: " << item.second; + } else if (starts_with(conf_key, "shards.pos.")) { + std::string shard_id = conf_key.substr(11); // Remove "shards.pos." prefix + _shard_positions[shard_id] = item.second; + VLOG_NOTICE << "Set shard position: " << shard_id << " = " << item.second; + } + // Type 3: Less-frequently-used API parameters (KinesisConf determines which API) + else { + KinesisConf::ConfResult res = _kinesis_conf->set(conf_key, item.second, errstr); + if (res == KinesisConf::CONF_INVALID) { + return Status::InternalError("Failed to set '{}': {}", conf_key, errstr); + } + // CONF_UNKNOWN is acceptable (parameter will be ignored) + } + } + } + + // Create AWS Kinesis client + RETURN_IF_ERROR(_create_kinesis_client(ctx)); + + VLOG_NOTICE << "finished to init Kinesis consumer. stream=" << _stream << ", region=" << _region + << ", " << ctx->brief(); + _init = true; + return Status::OK(); +} + +Status KinesisDataConsumer::_create_kinesis_client(std::shared_ptr<StreamLoadContext> ctx) { + // Reuse S3ClientFactory's credential provider logic + // This supports all AWS authentication methods: + // - Simple AK/SK + // - IAM instance profile (EC2) + // - STS assume role + // - Session tokens + // - Environment variables + // - Default credential chain + + S3ClientConf s3_conf; + s3_conf.region = _region; + s3_conf.endpoint = _endpoint; + + auto get_property = [this](const char* key) -> std::string { + auto it = _custom_properties.find(key); + if (it != _custom_properties.end() && !it->second.empty()) { + return it->second; + } + return ""; + }; + + // Keep one naming convention aligned with FE-side Kinesis properties. + s3_conf.ak = get_property("aws.access_key"); + s3_conf.sk = get_property("aws.secret_key"); + s3_conf.token = get_property("aws.session_key"); + s3_conf.role_arn = get_property("aws.role_arn"); + s3_conf.external_id = get_property("aws.external.id"); + + const std::string provider = get_property("aws.credentials.provider"); + if (!provider.empty()) { + // Map provider type string to enum + if (provider == "instance_profile") { + s3_conf.cred_provider_type = CredProviderType::InstanceProfile; + } else if (provider == "env") { + s3_conf.cred_provider_type = CredProviderType::Env; + } else if (provider == "simple") { + s3_conf.cred_provider_type = CredProviderType::Simple; + } + } + + // Create AWS ClientConfiguration + Aws::Client::ClientConfiguration aws_config = S3ClientFactory::getClientConfiguration(); + aws_config.region = _region; + + if (!_endpoint.empty()) { + aws_config.endpointOverride = _endpoint; + } + + std::string ca_cert_file_path = + get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";")); + if (!ca_cert_file_path.empty()) { + aws_config.caFile = ca_cert_file_path; + } + + auto parse_timeout_ms = [](const std::string& timeout_value, const std::string& property_name, + long* timeout_ms) -> Status { + try { + *timeout_ms = std::stol(timeout_value); + } catch (const std::exception&) { + return Status::InternalError("Invalid value for {}: {}", property_name, timeout_value); + } + return Status::OK(); + }; + + // Set timeouts from properties or use defaults + auto it_request_timeout = _custom_properties.find("aws.request.timeout.ms"); + if (it_request_timeout != _custom_properties.end()) { + RETURN_IF_ERROR(parse_timeout_ms(it_request_timeout->second, "aws.request.timeout.ms", + &aws_config.requestTimeoutMs)); + } else { + aws_config.requestTimeoutMs = 30000; // 30s default + } + + auto it_conn_timeout = _custom_properties.find("aws.connection.timeout.ms"); + if (it_conn_timeout != _custom_properties.end()) { + RETURN_IF_ERROR(parse_timeout_ms(it_conn_timeout->second, "aws.connection.timeout.ms", + &aws_config.connectTimeoutMs)); + } + + // Get credentials provider (reuses S3 infrastructure) + auto credentials_provider = S3ClientFactory::instance().get_aws_credentials_provider(s3_conf); + + // Create Kinesis client + _kinesis_client = + std::make_shared<Aws::Kinesis::KinesisClient>(credentials_provider, aws_config); + + if (!_kinesis_client) { + return Status::InternalError( + "Failed to create AWS Kinesis client for stream: {}, region: {}", _stream, _region); + } + + LOG(INFO) << "Created Kinesis client for stream: " << _stream << ", region: " << _region; + return Status::OK(); +} + +Status KinesisDataConsumer::assign_shards( + const std::map<std::string, std::string>& shard_sequence_numbers, + const std::string& stream_name, std::shared_ptr<StreamLoadContext> ctx) { + DORIS_CHECK(_kinesis_client); + + std::stringstream ss; + ss << "Assigning shards to Kinesis consumer " << _id << ": "; + + for (auto& entry : shard_sequence_numbers) { + const std::string& shard_id = entry.first; + const std::string& sequence_number = entry.second; + + // Get shard iterator for this shard + std::string iterator; + RETURN_IF_ERROR(_get_shard_iterator(shard_id, sequence_number, &iterator)); + + _shard_iterators[shard_id] = iterator; + _consuming_shard_ids.insert(shard_id); + + ss << "[" << shard_id << ": " << sequence_number << "] "; + } + + LOG(INFO) << ss.str(); + return Status::OK(); +} + +Status KinesisDataConsumer::_get_shard_iterator(const std::string& shard_id, + const std::string& sequence_number, + std::string* iterator) { + Aws::Kinesis::Model::GetShardIteratorRequest request; + + // Apply all configurations through KinesisConf + DCHECK(_kinesis_conf != nullptr); + Status st = _kinesis_conf->apply_to_get_shard_iterator_request(request, _stream, shard_id, + sequence_number); + if (!st.ok()) { + return Status::InternalError( + "Failed to apply Kinesis config to GetShardIteratorRequest: {}", st.to_string()); + } + + auto outcome = _kinesis_client->GetShardIterator(request); + if (!outcome.IsSuccess()) { + auto& error = outcome.GetError(); + return Status::InternalError("Failed to get shard iterator for shard {}: {} ({})", shard_id, + error.GetMessage(), static_cast<int>(error.GetErrorType())); + } + + *iterator = outcome.GetResult().GetShardIterator(); + VLOG_NOTICE << "Got shard iterator for shard: " << shard_id; + return Status::OK(); +} + +Status KinesisDataConsumer::group_consume( + BlockingQueue<std::shared_ptr<Aws::Kinesis::Model::Record>>* queue, + int64_t max_running_time_ms) { + static constexpr int MAX_RETRY_TIMES_FOR_TRANSPORT_FAILURE = 3; + static constexpr int RATE_LIMIT_BACKOFF_MS = 1000; // 1 second + static constexpr int INTER_SHARD_SLEEP_MS = 10; // Small sleep between shards + static constexpr int MIN_INTERVAL_BETWEEN_ROUNDS_MS = 200; // Min 200ms between rounds + + int64_t left_time = max_running_time_ms; + LOG(INFO) << "start Kinesis consumer: " << _id << ", grp: " << _grp_id + << ", stream: " << _stream << ", max running time(ms): " << left_time; + + int64_t received_rows = 0; + int64_t put_rows = 0; + int32_t retry_times = 0; + int32_t throttle_count = 0; // Track consecutive throttle errors + Status st = Status::OK(); + bool done = false; + + MonotonicStopWatch consumer_watch; + MonotonicStopWatch watch; + watch.start(); + + while (true) { + // Check cancellation flag + { + std::unique_lock<std::mutex> l(_lock); + if (_cancelled) { + break; + } + } + + if (left_time <= 0) { + break; + } + + // Round-robin through all active shards + for (auto it = _consuming_shard_ids.begin(); it != _consuming_shard_ids.end() && !done;) { + const std::string& shard_id = *it; + auto iter_it = _shard_iterators.find(shard_id); + + if (iter_it == _shard_iterators.end() || iter_it->second.empty()) { + // Shard exhausted (closed due to split/merge), remove from active set + LOG(INFO) << "Shard exhausted: " << shard_id; + it = _consuming_shard_ids.erase(it); + continue; + } + + consumer_watch.start(); + + Aws::Kinesis::Model::GetRecordsRequest request; + + DCHECK(_kinesis_conf != nullptr); + st = _kinesis_conf->apply_to_get_records_request(request, iter_it->second); + if (!st.ok()) { + LOG(WARNING) << "Failed to apply Kinesis config to GetRecordsRequest: " << st; + done = true; + break; + } + + auto outcome = _kinesis_client->GetRecords(request); + consumer_watch.stop(); + + // Track generic routine load metrics and Kinesis-specific metrics. + DorisMetrics::instance()->routine_load_get_msg_count->increment(1); + DorisMetrics::instance()->routine_load_get_msg_latency->increment( + consumer_watch.elapsed_time() / 1000 / 1000); + DorisMetrics::instance()->routine_load_kinesis_get_records_count->increment(1); + DorisMetrics::instance()->routine_load_kinesis_get_records_latency->increment( + consumer_watch.elapsed_time() / 1000 / 1000); + + if (!outcome.IsSuccess()) { + auto& error = outcome.GetError(); + + // Handle throttling (ProvisionedThroughputExceededException) + if (error.GetErrorType() == + Aws::Kinesis::KinesisErrors::PROVISIONED_THROUGHPUT_EXCEEDED) { + throttle_count++; + DorisMetrics::instance()->routine_load_kinesis_throttle_count->increment(1); + // Exponential backoff: 1s, 2s, 4s, 8s, max 10s + int backoff_ms = std::min( + RATE_LIMIT_BACKOFF_MS * (1 << std::min(throttle_count - 1, 3)), 10000); + LOG(INFO) << "Kinesis rate limit exceeded for shard: " << shard_id + << ", throttle_count: " << throttle_count << ", backing off " + << backoff_ms << "ms"; + std::this_thread::sleep_for(std::chrono::milliseconds(backoff_ms)); + ++it; // Move to next shard, will retry this one next round + continue; + } + + // Handle retriable errors + if (_is_retriable_error(error)) { + DorisMetrics::instance()->routine_load_kinesis_retriable_error_count->increment( + 1); + LOG(INFO) << "Kinesis retriable error for shard " << shard_id << ": " + << error.GetMessage() << ", retry times: " << retry_times++; + if (retry_times <= MAX_RETRY_TIMES_FOR_TRANSPORT_FAILURE) { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + continue; + } + } + + // Fatal error + LOG(WARNING) << "Kinesis consume failed for shard " << shard_id << ": " + << error.GetMessage() << " (" << static_cast<int>(error.GetErrorType()) + << ")"; + st = Status::InternalError("Kinesis GetRecords failed for shard {}: {}", shard_id, + error.GetMessage()); + done = true; + break; + } + + // Reset retry counter on success + retry_times = 0; + throttle_count = 0; // Reset throttle counter on successful GetRecords + + // Process records - move result to allow moving individual records + auto result = outcome.GetResultWithOwnership(); + auto millis_behind = result.GetMillisBehindLatest(); + std::string next_iterator = result.GetNextShardIterator(); + size_t record_count = result.GetRecords().size(); + RETURN_IF_ERROR(_process_records(shard_id, std::move(result), queue, &received_rows, + &put_rows)); + + // Track MillisBehindLatest for this shard (used by FE for lag monitoring & scheduling) + _millis_behind_latest[shard_id] = millis_behind; + + // Update shard iterator for next call + if (next_iterator.empty()) { + // Shard is closed (split/merge), mark as closed and remove from active set + LOG(INFO) << "Shard closed: " << shard_id << " (split/merge detected)"; + DorisMetrics::instance()->routine_load_kinesis_closed_shard_count->increment(1); + _closed_shard_ids.insert(shard_id); + _shard_iterators.erase(shard_id); + it = _consuming_shard_ids.erase(it); + } else { + // Update iterator for next consumption + _shard_iterators[shard_id] = next_iterator; + + if (record_count == 0) { + // No records in this batch - shard has caught up with latest data + // Remove from active set for this round (similar to Kafka PARTITION_EOF) + // but keep iterator and progress for next task execution + LOG(INFO) << "Shard has no new data: " << shard_id + << " (MillisBehindLatest=" << millis_behind << ")"; + it = _consuming_shard_ids.erase(it); + } else { + ++it; + } + } + + // Check if all shards are exhausted + if (_consuming_shard_ids.empty()) { + LOG(INFO) << "All shards exhausted for consumer: " << _id; + done = true; + break; + } + + // Small sleep to avoid tight loop + std::this_thread::sleep_for(std::chrono::milliseconds(INTER_SHARD_SLEEP_MS)); + } + + // Ensure minimum interval between rounds to respect Kinesis rate limits (5 GetRecords/sec per shard) + std::this_thread::sleep_for(std::chrono::milliseconds(MIN_INTERVAL_BETWEEN_ROUNDS_MS)); + + left_time = max_running_time_ms - watch.elapsed_time() / 1000 / 1000; + if (done) { + break; + } + } + + LOG(INFO) << "Kinesis consumer done: " << _id << ", grp: " << _grp_id + << ". cancelled: " << _cancelled << ", left time(ms): " << left_time + << ", total cost(ms): " << watch.elapsed_time() / 1000 / 1000 + << ", consume cost(ms): " << consumer_watch.elapsed_time() / 1000 / 1000 + << ", received rows: " << received_rows << ", put rows: " << put_rows; + + return st; +} + +Status KinesisDataConsumer::_process_records( + const std::string& shard_id, Aws::Kinesis::Model::GetRecordsResult result, + BlockingQueue<std::shared_ptr<Aws::Kinesis::Model::Record>>* queue, int64_t* received_rows, + int64_t* put_rows) { + // result is owned by value, safe to get mutable access to its records + auto records = + std::move(const_cast<Aws::Vector<Aws::Kinesis::Model::Record>&>(result.GetRecords())); + for (auto& record : records) { + DorisMetrics::instance()->routine_load_consume_bytes->increment( + record.GetData().GetLength()); + + if (record.GetData().GetLength() == 0) { + // Skip empty records + continue; + } + + // Track the last sequence number for this shard + _committed_sequence_numbers[shard_id] = record.GetSequenceNumber(); + + // Move record into shared_ptr to avoid expensive copy + auto record_ptr = std::make_shared<Aws::Kinesis::Model::Record>(std::move(record)); + + if (!queue->controlled_blocking_put(record_ptr, + config::blocking_queue_cv_wait_timeout_ms)) { + // Queue shutdown + return Status::InternalError("Queue shutdown during record processing"); + } + + (*put_rows)++; + (*received_rows)++; + DorisMetrics::instance()->routine_load_consume_rows->increment(1); + } + + return Status::OK(); +} + +bool KinesisDataConsumer::_is_retriable_error( + const Aws::Client::AWSError<Aws::Kinesis::KinesisErrors>& error) { + auto error_type = error.GetErrorType(); + + return error_type == Aws::Kinesis::KinesisErrors::PROVISIONED_THROUGHPUT_EXCEEDED || + error_type == Aws::Kinesis::KinesisErrors::SERVICE_UNAVAILABLE || + error_type == Aws::Kinesis::KinesisErrors::INTERNAL_FAILURE || + error_type == Aws::Kinesis::KinesisErrors::NETWORK_CONNECTION || error.ShouldRetry(); +} + +Status KinesisDataConsumer::reset() { + std::unique_lock<std::mutex> l(_lock); + _cancelled = false; + _consuming_shard_ids.clear(); + _shard_iterators.clear(); + _millis_behind_latest.clear(); + _committed_sequence_numbers.clear(); + _closed_shard_ids.clear(); + _last_visit_time = time(nullptr); + LOG(INFO) << "Kinesis consumer reset: " << _id; + return Status::OK(); +} + +Status KinesisDataConsumer::cancel(std::shared_ptr<StreamLoadContext> ctx) { + std::unique_lock<std::mutex> l(_lock); + if (!_init) { + return Status::InternalError("Kinesis consumer is not initialized"); + } + _cancelled = true; + LOG(INFO) << "Kinesis consumer cancelled: " << _id << ", " << ctx->brief(); + return Status::OK(); +} + +bool KinesisDataConsumer::match(std::shared_ptr<StreamLoadContext> ctx) { + if (ctx->load_src_type != TLoadSourceType::KINESIS) { + return false; + } + + if (_region != ctx->kinesis_info->region || _stream != ctx->kinesis_info->stream || + _endpoint != ctx->kinesis_info->endpoint) { + return false; + } + + // Check that properties match + if (_custom_properties.size() != ctx->kinesis_info->properties.size()) { + return false; + } + + for (auto& item : ctx->kinesis_info->properties) { + auto itr = _custom_properties.find(item.first); + if (itr == _custom_properties.end() || itr->second != item.second) { + return false; + } + } + + return true; +} + +Status KinesisDataConsumer::get_shard_list(std::vector<std::string>* shard_ids) { + DORIS_CHECK(_kinesis_client); + + // If user specified explicit shards, return those + if (!_explicit_shards.empty()) { + *shard_ids = _explicit_shards; + LOG(INFO) << "Using " << shard_ids->size() << " explicit shards for stream: " << _stream; + return Status::OK(); + } + + // Discover all shards + Aws::Kinesis::Model::ListShardsRequest request; + + DCHECK(_kinesis_conf != nullptr); + Status st = _kinesis_conf->apply_to_list_shards_request(request, _stream); + if (!st.ok()) { + return Status::InternalError("Failed to apply Kinesis config to ListShardsRequest: {}", + st.to_string()); + } + + // Only return OPEN shards. CLOSED shards are tracked separately via closedKinesisShards + // on the FE side (populated when BE reports shard exhaustion). Including CLOSED shards here + // would cause retired parent shards to be re-added to the open list after reschedule, Review Comment: Medium: this only issues a single `ListShards` call and never follows `NextToken`. On streams with enough shards for pagination, `get_shard_list()` will silently return only the first page, so FE never schedules the remaining shards. This is reproducible by setting `aws.kinesis.max_results` below the stream shard count. ########## fe/fe-core/src/main/java/org/apache/doris/load/routineload/RLTaskTxnCommitAttachment.java: ########## @@ -63,6 +63,9 @@ public RLTaskTxnCommitAttachment(TRLTaskTxnCommitAttachment rlTaskTxnCommitAttac case KAFKA: this.progress = new KafkaProgress(rlTaskTxnCommitAttachment.getKafkaRLTaskProgress()); break; + case KINESIS: Review Comment: Medium: adding a Kinesis progress type here also requires updating the cloud txn protobuf path. `TxnUtil.rlTaskTxnCommitAttachmentToPb()` still unconditionally casts `getProgress()` to `KafkaProgress`, and the protobuf constructor still rebuilds only `KafkaProgress`. Any cloud/meta-service serialization of a Kinesis routine-load attachment will therefore mis-serialize or throw. ########## be/src/load/routine_load/data_consumer.cpp: ########## @@ -560,4 +575,536 @@ bool KafkaDataConsumer::match(std::shared_ptr<StreamLoadContext> ctx) { return true; } +// ==================== AWS Kinesis Data Consumer Implementation ==================== + +KinesisDataConsumer::KinesisDataConsumer(std::shared_ptr<StreamLoadContext> ctx) + : _region(ctx->kinesis_info->region), + _stream(ctx->kinesis_info->stream), + _endpoint(ctx->kinesis_info->endpoint) { + VLOG_NOTICE << "construct Kinesis consumer: stream=" << _stream << ", region=" << _region; +} + +KinesisDataConsumer::~KinesisDataConsumer() { + VLOG_NOTICE << "destruct Kinesis consumer: stream=" << _stream; + // AWS SDK client managed by shared_ptr, will be automatically cleaned up +} + +Status KinesisDataConsumer::init(std::shared_ptr<StreamLoadContext> ctx) { + std::unique_lock<std::mutex> l(_lock); + if (_init) { + return Status::OK(); // Already initialized (idempotent) + } + + // Store custom properties (AWS credentials, etc.) + _custom_properties.insert(ctx->kinesis_info->properties.begin(), + ctx->kinesis_info->properties.end()); + + // Create KinesisConf and configure it + _kinesis_conf = std::make_unique<KinesisConf>(); + std::string errstr; + + // Parse and categorize aws.kinesis.* properties into three types + for (auto& item : _custom_properties) { + if (starts_with(item.first, "aws.kinesis.")) { + std::string conf_key = item.first.substr(12); // Remove "aws.kinesis." prefix + + // Type 2: Frequently-used parameters (explicit members) + if (conf_key == "shards") { + std::vector<std::string> parts = + absl::StrSplit(item.second, ",", absl::SkipWhitespace()); + _explicit_shards = std::move(parts); + VLOG_NOTICE << "Set explicit shards: " << item.second; + } else if (conf_key == "default.pos") { + _default_position = item.second; + VLOG_NOTICE << "Set default position: " << item.second; + } else if (starts_with(conf_key, "shards.pos.")) { + std::string shard_id = conf_key.substr(11); // Remove "shards.pos." prefix + _shard_positions[shard_id] = item.second; + VLOG_NOTICE << "Set shard position: " << shard_id << " = " << item.second; + } + // Type 3: Less-frequently-used API parameters (KinesisConf determines which API) + else { + KinesisConf::ConfResult res = _kinesis_conf->set(conf_key, item.second, errstr); + if (res == KinesisConf::CONF_INVALID) { + return Status::InternalError("Failed to set '{}': {}", conf_key, errstr); + } + // CONF_UNKNOWN is acceptable (parameter will be ignored) + } + } + } + + // Create AWS Kinesis client + RETURN_IF_ERROR(_create_kinesis_client(ctx)); + + VLOG_NOTICE << "finished to init Kinesis consumer. stream=" << _stream << ", region=" << _region + << ", " << ctx->brief(); + _init = true; + return Status::OK(); +} + +Status KinesisDataConsumer::_create_kinesis_client(std::shared_ptr<StreamLoadContext> ctx) { + // Reuse S3ClientFactory's credential provider logic + // This supports all AWS authentication methods: + // - Simple AK/SK + // - IAM instance profile (EC2) + // - STS assume role + // - Session tokens + // - Environment variables + // - Default credential chain + + S3ClientConf s3_conf; + s3_conf.region = _region; + s3_conf.endpoint = _endpoint; + + auto get_property = [this](const char* key) -> std::string { + auto it = _custom_properties.find(key); + if (it != _custom_properties.end() && !it->second.empty()) { + return it->second; + } + return ""; + }; + + // Keep one naming convention aligned with FE-side Kinesis properties. + s3_conf.ak = get_property("aws.access_key"); + s3_conf.sk = get_property("aws.secret_key"); + s3_conf.token = get_property("aws.session_key"); + s3_conf.role_arn = get_property("aws.role_arn"); + s3_conf.external_id = get_property("aws.external.id"); + + const std::string provider = get_property("aws.credentials.provider"); + if (!provider.empty()) { + // Map provider type string to enum + if (provider == "instance_profile") { + s3_conf.cred_provider_type = CredProviderType::InstanceProfile; + } else if (provider == "env") { + s3_conf.cred_provider_type = CredProviderType::Env; + } else if (provider == "simple") { + s3_conf.cred_provider_type = CredProviderType::Simple; + } + } + + // Create AWS ClientConfiguration + Aws::Client::ClientConfiguration aws_config = S3ClientFactory::getClientConfiguration(); + aws_config.region = _region; + + if (!_endpoint.empty()) { + aws_config.endpointOverride = _endpoint; + } + + std::string ca_cert_file_path = + get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";")); + if (!ca_cert_file_path.empty()) { + aws_config.caFile = ca_cert_file_path; + } + + auto parse_timeout_ms = [](const std::string& timeout_value, const std::string& property_name, + long* timeout_ms) -> Status { + try { + *timeout_ms = std::stol(timeout_value); + } catch (const std::exception&) { + return Status::InternalError("Invalid value for {}: {}", property_name, timeout_value); + } + return Status::OK(); + }; + + // Set timeouts from properties or use defaults + auto it_request_timeout = _custom_properties.find("aws.request.timeout.ms"); + if (it_request_timeout != _custom_properties.end()) { + RETURN_IF_ERROR(parse_timeout_ms(it_request_timeout->second, "aws.request.timeout.ms", + &aws_config.requestTimeoutMs)); + } else { + aws_config.requestTimeoutMs = 30000; // 30s default + } + + auto it_conn_timeout = _custom_properties.find("aws.connection.timeout.ms"); + if (it_conn_timeout != _custom_properties.end()) { + RETURN_IF_ERROR(parse_timeout_ms(it_conn_timeout->second, "aws.connection.timeout.ms", + &aws_config.connectTimeoutMs)); + } + + // Get credentials provider (reuses S3 infrastructure) + auto credentials_provider = S3ClientFactory::instance().get_aws_credentials_provider(s3_conf); + + // Create Kinesis client + _kinesis_client = + std::make_shared<Aws::Kinesis::KinesisClient>(credentials_provider, aws_config); + + if (!_kinesis_client) { + return Status::InternalError( + "Failed to create AWS Kinesis client for stream: {}, region: {}", _stream, _region); + } + + LOG(INFO) << "Created Kinesis client for stream: " << _stream << ", region: " << _region; + return Status::OK(); +} + +Status KinesisDataConsumer::assign_shards( + const std::map<std::string, std::string>& shard_sequence_numbers, + const std::string& stream_name, std::shared_ptr<StreamLoadContext> ctx) { + DORIS_CHECK(_kinesis_client); + + std::stringstream ss; + ss << "Assigning shards to Kinesis consumer " << _id << ": "; + + for (auto& entry : shard_sequence_numbers) { + const std::string& shard_id = entry.first; + const std::string& sequence_number = entry.second; + + // Get shard iterator for this shard + std::string iterator; + RETURN_IF_ERROR(_get_shard_iterator(shard_id, sequence_number, &iterator)); + + _shard_iterators[shard_id] = iterator; + _consuming_shard_ids.insert(shard_id); + + ss << "[" << shard_id << ": " << sequence_number << "] "; + } + + LOG(INFO) << ss.str(); + return Status::OK(); +} + +Status KinesisDataConsumer::_get_shard_iterator(const std::string& shard_id, + const std::string& sequence_number, + std::string* iterator) { + Aws::Kinesis::Model::GetShardIteratorRequest request; + + // Apply all configurations through KinesisConf + DCHECK(_kinesis_conf != nullptr); + Status st = _kinesis_conf->apply_to_get_shard_iterator_request(request, _stream, shard_id, + sequence_number); + if (!st.ok()) { + return Status::InternalError( + "Failed to apply Kinesis config to GetShardIteratorRequest: {}", st.to_string()); + } + + auto outcome = _kinesis_client->GetShardIterator(request); + if (!outcome.IsSuccess()) { + auto& error = outcome.GetError(); + return Status::InternalError("Failed to get shard iterator for shard {}: {} ({})", shard_id, + error.GetMessage(), static_cast<int>(error.GetErrorType())); + } + + *iterator = outcome.GetResult().GetShardIterator(); + VLOG_NOTICE << "Got shard iterator for shard: " << shard_id; + return Status::OK(); +} + +Status KinesisDataConsumer::group_consume( + BlockingQueue<std::shared_ptr<Aws::Kinesis::Model::Record>>* queue, + int64_t max_running_time_ms) { + static constexpr int MAX_RETRY_TIMES_FOR_TRANSPORT_FAILURE = 3; + static constexpr int RATE_LIMIT_BACKOFF_MS = 1000; // 1 second + static constexpr int INTER_SHARD_SLEEP_MS = 10; // Small sleep between shards + static constexpr int MIN_INTERVAL_BETWEEN_ROUNDS_MS = 200; // Min 200ms between rounds + + int64_t left_time = max_running_time_ms; + LOG(INFO) << "start Kinesis consumer: " << _id << ", grp: " << _grp_id + << ", stream: " << _stream << ", max running time(ms): " << left_time; + + int64_t received_rows = 0; + int64_t put_rows = 0; + int32_t retry_times = 0; + int32_t throttle_count = 0; // Track consecutive throttle errors + Status st = Status::OK(); + bool done = false; + + MonotonicStopWatch consumer_watch; + MonotonicStopWatch watch; + watch.start(); + + while (true) { + // Check cancellation flag + { + std::unique_lock<std::mutex> l(_lock); + if (_cancelled) { + break; + } + } + + if (left_time <= 0) { + break; + } + + // Round-robin through all active shards + for (auto it = _consuming_shard_ids.begin(); it != _consuming_shard_ids.end() && !done;) { + const std::string& shard_id = *it; + auto iter_it = _shard_iterators.find(shard_id); + + if (iter_it == _shard_iterators.end() || iter_it->second.empty()) { + // Shard exhausted (closed due to split/merge), remove from active set + LOG(INFO) << "Shard exhausted: " << shard_id; + it = _consuming_shard_ids.erase(it); + continue; + } + + consumer_watch.start(); + + Aws::Kinesis::Model::GetRecordsRequest request; + + DCHECK(_kinesis_conf != nullptr); + st = _kinesis_conf->apply_to_get_records_request(request, iter_it->second); + if (!st.ok()) { + LOG(WARNING) << "Failed to apply Kinesis config to GetRecordsRequest: " << st; + done = true; + break; + } + + auto outcome = _kinesis_client->GetRecords(request); + consumer_watch.stop(); + + // Track generic routine load metrics and Kinesis-specific metrics. + DorisMetrics::instance()->routine_load_get_msg_count->increment(1); + DorisMetrics::instance()->routine_load_get_msg_latency->increment( + consumer_watch.elapsed_time() / 1000 / 1000); + DorisMetrics::instance()->routine_load_kinesis_get_records_count->increment(1); + DorisMetrics::instance()->routine_load_kinesis_get_records_latency->increment( + consumer_watch.elapsed_time() / 1000 / 1000); + + if (!outcome.IsSuccess()) { + auto& error = outcome.GetError(); + + // Handle throttling (ProvisionedThroughputExceededException) + if (error.GetErrorType() == + Aws::Kinesis::KinesisErrors::PROVISIONED_THROUGHPUT_EXCEEDED) { + throttle_count++; + DorisMetrics::instance()->routine_load_kinesis_throttle_count->increment(1); + // Exponential backoff: 1s, 2s, 4s, 8s, max 10s + int backoff_ms = std::min( + RATE_LIMIT_BACKOFF_MS * (1 << std::min(throttle_count - 1, 3)), 10000); + LOG(INFO) << "Kinesis rate limit exceeded for shard: " << shard_id + << ", throttle_count: " << throttle_count << ", backing off " + << backoff_ms << "ms"; + std::this_thread::sleep_for(std::chrono::milliseconds(backoff_ms)); + ++it; // Move to next shard, will retry this one next round + continue; + } + + // Handle retriable errors + if (_is_retriable_error(error)) { + DorisMetrics::instance()->routine_load_kinesis_retriable_error_count->increment( + 1); + LOG(INFO) << "Kinesis retriable error for shard " << shard_id << ": " + << error.GetMessage() << ", retry times: " << retry_times++; + if (retry_times <= MAX_RETRY_TIMES_FOR_TRANSPORT_FAILURE) { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + continue; + } + } + + // Fatal error + LOG(WARNING) << "Kinesis consume failed for shard " << shard_id << ": " + << error.GetMessage() << " (" << static_cast<int>(error.GetErrorType()) + << ")"; + st = Status::InternalError("Kinesis GetRecords failed for shard {}: {}", shard_id, + error.GetMessage()); + done = true; + break; + } + + // Reset retry counter on success + retry_times = 0; + throttle_count = 0; // Reset throttle counter on successful GetRecords + + // Process records - move result to allow moving individual records + auto result = outcome.GetResultWithOwnership(); + auto millis_behind = result.GetMillisBehindLatest(); + std::string next_iterator = result.GetNextShardIterator(); + size_t record_count = result.GetRecords().size(); + RETURN_IF_ERROR(_process_records(shard_id, std::move(result), queue, &received_rows, + &put_rows)); + + // Track MillisBehindLatest for this shard (used by FE for lag monitoring & scheduling) + _millis_behind_latest[shard_id] = millis_behind; + + // Update shard iterator for next call + if (next_iterator.empty()) { + // Shard is closed (split/merge), mark as closed and remove from active set + LOG(INFO) << "Shard closed: " << shard_id << " (split/merge detected)"; + DorisMetrics::instance()->routine_load_kinesis_closed_shard_count->increment(1); + _closed_shard_ids.insert(shard_id); + _shard_iterators.erase(shard_id); + it = _consuming_shard_ids.erase(it); + } else { + // Update iterator for next consumption + _shard_iterators[shard_id] = next_iterator; + + if (record_count == 0) { + // No records in this batch - shard has caught up with latest data + // Remove from active set for this round (similar to Kafka PARTITION_EOF) + // but keep iterator and progress for next task execution + LOG(INFO) << "Shard has no new data: " << shard_id + << " (MillisBehindLatest=" << millis_behind << ")"; + it = _consuming_shard_ids.erase(it); + } else { + ++it; + } + } + + // Check if all shards are exhausted + if (_consuming_shard_ids.empty()) { + LOG(INFO) << "All shards exhausted for consumer: " << _id; + done = true; + break; + } + + // Small sleep to avoid tight loop + std::this_thread::sleep_for(std::chrono::milliseconds(INTER_SHARD_SLEEP_MS)); + } + + // Ensure minimum interval between rounds to respect Kinesis rate limits (5 GetRecords/sec per shard) + std::this_thread::sleep_for(std::chrono::milliseconds(MIN_INTERVAL_BETWEEN_ROUNDS_MS)); + + left_time = max_running_time_ms - watch.elapsed_time() / 1000 / 1000; + if (done) { + break; + } + } + + LOG(INFO) << "Kinesis consumer done: " << _id << ", grp: " << _grp_id + << ". cancelled: " << _cancelled << ", left time(ms): " << left_time + << ", total cost(ms): " << watch.elapsed_time() / 1000 / 1000 + << ", consume cost(ms): " << consumer_watch.elapsed_time() / 1000 / 1000 + << ", received rows: " << received_rows << ", put rows: " << put_rows; + + return st; +} + +Status KinesisDataConsumer::_process_records( + const std::string& shard_id, Aws::Kinesis::Model::GetRecordsResult result, + BlockingQueue<std::shared_ptr<Aws::Kinesis::Model::Record>>* queue, int64_t* received_rows, + int64_t* put_rows) { + // result is owned by value, safe to get mutable access to its records + auto records = + std::move(const_cast<Aws::Vector<Aws::Kinesis::Model::Record>&>(result.GetRecords())); + for (auto& record : records) { + DorisMetrics::instance()->routine_load_consume_bytes->increment( + record.GetData().GetLength()); + + if (record.GetData().GetLength() == 0) { + // Skip empty records + continue; + } + Review Comment: High: progress is advanced before the record is actually handed off successfully. `_committed_sequence_numbers[shard_id]` is updated before `controlled_blocking_put()` succeeds, so when a task stops on `max_batch_rows`/`max_batch_size`/timeout with buffered Kinesis records still in the queue, the commit attachment can report a later sequence number than the rows that were really appended. The next task will then start after data that Doris never loaded. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
