You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by ga...@apache.org on 2026/04/24 04:45:35 UTC
(doris) 01/01: (cloud) oss native sdk
This is an automated email from the ASF dual-hosted git repository.
gavinchou pushed a commit to branch tmp-branch-4.1.0-oss-native-sdk
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 0f9193cb1e869565926b3ebaa8969b839d268698
Author: Gavin Chou <ga...@selectdb.com>
AuthorDate: Fri Apr 24 12:35:47 2026 +0800
(cloud) oss native sdk
---
be/CMakeLists.txt | 6 +
be/cmake/thirdparty.cmake | 15 +
be/src/cloud/cloud_meta_mgr.cpp | 17 +-
be/src/cloud/cloud_meta_mgr.h | 6 +-
be/src/cloud/cloud_storage_engine.cpp | 38 +-
be/src/common/config.cpp | 5 +
be/src/common/config.h | 5 +
be/src/io/CMakeLists.txt | 3 +
be/src/io/fs/file_system.h | 12 +-
be/src/io/fs/oss_file_reader.cpp | 277 +++++++++
be/src/io/fs/oss_file_reader.h | 81 +++
be/src/io/fs/oss_file_system.cpp | 631 ++++++++++++++++++++
be/src/io/fs/oss_file_system.h | 140 +++++
be/src/io/fs/oss_file_writer.cpp | 515 ++++++++++++++++
be/src/io/fs/oss_file_writer.h | 98 +++
be/src/io/fs/oss_v2_obj_storage_client.cpp | 443 ++++++++++++++
be/src/io/fs/oss_v2_obj_storage_client.h | 93 +++
be/src/util/CMakeLists.txt | 4 +
be/src/util/oss_util.cpp | 290 +++++++++
be/src/util/oss_util.h | 146 +++++
be/src/util/s3_util.cpp | 75 ++-
be/src/util/s3_util.h | 3 +
be/test/util/oss_credential_provider_test.cpp | 326 ++++++++++
build.sh | 7 +
cloud/CMakeLists.txt | 6 +
cloud/cmake/thirdparty.cmake | 13 +
cloud/src/meta-service/meta_service_resource.cpp | 135 +++--
cloud/src/recycler/CMakeLists.txt | 4 +
cloud/src/recycler/oss_accessor.cpp | 659 +++++++++++++++++++++
cloud/src/recycler/oss_accessor.h | 167 ++++++
cloud/src/recycler/recycler.cpp | 94 ++-
cloud/src/recycler/storage_vault_accessor.h | 1 +
cloud/test/CMakeLists.txt | 11 +
cloud/test/oss_accessor_test.cpp | 562 ++++++++++++++++++
common/cpp/CMakeLists.txt | 6 +
common/cpp/oss_common.h | 47 ++
common/cpp/oss_credential_provider.cpp | 489 +++++++++++++++
common/cpp/oss_credential_provider.h | 109 ++++
.../java/org/apache/doris/catalog/OSSResource.java | 238 ++++++++
.../java/org/apache/doris/catalog/Resource.java | 6 +-
.../org/apache/doris/catalog/S3StorageVault.java | 1 -
.../org/apache/doris/catalog/StorageVault.java | 2 +-
.../org/apache/doris/catalog/StorageVaultMgr.java | 14 +-
.../datasource/property/storage/OSSProperties.java | 213 ++++++-
.../org/apache/doris/fs/StorageTypeMapper.java | 3 +-
.../org/apache/doris/fs/obj/OSSObjStorage.java | 639 ++++++++++++++++++++
.../org/apache/doris/fs/remote/OSSFileSystem.java | 138 +++++
.../config/WebServerFactoryCustomizerConfig.java | 42 +-
.../plans/commands/info/CreateResourceInfo.java | 6 +
.../org/apache/doris/persist/gson/GsonUtils.java | 2 +
.../apache/doris/task/PushStoragePolicyTask.java | 6 +-
.../property/storage/OSSPropertiesTest.java | 131 +++-
.../test_oss_vault_with_assumerole.groovy | 158 +++++
thirdparty/build-thirdparty.sh | 247 +++++++-
thirdparty/download-thirdparty.sh | 51 ++
thirdparty/patches/tea-cpp-doris-oss-fix.patch | 63 ++
thirdparty/vars.sh | 57 +-
57 files changed, 7430 insertions(+), 126 deletions(-)
diff --git a/be/CMakeLists.txt b/be/CMakeLists.txt
index 1de3541d3eb..62da8ca01d1 100644
--- a/be/CMakeLists.txt
+++ b/be/CMakeLists.txt
@@ -191,6 +191,12 @@ if(BUILD_AZURE STREQUAL "ON")
add_definitions(-DUSE_AZURE)
endif()
+# Set if use Alibaba Cloud OSS or not
+option(BUILD_OSS "ON for building Alibaba Cloud OSS support for BE or OFF for not" ON)
+message(STATUS "build OSS: ${BUILD_OSS}")
+if(BUILD_OSS STREQUAL "ON")
+ add_definitions(-DUSE_OSS)
+endif()
set(GPERFTOOLS_HOME "${THIRDPARTY_DIR}/gperftools")
diff --git a/be/cmake/thirdparty.cmake b/be/cmake/thirdparty.cmake
index 227f81411f1..625d5d59a96 100644
--- a/be/cmake/thirdparty.cmake
+++ b/be/cmake/thirdparty.cmake
@@ -144,6 +144,21 @@ if (NOT OS_MACOSX)
add_thirdparty(aws-s2n LIBNAME "lib/libs2n.a")
endif()
+# Alibaba Cloud OSS SDK
+if(NOT BUILD_OSS STREQUAL "OFF")
+ # STS SDK V2 for AssumeRole (must be before OSS SDK)
+ add_thirdparty(darabonba_core)
+ add_thirdparty(alibabacloud_credentials)
+ add_thirdparty(alibabacloud_open_api_v2)
+ add_thirdparty(alibabacloud_sts20150401)
+
+ # OSS SDK
+ add_thirdparty(alibabacloud-oss-cpp-sdk)
+ add_thirdparty(apr)
+ add_thirdparty(apr-util LIBNAME "lib/libaprutil.a")
+ add_thirdparty(uuid LIB64)
+endif()
+
if(BUILD_AZURE STREQUAL "ON")
add_thirdparty(azure-core)
add_thirdparty(azure-identity)
diff --git a/be/src/cloud/cloud_meta_mgr.cpp b/be/src/cloud/cloud_meta_mgr.cpp
index 4e332b3b879..45925769fe0 100644
--- a/be/src/cloud/cloud_meta_mgr.cpp
+++ b/be/src/cloud/cloud_meta_mgr.cpp
@@ -64,6 +64,9 @@
#include "storage/tablet/tablet_meta.h"
#include "util/client_cache.h"
#include "util/network_util.h"
+#ifdef USE_OSS
+#include "util/oss_util.h"
+#endif
#include "util/s3_util.h"
#include "util/thrift_rpc_helper.h"
@@ -1581,8 +1584,18 @@ Status CloudMetaMgr::get_storage_vault_info(StorageVaultInfos* vault_infos, bool
*is_vault_mode = resp.enable_storage_vault();
auto add_obj_store = [&vault_infos](const auto& obj_store) {
- vault_infos->emplace_back(obj_store.id(), S3Conf::get_s3_conf(obj_store),
- StorageVaultPB_PathFormat {});
+#ifdef USE_OSS
+ if (obj_store.provider() == cloud::ObjectStoreInfoPB::OSS &&
+ config::enable_oss_native_sdk) {
+ vault_infos->emplace_back(obj_store.id(), OSSConf::get_oss_conf(obj_store),
+ StorageVaultPB_PathFormat {});
+ } else {
+#endif
+ vault_infos->emplace_back(obj_store.id(), S3Conf::get_s3_conf(obj_store),
+ StorageVaultPB_PathFormat {});
+#ifdef USE_OSS
+ }
+#endif
};
std::ranges::for_each(resp.obj_info(), add_obj_store);
diff --git a/be/src/cloud/cloud_meta_mgr.h b/be/src/cloud/cloud_meta_mgr.h
index 5bf54dde548..afffc3ab51c 100644
--- a/be/src/cloud/cloud_meta_mgr.h
+++ b/be/src/cloud/cloud_meta_mgr.h
@@ -29,6 +29,7 @@
#include "common/status.h"
#include "storage/rowset/rowset_fwd.h"
#include "storage/rowset/rowset_meta.h"
+#include "util/oss_util.h"
#include "util/s3_util.h"
namespace doris {
@@ -50,8 +51,9 @@ class TabletJobInfoPB;
class TabletStatsPB;
class TabletIndexPB;
-using StorageVaultInfos = std::vector<
- std::tuple<std::string, std::variant<S3Conf, HdfsVaultInfo>, StorageVaultPB_PathFormat>>;
+using StorageVaultInfos =
+ std::vector<std::tuple<std::string, std::variant<S3Conf, HdfsVaultInfo, OSSConf>,
+ StorageVaultPB_PathFormat>>;
// run tasks in bthread with concurrency and wait until all tasks done
// it stops running tasks if there are any tasks return !ok, leaving some tasks untouched
diff --git a/be/src/cloud/cloud_storage_engine.cpp b/be/src/cloud/cloud_storage_engine.cpp
index b1882a3c1bd..3096e0eb858 100644
--- a/be/src/cloud/cloud_storage_engine.cpp
+++ b/be/src/cloud/cloud_storage_engine.cpp
@@ -53,6 +53,7 @@
#include "io/cache/file_cache_common.h"
#include "io/fs/file_system.h"
#include "io/fs/hdfs_file_system.h"
+#include "io/fs/oss_file_system.h"
#include "io/fs/s3_file_system.h"
#include "io/hdfs_util.h"
#include "io/io_common.h"
@@ -110,7 +111,8 @@ CloudStorageEngine::~CloudStorageEngine() {
}
static Status vault_process_error(std::string_view id,
- std::variant<S3Conf, cloud::HdfsVaultInfo>& vault, Status err) {
+ std::variant<S3Conf, cloud::HdfsVaultInfo, OSSConf>& vault,
+ Status err) {
std::stringstream ss;
std::visit(
[&]<typename T>(T& val) {
@@ -118,6 +120,8 @@ static Status vault_process_error(std::string_view id,
ss << val.to_string();
} else if constexpr (std::is_same_v<T, cloud::HdfsVaultInfo>) {
val.SerializeToOstream(&ss);
+ } else if constexpr (std::is_same_v<T, OSSConf>) {
+ ss << val.to_string();
}
},
vault);
@@ -159,6 +163,27 @@ struct VaultCreateFSVisitor {
return Status::OK();
}
+ Status operator()(const OSSConf& oss_conf) const {
+ LOG(INFO) << "get new oss info: " << oss_conf.to_string() << " resource_id=" << id
+ << " check_fs: " << check_fs;
+
+ auto fs = DORIS_TRY(io::OSSFileSystem::create(oss_conf, id));
+ if (check_fs) {
+ bool res = false;
+ // just check connectivity, not care object if exist
+ auto st = fs->exists("not_exist_object", &res);
+ if (!st.ok()) {
+ LOG(FATAL) << "failed to check oss fs, resource_id: " << id << " st: " << st
+ << "oss_conf: " << oss_conf.to_string()
+ << "add enable_check_storage_vault=false to be.conf to skip the check";
+ }
+ }
+
+ put_storage_resource(id, {std::move(fs), path_format}, 0);
+ LOG_INFO("successfully create oss vault, vault id {}", id);
+ return Status::OK();
+ }
+
const std::string& id;
const cloud::StorageVaultPB_PathFormat& path_format;
bool check_fs;
@@ -190,6 +215,17 @@ struct RefreshFSVaultVisitor {
return Status::OK();
}
+ Status operator()(const OSSConf& oss_conf) const {
+ DCHECK_EQ(fs->type(), io::FileSystemType::OSS) << id;
+ auto oss_fs = std::static_pointer_cast<io::OSSFileSystem>(fs);
+ auto client_holder = oss_fs->client_holder();
+ auto st = client_holder->reset(oss_conf.client_conf);
+ if (!st.ok()) {
+ LOG(WARNING) << "failed to update oss fs, resource_id=" << id << ": " << st;
+ }
+ return st;
+ }
+
const std::string& id;
io::FileSystemSPtr fs;
const cloud::StorageVaultPB_PathFormat& path_format;
diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index ccdb9ffe22c..469a4b5bb85 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -1459,6 +1459,11 @@ DEFINE_mInt32(s3_read_max_wait_time_ms, "800");
DEFINE_mBool(enable_s3_object_check_after_upload, "true");
DEFINE_mInt32(aws_client_request_timeout_ms, "30000");
+DEFINE_mInt32(max_oss_client_retry, "10");
+DEFINE_mInt32(oss_read_base_wait_time_ms, "100");
+DEFINE_mInt32(oss_read_max_wait_time_ms, "800");
+DEFINE_Bool(enable_oss_native_sdk, "false");
+
DEFINE_mBool(enable_s3_rate_limiter, "false");
DEFINE_mInt64(s3_get_bucket_tokens, "1000000000000000000");
DEFINE_Validator(s3_get_bucket_tokens, [](int64_t config) -> bool { return config > 0; });
diff --git a/be/src/common/config.h b/be/src/common/config.h
index 39e176e4672..e2a434341d9 100644
--- a/be/src/common/config.h
+++ b/be/src/common/config.h
@@ -1572,6 +1572,11 @@ DECLARE_mInt32(s3_read_max_wait_time_ms);
DECLARE_mBool(enable_s3_object_check_after_upload);
DECLARE_mInt32(aws_client_request_timeout_ms);
+DECLARE_mInt32(max_oss_client_retry);
+DECLARE_mInt32(oss_read_base_wait_time_ms);
+DECLARE_mInt32(oss_read_max_wait_time_ms);
+DECLARE_Bool(enable_oss_native_sdk);
+
// write as inverted index tmp directory
DECLARE_String(tmp_file_dir);
diff --git a/be/src/io/CMakeLists.txt b/be/src/io/CMakeLists.txt
index 84f40761f1a..a4b805d697a 100644
--- a/be/src/io/CMakeLists.txt
+++ b/be/src/io/CMakeLists.txt
@@ -25,6 +25,9 @@ file(GLOB_RECURSE IO_FILES CONFIGURE_DEPENDS *.cpp)
if(BUILD_AZURE STREQUAL "OFF")
list(REMOVE_ITEM IO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/fs/azure_obj_storage_client.cpp")
endif()
+if(BUILD_OSS STREQUAL "OFF")
+ list(REMOVE_ITEM IO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/fs/oss_v2_obj_storage_client.cpp")
+endif()
if(NOT "${WITH_TDE_DIR}" STREQUAL "")
list(REMOVE_ITEM IO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/fs/encrypted_fs_factory.cpp")
diff --git a/be/src/io/fs/file_system.h b/be/src/io/fs/file_system.h
index 2cf63b2ff00..92ecbc956ef 100644
--- a/be/src/io/fs/file_system.h
+++ b/be/src/io/fs/file_system.h
@@ -48,7 +48,14 @@ namespace doris::io {
} while (0);
#endif
-enum class FileSystemType : uint8_t { LOCAL, S3, HDFS, BROKER, HTTP };
+enum class FileSystemType : uint8_t {
+ LOCAL,
+ S3,
+ HDFS,
+ BROKER,
+ HTTP,
+ OSS,
+};
inline std::ostream& operator<<(std::ostream& ostr, FileSystemType type) {
switch (type) {
@@ -67,6 +74,9 @@ inline std::ostream& operator<<(std::ostream& ostr, FileSystemType type) {
case FileSystemType::HTTP:
ostr << "HTTP";
return ostr;
+ case FileSystemType::OSS:
+ ostr << "OSS";
+ return ostr;
default:
ostr << "UNKNOWN";
return ostr;
diff --git a/be/src/io/fs/oss_file_reader.cpp b/be/src/io/fs/oss_file_reader.cpp
new file mode 100644
index 00000000000..a8f2a0a4eb7
--- /dev/null
+++ b/be/src/io/fs/oss_file_reader.cpp
@@ -0,0 +1,277 @@
+// 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 "io/fs/oss_file_reader.h"
+
+#include <alibabacloud/oss/OssClient.h>
+#include <bvar/latency_recorder.h>
+#include <bvar/reducer.h>
+#include <fmt/format.h>
+#include <glog/logging.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cstdlib>
+#include <random>
+#include <sstream>
+#include <thread>
+#include <utility>
+
+#include "common/compiler_util.h"
+#include "common/config.h"
+#include "common/metrics/doris_metrics.h"
+#include "io/fs/err_utils.h"
+#include "runtime/runtime_profile.h"
+#include "runtime/thread_context.h"
+#include "runtime/workload_management/io_throttle.h"
+#include "util/bvar_helper.h"
+#include "util/debug_points.h"
+
+namespace doris::io {
+
+namespace {
+// Thread-local random number generator for jitter
+// Using thread_local ensures each thread has its own seeded generator
+thread_local std::mt19937 g_rng(std::random_device {}());
+} // namespace
+
+bvar::Adder<uint64_t> oss_file_reader_read_counter("oss_file_reader", "read_at");
+bvar::Adder<uint64_t> oss_file_reader_total("oss_file_reader", "total_num");
+bvar::Adder<uint64_t> oss_bytes_read_total("oss_file_reader", "bytes_read");
+bvar::Adder<uint64_t> oss_file_being_read("oss_file_reader", "file_being_read");
+bvar::LatencyRecorder oss_bytes_per_read("oss_file_reader", "bytes_per_read");
+bvar::PerSecond<bvar::Adder<uint64_t>> oss_read_throughput("oss_file_reader", "oss_read_throughput",
+ &oss_bytes_read_total);
+bvar::PerSecond<bvar::Adder<uint64_t>> oss_get_request_qps("oss_file_reader", "oss_get_request",
+ &oss_file_reader_read_counter);
+bvar::LatencyRecorder oss_file_reader_latency("oss_file_reader", "oss_latency");
+
+Result<FileReaderSPtr> OSSFileReader::create(std::shared_ptr<OSSClientHolder> client,
+ std::string bucket, std::string key, int64_t file_size,
+ RuntimeProfile* profile) {
+ if (file_size < 0) {
+ auto res = client->object_file_size(bucket, key);
+ if (!res.has_value()) {
+ return ResultError(std::move(res.error()));
+ }
+ file_size = res.value();
+ }
+
+ return std::make_shared<OSSFileReader>(std::move(client), std::move(bucket), std::move(key),
+ file_size, profile);
+}
+
+OSSFileReader::OSSFileReader(std::shared_ptr<OSSClientHolder> client, std::string bucket,
+ std::string key, size_t file_size, RuntimeProfile* profile)
+ : _path(fmt::format("oss://{}/{}", bucket, key)),
+ _file_size(file_size),
+ _bucket(std::move(bucket)),
+ _key(std::move(key)),
+ _client(std::move(client)),
+ _profile(profile) {
+ // TODO: Create separate oss_file_open_reading and oss_file_reader_total DorisMetrics
+ // Currently reusing s3 metrics for backward compatibility with dashboards
+ DorisMetrics::instance()->s3_file_open_reading->increment(1);
+ DorisMetrics::instance()->s3_file_reader_total->increment(1);
+ oss_file_reader_total << 1;
+ oss_file_being_read << 1;
+}
+
+OSSFileReader::~OSSFileReader() {
+ static_cast<void>(close());
+ oss_file_being_read << -1;
+}
+
+Status OSSFileReader::close() {
+ bool expected = false;
+ if (_closed.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
+ // TODO: Should decrement oss_file_open_reading DorisMetric instead of s3 metric
+ DorisMetrics::instance()->s3_file_open_reading->increment(-1);
+ }
+ return Status::OK();
+}
+
+Status OSSFileReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
+ const IOContext* /*io_ctx*/) {
+ DCHECK(!closed());
+ if (offset > _file_size) {
+ return Status::InternalError(
+ "offset exceeds file size(offset: {}, file size: {}, path: {})", offset, _file_size,
+ _path.native());
+ }
+
+ size_t bytes_req = result.size;
+ char* to = result.data;
+ bytes_req = std::min(bytes_req, _file_size - offset);
+
+ VLOG_DEBUG << "OSS read_at_impl: offset=" << offset << " bytes_req=" << bytes_req
+ << " result.size=" << result.size << " file_size=" << _file_size;
+
+ if (UNLIKELY(bytes_req == 0)) {
+ *bytes_read = 0;
+ return Status::OK();
+ }
+
+ auto client = _client->get();
+ if (!client) {
+ return Status::InternalError("OSS client not initialized");
+ }
+ // TODO: add SCOPED_CONCURRENCY_COUNT for oss_file_reader_read like S3
+
+ int retry_count = 0;
+ const int base_wait_time = config::oss_read_base_wait_time_ms;
+ const int max_wait_time = config::oss_read_max_wait_time_ms;
+ const int max_retries = config::max_oss_client_retry;
+
+ int64_t begin_ts = std::chrono::duration_cast<std::chrono::microseconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
+ LIMIT_REMOTE_SCAN_IO(bytes_read);
+ SCOPED_RAW_TIMER(&_oss_stats.total_get_request_time_ns);
+ Defer defer_latency {[&]() {
+ int64_t end_ts = std::chrono::duration_cast<std::chrono::microseconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
+ oss_file_reader_latency << (end_ts - begin_ts);
+ }};
+
+ int total_sleep_time = 0;
+ while (retry_count <= max_retries) {
+ *bytes_read = 0;
+ oss_file_reader_read_counter << 1;
+
+ // Debug point: Simulate slow read
+ DBUG_EXECUTE_IF("OSSFileReader::read_at_impl.slow_read", {
+ auto sleep_ms = dp->param<int>("sleep_ms", 1000);
+ LOG(INFO) << "Debug point: Simulating slow OSS read, sleeping " << sleep_ms << "ms";
+ std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
+ });
+
+ // Debug point: Simulate rate limiting error
+ DBUG_EXECUTE_IF("OSSFileReader::read_at_impl.rate_limit", {
+ LOG(WARNING) << "Debug point: Simulating OSS rate limit error";
+ std::string msg = fmt::format("Debug OSS rate limit error for path {}", _path.native());
+ return Status::IOError(msg);
+ });
+
+ AlibabaCloud::OSS::GetObjectRequest request(_bucket, _key);
+ request.setRange(static_cast<int64_t>(offset),
+ static_cast<int64_t>(offset + bytes_req - 1));
+
+ auto outcome = client->GetObject(request);
+ _oss_stats.total_get_request_counter++;
+
+ // Debug point: Simulate read failure
+ DBUG_EXECUTE_IF("OSSFileReader::read_at_impl.read_error", {
+ LOG(WARNING) << "Debug point: Simulating OSS read error";
+ std::string msg = fmt::format("Debug OSS read error for path {}", _path.native());
+ return Status::IOError(msg);
+ });
+
+ if (!outcome.isSuccess()) {
+ std::string error_code = outcome.error().Code();
+
+ // Exponential backoff with jitter for rate limiting
+ if (error_code == "TooManyRequests" || error_code == "SlowDown") {
+ retry_count++;
+ if (retry_count > max_retries) {
+ std::string err_msg = fmt::format(
+ "OSS GetObject failed after {} retries for {}: {} - {}", max_retries,
+ _path.native(), error_code, outcome.error().Message());
+ LOG(WARNING) << err_msg;
+ return Status::IOError(err_msg);
+ }
+
+ // Exponential backoff with jitter
+ int wait_time = std::min(base_wait_time * (1 << retry_count), max_wait_time);
+ std::uniform_int_distribution<int> dist(0, 99);
+ int jitter = dist(g_rng);
+ wait_time += jitter;
+
+ std::this_thread::sleep_for(std::chrono::milliseconds(wait_time));
+ _oss_stats.too_many_request_err_counter++;
+ _oss_stats.too_many_request_sleep_time_ms += wait_time;
+ total_sleep_time += wait_time;
+
+ VLOG_DEBUG << "OSS rate limited, retry " << retry_count << "/" << max_retries
+ << " after " << wait_time << "ms (jitter: " << jitter
+ << "ms), path: " << _path.native();
+ continue;
+ }
+
+ std::string err_msg =
+ fmt::format("OSS GetObject failed for {}: {} - {}", _path.native(), error_code,
+ outcome.error().Message());
+ LOG(WARNING) << err_msg;
+ return Status::IOError(err_msg);
+ }
+
+ auto& content_stream = outcome.result().Content();
+ content_stream->read(to, bytes_req);
+ *bytes_read = content_stream->gcount();
+
+ if (*bytes_read != bytes_req) {
+ std::string msg = fmt::format(
+ "OSS read size mismatch: path={} offset={} bytes_req={} bytes_read={} "
+ "file_size={}",
+ _path.native(), offset, bytes_req, *bytes_read, _file_size);
+ LOG(WARNING) << msg;
+ return Status::InternalError(msg);
+ }
+
+ _oss_stats.total_bytes_read += bytes_req;
+ oss_bytes_read_total << bytes_req;
+ oss_bytes_per_read << bytes_req;
+ // TODO: Create separate oss_bytes_read_total DorisMetric to avoid confusing naming
+ // Currently reusing s3_bytes_read_total for backward compatibility with dashboards
+ DorisMetrics::instance()->s3_bytes_read_total->increment(bytes_req);
+
+ if (retry_count > 0) {
+ LOG(INFO) << fmt::format("OSS read {} succeeded after {} retries with {} ms sleeping",
+ _path.native(), retry_count, total_sleep_time);
+ }
+
+ return Status::OK();
+ }
+
+ return Status::IOError("OSS read failed: max retries exceeded");
+}
+
+void OSSFileReader::_collect_profile_before_close() {
+ if (_profile != nullptr) {
+ const char* oss_profile_name = "OSSProfile";
+ ADD_TIMER(_profile, oss_profile_name);
+ RuntimeProfile::Counter* total_get_request_counter =
+ ADD_CHILD_COUNTER(_profile, "TotalGetRequest", TUnit::UNIT, oss_profile_name);
+ RuntimeProfile::Counter* too_many_request_err_counter =
+ ADD_CHILD_COUNTER(_profile, "TooManyRequestErr", TUnit::UNIT, oss_profile_name);
+ RuntimeProfile::Counter* too_many_request_sleep_time = ADD_CHILD_COUNTER(
+ _profile, "TooManyRequestSleepTime", TUnit::TIME_MS, oss_profile_name);
+ RuntimeProfile::Counter* total_bytes_read =
+ ADD_CHILD_COUNTER(_profile, "TotalBytesRead", TUnit::BYTES, oss_profile_name);
+ RuntimeProfile::Counter* total_get_request_time_ns =
+ ADD_CHILD_TIMER(_profile, "TotalGetRequestTime", oss_profile_name);
+
+ COUNTER_UPDATE(total_get_request_counter, _oss_stats.total_get_request_counter);
+ COUNTER_UPDATE(too_many_request_err_counter, _oss_stats.too_many_request_err_counter);
+ COUNTER_UPDATE(too_many_request_sleep_time, _oss_stats.too_many_request_sleep_time_ms);
+ COUNTER_UPDATE(total_bytes_read, _oss_stats.total_bytes_read);
+ COUNTER_UPDATE(total_get_request_time_ns, _oss_stats.total_get_request_time_ns);
+ }
+}
+
+} // namespace doris::io
diff --git a/be/src/io/fs/oss_file_reader.h b/be/src/io/fs/oss_file_reader.h
new file mode 100644
index 00000000000..003d54b828c
--- /dev/null
+++ b/be/src/io/fs/oss_file_reader.h
@@ -0,0 +1,81 @@
+// 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.
+
+#pragma once
+
+#include <atomic>
+#include <memory>
+#include <string>
+
+#include "io/fs/file_reader.h"
+#include "io/fs/oss_file_system.h"
+#include "io/fs/path.h"
+
+namespace doris {
+class RuntimeProfile;
+
+namespace io {
+
+struct OSSFileReaderStats {
+ int64_t total_get_request_time_ns = 0;
+ int64_t total_get_request_counter = 0;
+ int64_t total_bytes_read = 0;
+ int64_t too_many_request_err_counter = 0;
+ int64_t too_many_request_sleep_time_ms = 0;
+};
+
+class OSSFileReader final : public FileReader {
+public:
+ static Result<FileReaderSPtr> create(std::shared_ptr<OSSClientHolder> client,
+ std::string bucket, std::string key, int64_t file_size,
+ RuntimeProfile* profile = nullptr);
+
+ OSSFileReader(std::shared_ptr<OSSClientHolder> client, std::string bucket, std::string key,
+ size_t file_size, RuntimeProfile* profile);
+
+ ~OSSFileReader() override;
+
+ Status close() override;
+
+ const Path& path() const override { return _path; }
+
+ size_t size() const override { return _file_size; }
+
+ bool closed() const override { return _closed.load(std::memory_order_acquire); }
+
+ int64_t mtime() const override { return 0; }
+
+protected:
+ Status read_at_impl(size_t offset, Slice result, size_t* bytes_read,
+ const IOContext* io_ctx) override;
+
+ void _collect_profile_before_close() override;
+
+private:
+ Path _path;
+ size_t _file_size;
+ std::string _bucket;
+ std::string _key;
+ std::shared_ptr<OSSClientHolder> _client;
+ std::atomic<bool> _closed {false};
+
+ OSSFileReaderStats _oss_stats;
+ RuntimeProfile* _profile = nullptr;
+};
+
+} // namespace io
+} // namespace doris
diff --git a/be/src/io/fs/oss_file_system.cpp b/be/src/io/fs/oss_file_system.cpp
new file mode 100644
index 00000000000..bc04ed49db9
--- /dev/null
+++ b/be/src/io/fs/oss_file_system.cpp
@@ -0,0 +1,631 @@
+// 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 "io/fs/oss_file_system.h"
+
+#include <alibabacloud/oss/OssClient.h>
+#include <fmt/format.h>
+
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <memory>
+#include <thread>
+
+#include "common/config.h"
+#include "common/logging.h"
+#include "common/status.h"
+#include "io/fs/err_utils.h"
+#include "io/fs/file_system.h"
+#include "io/fs/file_writer.h"
+#include "io/fs/local_file_system.h"
+#include "io/fs/oss_file_reader.h"
+#include "io/fs/oss_file_writer.h"
+#include "io/fs/remote_file_system.h"
+
+namespace doris::io {
+namespace {
+
+constexpr int64_t MULTIPART_COPY_THRESHOLD = 1073741824; // 1GB
+constexpr int64_t MULTIPART_COPY_PART_SIZE = 104857600; // 100MB per part
+
+#ifndef CHECK_OSS_CLIENT
+#define CHECK_OSS_CLIENT(client) \
+ if (!client) { \
+ return Status::InvalidArgument("init oss client error"); \
+ }
+#endif
+
+Result<std::string> get_oss_key(const Path& full_path) {
+ std::string path_str = full_path.native();
+
+ const std::string oss_prefix = "oss://";
+ if (path_str.find(oss_prefix) == 0) {
+ path_str = path_str.substr(oss_prefix.length());
+
+ size_t pos = path_str.find('/');
+ if (pos == std::string::npos) {
+ return ""; // No key, just bucket
+ }
+ return path_str.substr(pos + 1);
+ }
+
+ return path_str;
+}
+
+} // namespace
+
+OSSClientHolder::OSSClientHolder(OSSClientConf conf) : _conf(std::move(conf)) {}
+
+OSSClientHolder::~OSSClientHolder() = default;
+
+Status OSSClientHolder::init() {
+ _client = OSSClientFactory::instance().create(_conf);
+ if (!_client) {
+ return Status::InvalidArgument("failed to init oss client with conf {}", _conf.to_string());
+ }
+
+ return Status::OK();
+}
+
+Status OSSClientHolder::reset(const OSSClientConf& conf) {
+ OSSClientConf reset_conf;
+ {
+ std::shared_lock lock(_mtx);
+ if (conf.get_hash() == _conf.get_hash()) {
+ return Status::OK();
+ }
+
+ reset_conf = _conf;
+ reset_conf.ak = conf.ak;
+ reset_conf.sk = conf.sk;
+ reset_conf.token = conf.token;
+ reset_conf.bucket = conf.bucket;
+ reset_conf.connect_timeout_ms = conf.connect_timeout_ms;
+ reset_conf.max_connections = conf.max_connections;
+ reset_conf.request_timeout_ms = conf.request_timeout_ms;
+ reset_conf.cred_provider_type = conf.cred_provider_type;
+ }
+
+ auto client = OSSClientFactory::instance().create(reset_conf);
+ if (!client) {
+ return Status::InvalidArgument("failed to init oss client with conf {}", conf.to_string());
+ }
+
+ LOG(WARNING) << "reset oss client with new conf: " << conf.to_string();
+
+ {
+ std::lock_guard lock(_mtx);
+ _client = std::move(client);
+ _conf = std::move(reset_conf);
+ }
+
+ return Status::OK();
+}
+
+Result<int64_t> OSSClientHolder::object_file_size(const std::string& bucket,
+ const std::string& key) const {
+ auto client = get();
+ if (!client) {
+ return ResultError(Status::InvalidArgument("init oss client error"));
+ }
+
+ auto outcome = client->HeadObject(bucket, key);
+ if (!outcome.isSuccess()) {
+ return ResultError(Status::IOError("failed to head oss file {}: {} - {}",
+ full_oss_path(bucket, key), outcome.error().Code(),
+ outcome.error().Message()));
+ }
+
+ return outcome.result().ContentLength();
+}
+
+std::string OSSClientHolder::full_oss_path(std::string_view bucket, std::string_view key) const {
+ return fmt::format("{}/{}/{}", _conf.endpoint, bucket, key);
+}
+
+std::string OSSFileSystem::full_oss_path(std::string_view key) const {
+ return _client->full_oss_path(_bucket, key);
+}
+
+Result<std::shared_ptr<OSSFileSystem>> OSSFileSystem::create(OSSConf oss_conf, std::string id) {
+ std::shared_ptr<OSSFileSystem> fs(new OSSFileSystem(std::move(oss_conf), std::move(id)));
+ RETURN_IF_ERROR_RESULT(fs->init());
+ return fs;
+}
+
+OSSFileSystem::OSSFileSystem(OSSConf oss_conf, std::string id)
+ : RemoteFileSystem(oss_conf.prefix, std::move(id), FileSystemType::OSS),
+ _bucket(std::move(oss_conf.bucket)),
+ _prefix(std::move(oss_conf.prefix)),
+ _client(std::make_shared<OSSClientHolder>(std::move(oss_conf.client_conf))) {
+ if (!_prefix.empty()) {
+ size_t start = _prefix.find_first_not_of('/');
+ if (start == std::string::npos) {
+ _prefix = "";
+ } else {
+ size_t end = _prefix.find_last_not_of('/');
+ if (start > 0 || end < _prefix.size() - 1) {
+ _prefix = _prefix.substr(start, end - start + 1);
+ }
+ }
+ }
+}
+
+Status OSSFileSystem::init() {
+ return _client->init();
+}
+
+OSSFileSystem::~OSSFileSystem() = default;
+
+Status OSSFileSystem::create_file_impl(const Path& file, FileWriterPtr* writer,
+ const FileWriterOptions* opts) {
+ auto key = DORIS_TRY(get_oss_key(file));
+ *writer = std::make_unique<OSSFileWriter>(_client, _bucket, key, opts);
+ return Status::OK();
+}
+
+Status OSSFileSystem::open_file_internal(const Path& file, FileReaderSPtr* reader,
+ const FileReaderOptions& opts) {
+ auto key = DORIS_TRY(get_oss_key(file));
+ int64_t fsize = opts.file_size;
+
+ auto oss_reader = DORIS_TRY(OSSFileReader::create(_client, _bucket, key, fsize));
+ *reader = oss_reader;
+ return Status::OK();
+}
+
+Status OSSFileSystem::create_directory_impl(const Path& dir, bool failed_if_exists) {
+ return Status::OK();
+}
+
+Status OSSFileSystem::delete_file_impl(const Path& file) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto key = DORIS_TRY(get_oss_key(file));
+
+ auto outcome = client->DeleteObject(_bucket, key);
+
+ if (!outcome.isSuccess()) {
+ std::string error_code = outcome.error().Code();
+ if (error_code != "NoSuchKey") {
+ return Status::IOError("failed to delete file {}: {} - {}", full_oss_path(key),
+ error_code, outcome.error().Message());
+ }
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::delete_directory_impl(const Path& dir) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto prefix = DORIS_TRY(get_oss_key(dir));
+ if (!prefix.empty() && prefix.back() != '/') {
+ prefix.push_back('/');
+ }
+
+ // Abort in-progress multipart uploads
+ {
+ bool is_truncated = true;
+ std::string key_marker;
+ std::string upload_id_marker;
+ int aborted_count = 0;
+
+ while (is_truncated) {
+ AlibabaCloud::OSS::ListMultipartUploadsRequest list_uploads_request(_bucket);
+ list_uploads_request.setPrefix(prefix);
+ list_uploads_request.setMaxUploads(1000);
+
+ if (!key_marker.empty()) {
+ list_uploads_request.setKeyMarker(key_marker);
+ }
+ if (!upload_id_marker.empty()) {
+ list_uploads_request.setUploadIdMarker(upload_id_marker);
+ }
+
+ auto list_uploads_outcome = client->ListMultipartUploads(list_uploads_request);
+ if (!list_uploads_outcome.isSuccess()) {
+ LOG(WARNING) << "Failed to list multipart uploads for prefix " << prefix << ": "
+ << list_uploads_outcome.error().Code() << " - "
+ << list_uploads_outcome.error().Message()
+ << ". Continuing with object deletion.";
+ break; // Don't fail deletion if listing uploads fails
+ }
+
+ const auto& uploads_result = list_uploads_outcome.result();
+ const auto& uploads = uploads_result.MultipartUploadList();
+
+ for (const auto& upload : uploads) {
+ AlibabaCloud::OSS::AbortMultipartUploadRequest abort_request(_bucket, upload.Key,
+ upload.UploadId);
+ auto abort_outcome = client->AbortMultipartUpload(abort_request);
+
+ if (!abort_outcome.isSuccess()) {
+ LOG(WARNING) << "Failed to abort multipart upload: key=" << upload.Key
+ << " upload_id=" << upload.UploadId
+ << " error=" << abort_outcome.error().Code() << " - "
+ << abort_outcome.error().Message();
+ // Don't fail directory deletion if abort fails
+ } else {
+ aborted_count++;
+ VLOG(1) << "Aborted multipart upload: key=" << upload.Key
+ << " upload_id=" << upload.UploadId;
+ }
+ }
+
+ is_truncated = uploads_result.IsTruncated();
+ key_marker = uploads_result.NextKeyMarker();
+ upload_id_marker = uploads_result.NextUploadIdMarker();
+ }
+
+ if (aborted_count > 0) {
+ LOG(INFO) << "Aborted " << aborted_count
+ << " in-progress multipart uploads under prefix: " << prefix;
+ }
+ }
+
+ // Delete all objects with prefix
+ bool is_truncated = true;
+ std::string marker;
+
+ while (is_truncated) {
+ AlibabaCloud::OSS::ListObjectsRequest list_request(_bucket);
+ list_request.setPrefix(prefix);
+ list_request.setMaxKeys(1000);
+
+ if (!marker.empty()) {
+ list_request.setMarker(marker);
+ }
+
+ auto list_outcome = client->ListObjects(list_request);
+ if (!list_outcome.isSuccess()) {
+ return Status::IOError("failed to list objects for delete directory {}: {} - {}",
+ full_oss_path(prefix), list_outcome.error().Code(),
+ list_outcome.error().Message());
+ }
+
+ const auto& result = list_outcome.result();
+ const auto& objects = result.ObjectSummarys();
+
+ if (!objects.empty()) {
+ AlibabaCloud::OSS::DeletedKeyList keys;
+ for (const auto& obj : objects) {
+ keys.push_back(obj.Key());
+ }
+
+ AlibabaCloud::OSS::DeleteObjectsRequest delete_request(_bucket);
+ delete_request.setKeyList(keys);
+ auto delete_outcome = client->DeleteObjects(delete_request);
+
+ if (!delete_outcome.isSuccess()) {
+ return Status::IOError("failed to batch delete objects: {} - {}",
+ delete_outcome.error().Code(),
+ delete_outcome.error().Message());
+ }
+ }
+
+ is_truncated = result.IsTruncated();
+ marker = result.NextMarker();
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::batch_delete_impl(const std::vector<Path>& remote_files) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ constexpr size_t max_delete_batch = 1000;
+ auto path_iter = remote_files.begin();
+
+ do {
+ AlibabaCloud::OSS::DeletedKeyList keys;
+ auto path_begin = path_iter;
+
+ for (; path_iter != remote_files.end() && (path_iter - path_begin < max_delete_batch);
+ ++path_iter) {
+ auto key = DORIS_TRY(get_oss_key(*path_iter));
+ keys.push_back(key);
+ }
+
+ if (keys.empty()) {
+ break;
+ }
+
+ AlibabaCloud::OSS::DeleteObjectsRequest request(_bucket);
+ request.setKeyList(keys);
+ auto outcome = client->DeleteObjects(request);
+
+ if (!outcome.isSuccess()) {
+ return Status::IOError("failed to batch delete objects: {} - {}",
+ outcome.error().Code(), outcome.error().Message());
+ }
+ } while (path_iter != remote_files.end());
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::exists_impl(const Path& path, bool* res) const {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto key = DORIS_TRY(get_oss_key(path));
+
+ auto outcome = client->HeadObject(_bucket, key);
+ if (outcome.isSuccess()) {
+ *res = true;
+ } else if (outcome.error().Code() == "NoSuchKey") {
+ *res = false;
+ } else {
+ return Status::IOError("failed to check existence of {}: {} - {}", key,
+ outcome.error().Code(), outcome.error().Message());
+ }
+ return Status::OK();
+}
+
+Status OSSFileSystem::file_size_impl(const Path& file, int64_t* file_size) const {
+ auto key = DORIS_TRY(get_oss_key(file));
+ *file_size = DORIS_TRY(_client->object_file_size(_bucket, key));
+ return Status::OK();
+}
+
+Status OSSFileSystem::list_impl(const Path& dir, bool only_file, std::vector<FileInfo>* files,
+ bool* exists) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto prefix = DORIS_TRY(get_oss_key(dir));
+ if (!prefix.empty() && prefix.back() != '/') {
+ prefix.push_back('/');
+ }
+
+ *exists = false;
+
+ bool is_truncated = true;
+ std::string marker;
+
+ while (is_truncated) {
+ AlibabaCloud::OSS::ListObjectsRequest request(_bucket);
+ request.setPrefix(prefix);
+ request.setMaxKeys(1000);
+
+ // Use delimiter for non-recursive listing to prevent memory exhaustion
+ if (only_file) {
+ request.setDelimiter("/");
+ }
+
+ if (!marker.empty()) {
+ request.setMarker(marker);
+ }
+
+ auto outcome = client->ListObjects(request);
+ if (!outcome.isSuccess()) {
+ return Status::IOError("failed to list objects: {} - {}", outcome.error().Code(),
+ outcome.error().Message());
+ }
+
+ const auto& result = outcome.result();
+ const auto& objects = result.ObjectSummarys();
+
+ if (!objects.empty()) {
+ *exists = true;
+ }
+
+ for (const auto& obj : objects) {
+ FileInfo file_info;
+ file_info.file_name = obj.Key();
+ // Remove prefix from file name
+ if (file_info.file_name.find(prefix) == 0) {
+ file_info.file_name = file_info.file_name.substr(prefix.length());
+ }
+
+ file_info.file_size = obj.Size();
+ file_info.is_file = true;
+
+ files->push_back(std::move(file_info));
+ }
+
+ is_truncated = result.IsTruncated();
+ marker = result.NextMarker();
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::rename_impl(const Path& orig_name, const Path& new_name) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto src_key = DORIS_TRY(get_oss_key(orig_name));
+ auto dst_key = DORIS_TRY(get_oss_key(new_name));
+
+ // Get source file size to determine copy strategy
+ int64_t file_size = DORIS_TRY(_client->object_file_size(_bucket, src_key));
+
+ if (file_size < MULTIPART_COPY_THRESHOLD) {
+ // Simple copy for files < 1GB
+ AlibabaCloud::OSS::CopyObjectRequest copy_request(_bucket, dst_key);
+ copy_request.setCopySource(_bucket, src_key);
+
+ auto copy_outcome = client->CopyObject(copy_request);
+ if (!copy_outcome.isSuccess()) {
+ return Status::IOError("failed to copy object from {} to {}: {} - {}",
+ full_oss_path(src_key), full_oss_path(dst_key),
+ copy_outcome.error().Code(), copy_outcome.error().Message());
+ }
+ } else {
+ // Multipart copy for large files to avoid timeouts
+ auto init_outcome = client->InitiateMultipartUpload(
+ AlibabaCloud::OSS::InitiateMultipartUploadRequest(_bucket, dst_key));
+ if (!init_outcome.isSuccess()) {
+ return Status::IOError("failed to initiate multipart upload: {} - {}",
+ init_outcome.error().Code(), init_outcome.error().Message());
+ }
+
+ std::string upload_id = init_outcome.result().UploadId();
+ AlibabaCloud::OSS::PartList part_etags;
+
+ // Calculate number of parts
+ int64_t part_count = (file_size + MULTIPART_COPY_PART_SIZE - 1) / MULTIPART_COPY_PART_SIZE;
+
+ // Copy parts
+ for (int64_t i = 0; i < part_count; ++i) {
+ int64_t start_offset = i * MULTIPART_COPY_PART_SIZE;
+ int64_t end_offset =
+ std::min(start_offset + MULTIPART_COPY_PART_SIZE - 1, file_size - 1);
+
+ AlibabaCloud::OSS::UploadPartCopyRequest part_request(_bucket, dst_key, _bucket,
+ src_key);
+ part_request.setUploadId(upload_id);
+ part_request.setPartNumber(static_cast<uint32_t>(i + 1));
+ part_request.setCopySourceRange(start_offset, end_offset);
+
+ auto part_outcome = client->UploadPartCopy(part_request);
+ if (!part_outcome.isSuccess()) {
+ // Abort multipart upload on failure
+ client->AbortMultipartUpload(AlibabaCloud::OSS::AbortMultipartUploadRequest(
+ _bucket, dst_key, upload_id));
+ return Status::IOError("failed to copy part {}: {} - {}", i + 1,
+ part_outcome.error().Code(), part_outcome.error().Message());
+ }
+
+ part_etags.push_back(AlibabaCloud::OSS::Part(static_cast<int32_t>(i + 1),
+ part_outcome.result().ETag()));
+ }
+
+ // Complete multipart upload
+ AlibabaCloud::OSS::CompleteMultipartUploadRequest complete_request(_bucket, dst_key,
+ part_etags, upload_id);
+ auto complete_outcome = client->CompleteMultipartUpload(complete_request);
+ if (!complete_outcome.isSuccess()) {
+ client->AbortMultipartUpload(
+ AlibabaCloud::OSS::AbortMultipartUploadRequest(_bucket, dst_key, upload_id));
+ return Status::IOError("failed to complete multipart upload: {} - {}",
+ complete_outcome.error().Code(),
+ complete_outcome.error().Message());
+ }
+ }
+
+ // Delete source object
+ auto delete_outcome = client->DeleteObject(_bucket, src_key);
+ if (!delete_outcome.isSuccess()) {
+ LOG(WARNING) << "Failed to delete source object after copy: " << src_key << " - "
+ << delete_outcome.error().Code() << ": " << delete_outcome.error().Message();
+ // Don't fail rename if delete fails, copy succeeded
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::upload_impl(const Path& local_file, const Path& remote_file) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto key = DORIS_TRY(get_oss_key(remote_file));
+
+ auto outcome = client->PutObject(_bucket, key, local_file.native());
+ if (!outcome.isSuccess()) {
+ return Status::IOError("failed to upload file to {}: {} - {}", full_oss_path(key),
+ outcome.error().Code(), outcome.error().Message());
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::batch_upload_impl(const std::vector<Path>& local_files,
+ const std::vector<Path>& remote_files) {
+ if (local_files.size() != remote_files.size()) {
+ return Status::InvalidArgument("local_files and remote_files size mismatch");
+ }
+
+ for (size_t i = 0; i < local_files.size(); ++i) {
+ RETURN_IF_ERROR(upload_impl(local_files[i], remote_files[i]));
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileSystem::download_impl(const Path& remote_file, const Path& local_file) {
+ auto client = _client->get();
+ CHECK_OSS_CLIENT(client);
+
+ auto key = DORIS_TRY(get_oss_key(remote_file));
+
+ AlibabaCloud::OSS::GetObjectRequest request(_bucket, key);
+
+ auto outcome = client->GetObject(request);
+ if (!outcome.isSuccess()) {
+ return Status::IOError("failed to download file from {}: {} - {}", full_oss_path(key),
+ outcome.error().Code(), outcome.error().Message());
+ }
+
+ // Use temp file + rename pattern to ensure atomicity and proper cleanup on failure.
+ std::string temp_file_path =
+ local_file.native() + ".tmp." + std::to_string(getpid()) + "." +
+ std::to_string(std::hash<std::thread::id> {}(std::this_thread::get_id()));
+
+ // RAII wrapper to ensure temp file cleanup on failure
+ struct TempFileGuard {
+ std::string path;
+ bool success = false;
+
+ ~TempFileGuard() {
+ if (!success && !path.empty()) {
+ // Clean up temp file on failure
+ std::error_code ec;
+ std::filesystem::remove(path, ec);
+ if (ec) {
+ LOG(WARNING) << "Failed to remove temp file " << path << ": " << ec.message();
+ }
+ }
+ }
+ } temp_guard {temp_file_path};
+
+ // Write to temp file
+ std::ofstream out(temp_file_path, std::ios::binary);
+ if (!out) {
+ return Status::IOError("failed to open temp file for writing: {}", temp_file_path);
+ }
+
+ auto& content_stream = outcome.result().Content();
+ out << content_stream->rdbuf();
+
+ if (!out.good()) {
+ return Status::IOError("failed to write to temp file: {}", temp_file_path);
+ }
+
+ out.close();
+ if (!out) {
+ return Status::IOError("failed to close temp file: {}", temp_file_path);
+ }
+
+ // Atomically rename temp file to target file
+ std::error_code ec;
+ std::filesystem::rename(temp_file_path, local_file.native(), ec);
+ if (ec) {
+ return Status::IOError("failed to rename temp file {} to {}: {}", temp_file_path,
+ local_file.native(), ec.message());
+ }
+
+ temp_guard.success = true; // Prevent cleanup of successfully renamed file
+ return Status::OK();
+}
+
+} // namespace doris::io
diff --git a/be/src/io/fs/oss_file_system.h b/be/src/io/fs/oss_file_system.h
new file mode 100644
index 00000000000..fc1c6256709
--- /dev/null
+++ b/be/src/io/fs/oss_file_system.h
@@ -0,0 +1,140 @@
+// 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.
+
+#pragma once
+
+#include <filesystem>
+#include <memory>
+#include <shared_mutex>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "common/status.h"
+#include "io/fs/file_reader_writer_fwd.h"
+#include "io/fs/path.h"
+#include "io/fs/remote_file_system.h"
+#include "util/oss_util.h"
+
+// Forward declare OSS SDK types
+namespace AlibabaCloud {
+namespace OSS {
+class OssClient;
+} // namespace OSS
+} // namespace AlibabaCloud
+
+namespace doris::io {
+
+// OSSClientHolder holds a shared OSS client and provides thread-safe access
+// In runtime, AK and SK may be modified via vault updates, and the original OssClient will be replaced.
+// The OSSFileReader cached by the Segment must hold a shared OSSClientHolder in order to
+// access OSS data with latest credentials.
+class OSSClientHolder {
+public:
+ explicit OSSClientHolder(OSSClientConf conf);
+ ~OSSClientHolder();
+
+ Status init();
+
+ // Update OSS conf and reset client if `conf` is different. This method is threadsafe.
+ Status reset(const OSSClientConf& conf);
+
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> get() const {
+ std::shared_lock lock(_mtx);
+ return _client;
+ }
+
+ Result<int64_t> object_file_size(const std::string& bucket, const std::string& key) const;
+
+ // For error msg
+ std::string full_oss_path(std::string_view bucket, std::string_view key) const;
+
+ const OSSClientConf& oss_client_conf() { return _conf; }
+
+private:
+ mutable std::shared_mutex _mtx;
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> _client;
+ OSSClientConf _conf;
+};
+
+// File system for Alibaba Cloud OSS (Object Storage Service)
+// When creating OSSFileSystem, all required info should be set in OSSConf,
+// such as ak, sk, region, endpoint, bucket.
+// And the root_path of OSSFileSystem is oss_conf.prefix.
+// When using OSSFileSystem, it accepts 2 kinds of path:
+// 1. Full path: oss://bucket/path/to/file.txt
+// In this case, the root_path is not used.
+// 2. only key: path/to/file.txt
+// In this case, the final key will be "prefix + path/to/file.txt"
+class OSSFileSystem final : public RemoteFileSystem {
+public:
+ static Result<std::shared_ptr<OSSFileSystem>> create(OSSConf oss_conf, std::string id);
+
+ ~OSSFileSystem() override;
+
+ const std::shared_ptr<OSSClientHolder>& client_holder() const { return _client; }
+
+ const std::string& bucket() const { return _bucket; }
+ const std::string& prefix() const { return _prefix; }
+
+protected:
+ Status create_file_impl(const Path& file, FileWriterPtr* writer,
+ const FileWriterOptions* opts) override;
+ Status open_file_internal(const Path& file, FileReaderSPtr* reader,
+ const FileReaderOptions& opts) override;
+ Status create_directory_impl(const Path& dir, bool failed_if_exists = false) override;
+ Status delete_file_impl(const Path& file) override;
+ Status delete_directory_impl(const Path& dir) override;
+ Status batch_delete_impl(const std::vector<Path>& files) override;
+ Status exists_impl(const Path& path, bool* res) const override;
+ Status file_size_impl(const Path& file, int64_t* file_size) const override;
+ Status list_impl(const Path& dir, bool only_file, std::vector<FileInfo>* files,
+ bool* exists) override;
+ Status rename_impl(const Path& orig_name, const Path& new_name) override;
+
+ Status upload_impl(const Path& local_file, const Path& remote_file) override;
+ Status batch_upload_impl(const std::vector<Path>& local_files,
+ const std::vector<Path>& remote_files) override;
+ Status download_impl(const Path& remote_file, const Path& local_file) override;
+
+ Status absolute_path(const Path& path, Path& abs_path) const override {
+ if (path.string().find("://") != std::string::npos) {
+ // the path is with schema, which means this is a full path like:
+ // oss://bucket/path/to/file.txt
+ // so no need to concat with prefix
+ abs_path = path;
+ } else {
+ // path with no schema
+ abs_path = _prefix / path;
+ }
+ return Status::OK();
+ }
+
+private:
+ OSSFileSystem(OSSConf oss_conf, std::string id);
+
+ Status init();
+
+ // For error msg
+ std::string full_oss_path(std::string_view key) const;
+
+ std::string _bucket;
+ std::string _prefix;
+ std::shared_ptr<OSSClientHolder> _client;
+};
+
+} // namespace doris::io
diff --git a/be/src/io/fs/oss_file_writer.cpp b/be/src/io/fs/oss_file_writer.cpp
new file mode 100644
index 00000000000..44a9213ec67
--- /dev/null
+++ b/be/src/io/fs/oss_file_writer.cpp
@@ -0,0 +1,515 @@
+// 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 "io/fs/oss_file_writer.h"
+
+#include <alibabacloud/oss/OssClient.h>
+#include <bvar/reducer.h>
+#include <fmt/format.h>
+#include <glog/logging.h>
+
+#include <algorithm>
+#include <sstream>
+
+#include "common/config.h"
+#include "common/status.h"
+#include "io/cache/file_cache_common.h"
+#include "io/fs/file_writer.h"
+#include "io/fs/path.h"
+#include "io/fs/s3_file_bufferpool.h"
+#include "runtime/exec_env.h"
+#include "util/debug_points.h"
+#include "common/compile_check_begin.h"
+
+namespace doris::io {
+
+// Existing metrics
+bvar::Adder<uint64_t> oss_file_writer_total("oss_file_writer_total_num");
+bvar::Adder<uint64_t> oss_bytes_written_total("oss_file_writer_bytes_written");
+bvar::Adder<uint64_t> oss_file_created_total("oss_file_writer_file_created");
+bvar::Adder<uint64_t> oss_file_being_written("oss_file_writer_file_being_written");
+
+// New async metrics
+bvar::Adder<int64_t> oss_file_writer_async_close_queuing("oss_file_writer_async_close_queuing");
+bvar::Adder<int64_t> oss_file_writer_async_close_processing(
+ "oss_file_writer_async_close_processing");
+
+OSSFileWriter::OSSFileWriter(std::shared_ptr<OSSClientHolder> client, std::string bucket,
+ std::string key, const FileWriterOptions* opts)
+ : _path(fmt::format("oss://{}/{}", bucket, key)),
+ _bucket(std::move(bucket)),
+ _key(std::move(key)),
+ _client(std::move(client)),
+ _buffer_size(config::s3_write_buffer_size),
+ _used_by_oss_committer(opts ? opts->used_by_s3_committer : false) {
+ oss_file_writer_total << 1;
+ oss_file_being_written << 1;
+
+ _completed_parts.reserve(100);
+
+ init_cache_builder(opts, _path);
+}
+
+OSSFileWriter::~OSSFileWriter() {
+ // Wait for async close task or pending part uploads to complete before destruction.
+ if (_async_close_pack != nullptr) {
+ std::ignore = _async_close_pack->future.get();
+ _async_close_pack = nullptr;
+ } else {
+ _wait_until_finish("~OSSFileWriter");
+ }
+
+ // Abort multipart upload if not completed
+ if (state() != State::CLOSED && !_upload_id.empty()) {
+ LOG(WARNING) << "OSSFileWriter destroyed without close(), aborting multipart upload: "
+ << _path.native() << " upload_id: " << _upload_id;
+ static_cast<void>(_abort_multipart_upload());
+ }
+
+ if (state() == State::OPENED && !_failed) {
+ oss_bytes_written_total << _bytes_appended;
+ }
+ oss_file_being_written << -1;
+}
+
+Status OSSFileWriter::appendv(const Slice* data, size_t data_cnt) {
+ if (state() != State::OPENED) {
+ return Status::InternalError("append to closed file: {}", _path.native());
+ }
+
+ for (size_t i = 0; i < data_cnt; i++) {
+ size_t data_size = data[i].size;
+ const char* data_ptr = data[i].data;
+ size_t pos = 0;
+
+ while (pos < data_size) {
+ if (_failed) {
+ return _st;
+ }
+
+ // Create new buffer if needed
+ if (!_pending_buf) {
+ RETURN_IF_ERROR(_build_upload_buffer());
+ }
+
+ size_t remaining = data_size - pos;
+ size_t buffer_remaining = _buffer_size - _pending_buf->get_size();
+ size_t to_append = std::min(remaining, buffer_remaining);
+
+ Slice s(data_ptr + pos, to_append);
+ RETURN_IF_ERROR(_pending_buf->append_data(s));
+
+ pos += to_append;
+ _bytes_appended += to_append;
+
+ if (_pending_buf->get_size() == _buffer_size) {
+ // Create multipart upload on first buffer flush
+ if (_cur_part_num == 1) {
+ RETURN_IF_ERROR(_create_multipart_upload());
+ }
+
+ _cur_part_num++;
+ _countdown_event.add_count();
+ RETURN_IF_ERROR(FileBuffer::submit(std::move(_pending_buf)));
+ _pending_buf = nullptr;
+ }
+ }
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileWriter::_build_upload_buffer() {
+ auto builder = FileBufferBuilder();
+ builder.set_type(BufferType::UPLOAD)
+ .set_upload_callback([part_num = _cur_part_num, this](UploadFileBuffer& buf) {
+ _upload_one_part(part_num, buf);
+ })
+ .set_file_offset(_bytes_appended)
+ .set_sync_after_complete_task([this](auto&& s) {
+ return _complete_part_task_callback(std::forward<decltype(s)>(s));
+ })
+ .set_is_cancelled([this]() { return _failed.load(); });
+
+ if (cache_builder() != nullptr) {
+ int64_t tablet_id = get_tablet_id(_path.native()).value_or(0);
+ builder.set_allocate_file_blocks_holder(
+ [builder = *cache_builder(),
+ offset = _bytes_appended,
+ tablet_id]() -> FileBlocksHolderPtr {
+ return builder.allocate_cache_holder(offset, config::s3_write_buffer_size,
+ tablet_id);
+ });
+ }
+
+ RETURN_IF_ERROR(builder.build(&_pending_buf));
+ return Status::OK();
+}
+
+void OSSFileWriter::_upload_one_part(int64_t part_num, UploadFileBuffer& buf) {
+ if (buf.is_cancelled()) {
+ LOG(INFO) << "OSS file " << _path.native() << " skip part " << part_num
+ << " because previous failure";
+ return;
+ }
+
+ // Debug point: Simulate upload failure
+ DBUG_EXECUTE_IF("OSSFileWriter::_upload_one_part.upload_error", {
+ auto fail_part = dp->param<int64_t>("fail_part_num", 0);
+ if (fail_part == 0 || fail_part == part_num) {
+ LOG(WARNING) << "Debug point: Simulating OSS upload failure for part " << part_num;
+ buf.set_status(Status::IOError("Debug OSS upload error for part {}", part_num));
+ return;
+ }
+ });
+
+ // Debug point: Simulate slow upload
+ DBUG_EXECUTE_IF("OSSFileWriter::_upload_one_part.slow_upload", {
+ auto sleep_ms = dp->param<int>("sleep_ms", 1000);
+ LOG(INFO) << "Debug point: Simulating slow OSS upload, sleeping " << sleep_ms << "ms";
+ std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
+ });
+
+ auto client = _client->get();
+ if (nullptr == client) {
+ buf.set_status(Status::InternalError("OSS client not initialized"));
+ return;
+ }
+
+ auto stream = buf.get_stream();
+ if (!stream) {
+ buf.set_status(Status::InternalError("Failed to get stream from upload buffer for part {}",
+ part_num));
+ return;
+ }
+
+ AlibabaCloud::OSS::UploadPartRequest request(_bucket, _key, stream);
+ request.setPartNumber(static_cast<int32_t>(part_num));
+ request.setUploadId(_upload_id);
+ request.setContentLength(buf.get_size());
+
+ auto outcome = client->UploadPart(request);
+ if (!outcome.isSuccess()) {
+ std::string err = fmt::format("OSS UploadPart {} failed: {} - {}", part_num,
+ outcome.error().Code(), outcome.error().Message());
+ LOG(WARNING) << err << ", path: " << _path.native();
+ buf.set_status(Status::IOError(err));
+ return;
+ }
+
+ oss_bytes_written_total << buf.get_size();
+
+ AlibabaCloud::OSS::Part part(static_cast<int32_t>(part_num), outcome.result().ETag());
+
+ {
+ std::lock_guard<std::mutex> lock(_completed_lock);
+ _completed_parts.push_back(part);
+ }
+
+ VLOG_DEBUG << "OSS UploadPart " << part_num << " completed: " << _path.native()
+ << " size: " << buf.get_size();
+}
+
+bool OSSFileWriter::_complete_part_task_callback(Status s) {
+ if (!s.ok()) {
+ std::unique_lock<std::mutex> lck {_completed_lock};
+ _failed = true;
+ _st = std::move(s);
+ LOG(WARNING) << "OSS async upload failed: " << _path.native() << " error: " << _st;
+ }
+ _countdown_event.signal();
+ return !s.ok();
+}
+
+void OSSFileWriter::_wait_until_finish(std::string_view task_name) {
+ auto timeout_duration = config::s3_file_writer_log_interval_second;
+ auto msg = fmt::format("OSS file {} still has unfinished async tasks: {}", _path.native(),
+ task_name);
+ timespec current_time;
+ auto current_time_second = time(nullptr);
+ current_time.tv_sec = current_time_second + timeout_duration;
+ current_time.tv_nsec = 0;
+
+ while (0 != _countdown_event.timed_wait(current_time)) {
+ current_time.tv_sec += timeout_duration;
+ LOG(WARNING) << msg;
+ }
+}
+
+Status OSSFileWriter::_create_multipart_upload() {
+ auto client = _client->get();
+ if (!client) {
+ return Status::InternalError("OSS client not initialized");
+ }
+
+ AlibabaCloud::OSS::InitiateMultipartUploadRequest request(_bucket, _key);
+ auto outcome = client->InitiateMultipartUpload(request);
+
+ if (!outcome.isSuccess()) {
+ std::string err = fmt::format("OSS InitiateMultipartUpload failed: {} - {}",
+ outcome.error().Code(), outcome.error().Message());
+ LOG(WARNING) << err << ", path: " << _path.native();
+ return Status::IOError(err);
+ }
+
+ _upload_id = outcome.result().UploadId();
+ LOG(INFO) << "OSS multipart upload initiated: " << _path.native()
+ << " upload_id: " << _upload_id;
+
+ return Status::OK();
+}
+
+Status OSSFileWriter::_complete_multipart_upload() {
+ auto client = _client->get();
+ if (!client) {
+ return Status::InternalError("OSS client not initialized");
+ }
+
+ // Debug point: Simulate complete multipart failure
+ DBUG_EXECUTE_IF("OSSFileWriter::_complete_multipart_upload.complete_error", {
+ LOG(WARNING) << "Debug point: Simulating OSS complete multipart upload failure";
+ _failed = true;
+ return Status::IOError("Debug OSS complete multipart upload error for path {}",
+ _path.native());
+ });
+
+ // CRITICAL: Sort parts by part number (OSS requires ascending order)
+ std::sort(_completed_parts.begin(), _completed_parts.end(),
+ [](const AlibabaCloud::OSS::Part& a, const AlibabaCloud::OSS::Part& b) {
+ return a.PartNumber() < b.PartNumber();
+ });
+
+ AlibabaCloud::OSS::CompleteMultipartUploadRequest request(_bucket, _key, _completed_parts,
+ _upload_id);
+ auto outcome = client->CompleteMultipartUpload(request);
+
+ if (!outcome.isSuccess()) {
+ _failed = true;
+ std::string err = fmt::format("OSS CompleteMultipartUpload failed: {} - {}",
+ outcome.error().Code(), outcome.error().Message());
+ LOG(WARNING) << err << ", path: " << _path.native();
+ static_cast<void>(_abort_multipart_upload());
+ return Status::IOError(err);
+ }
+
+ LOG(INFO) << "OSS multipart upload completed: " << _path.native()
+ << " parts: " << _completed_parts.size() << " bytes: " << _bytes_appended;
+
+ oss_file_created_total << 1;
+ return Status::OK();
+}
+
+Status OSSFileWriter::_abort_multipart_upload() {
+ if (_upload_id.empty()) {
+ return Status::OK();
+ }
+
+ auto client = _client->get();
+ if (!client) {
+ return Status::InternalError("OSS client not initialized");
+ }
+
+ AlibabaCloud::OSS::AbortMultipartUploadRequest request(_bucket, _key, _upload_id);
+ auto outcome = client->AbortMultipartUpload(request);
+
+ if (!outcome.isSuccess()) {
+ std::string err = fmt::format("OSS AbortMultipartUpload failed: {} - {}",
+ outcome.error().Code(), outcome.error().Message());
+ LOG(WARNING) << err << ", path: " << _path.native() << " upload_id: " << _upload_id;
+ return Status::IOError(err);
+ }
+
+ LOG(INFO) << "OSS multipart upload aborted: " << _path.native() << " upload_id: " << _upload_id;
+ _upload_id.clear();
+
+ return Status::OK();
+}
+
+Status OSSFileWriter::_put_object(UploadFileBuffer& buf) {
+ auto client = _client->get();
+ if (!client) {
+ return Status::InternalError("OSS client not initialized");
+ }
+
+ auto stream = buf.get_stream();
+ if (!stream) {
+ return Status::InternalError("Failed to get stream from upload buffer");
+ }
+
+ AlibabaCloud::OSS::PutObjectRequest request(_bucket, _key, stream);
+ auto outcome = client->PutObject(request);
+
+ if (!outcome.isSuccess()) {
+ _failed = true;
+ std::string err = fmt::format("OSS PutObject failed: {} - {}", outcome.error().Code(),
+ outcome.error().Message());
+ LOG(WARNING) << err << ", path: " << _path.native();
+ return Status::IOError(err);
+ }
+
+ LOG(INFO) << "OSS PutObject completed: " << _path.native() << " size: " << buf.get_size();
+
+ oss_file_created_total << 1;
+ oss_bytes_written_total << buf.get_size();
+
+ return Status::OK();
+}
+
+Status OSSFileWriter::_set_upload_to_remote_less_than_buffer_size() {
+ auto* buf = dynamic_cast<UploadFileBuffer*>(_pending_buf.get());
+ if (buf == nullptr) {
+ return Status::InternalError(
+ "Invalid buffer type in _set_upload_to_remote_less_than_buffer_size: expected "
+ "UploadFileBuffer");
+ }
+
+ if (_used_by_oss_committer) {
+ // Committer mode: use multipart (FE needs upload_id and part ETags)
+ buf->set_upload_to_remote([part_num = _cur_part_num, this](UploadFileBuffer& buf) {
+ _upload_one_part(part_num, buf);
+ });
+ DCHECK(_cur_part_num == 1);
+ RETURN_IF_ERROR(_create_multipart_upload());
+ } else {
+ // Normal mode: use PutObject for small files
+ buf->set_upload_to_remote([this](UploadFileBuffer& buf) {
+ Status st = _put_object(buf);
+ if (!st.ok()) {
+ buf.set_status(st);
+ }
+ });
+ }
+
+ return Status::OK();
+}
+
+Status OSSFileWriter::close(bool non_block) {
+ std::lock_guard<std::mutex> lock(_close_lock);
+
+ if (state() == State::CLOSED) {
+ return _st;
+ }
+
+ if (state() == State::ASYNC_CLOSING) {
+ if (non_block) {
+ return Status::InternalError("Don't submit async close multiple times");
+ }
+ CHECK(_async_close_pack != nullptr);
+ _st = _async_close_pack->future.get();
+ _async_close_pack = nullptr;
+ _state = State::CLOSED;
+ return _st;
+ }
+
+ if (non_block) {
+ _state = State::ASYNC_CLOSING;
+ _async_close_pack = std::make_unique<AsyncCloseStatusPack>();
+ _async_close_pack->future = _async_close_pack->promise.get_future();
+
+ oss_file_writer_async_close_queuing << 1;
+
+ return ExecEnv::GetInstance()->non_block_close_thread_pool()->submit_func([this]() {
+ oss_file_writer_async_close_queuing << -1;
+ oss_file_writer_async_close_processing << 1;
+ _async_close_pack->promise.set_value(_close_impl());
+ oss_file_writer_async_close_processing << -1;
+ });
+ }
+
+ _st = _close_impl();
+ _state = State::CLOSED;
+ return _st;
+}
+
+Status OSSFileWriter::_close_impl() {
+ // Wait for any pending async operations to complete
+ _wait_until_finish("_close_impl");
+
+ if (_failed) {
+ if (!_upload_id.empty()) {
+ static_cast<void>(_abort_multipart_upload());
+ }
+ return _st;
+ }
+
+ if (_bytes_appended == 0) {
+ DCHECK_EQ(_cur_part_num, 1);
+ // Create an empty buffer for PutObject
+ RETURN_IF_ERROR(_build_upload_buffer());
+
+ if (!_used_by_oss_committer) {
+ auto* pending_buf = dynamic_cast<UploadFileBuffer*>(_pending_buf.get());
+ DCHECK(pending_buf != nullptr);
+ pending_buf->set_upload_to_remote([this](UploadFileBuffer& buf) {
+ Status st = _put_object(buf);
+ if (!st.ok()) {
+ buf.set_status(st);
+ }
+ });
+ } else {
+ RETURN_IF_ERROR(_create_multipart_upload());
+ }
+ }
+
+ if (_cur_part_num == 1 && _pending_buf) {
+ RETURN_IF_ERROR(_set_upload_to_remote_less_than_buffer_size());
+ }
+
+ if (_pending_buf && _pending_buf->get_size() > 0) {
+ _countdown_event.add_count();
+ Status st = FileBuffer::submit(std::move(_pending_buf));
+ _pending_buf = nullptr;
+ if (!st.ok()) {
+ if (!_upload_id.empty()) {
+ static_cast<void>(_abort_multipart_upload());
+ }
+ return st;
+ }
+
+ _wait_until_finish("last_part");
+
+ if (_failed) {
+ if (!_upload_id.empty()) {
+ static_cast<void>(_abort_multipart_upload());
+ }
+ return _st;
+ }
+ }
+
+ if (_cur_part_num == 1) {
+ _wait_until_finish("PutObject or single part");
+ return _st;
+ }
+
+ _wait_until_finish("Complete multipart");
+
+ if (_used_by_oss_committer) {
+ // OSS committer mode: FE will complete multipart upload
+ oss_file_created_total << 1;
+ LOG(INFO) << "OSS multipart upload parts completed (FE will finish): " << _path.native()
+ << " parts: " << _completed_parts.size() << " bytes: " << _bytes_appended
+ << " upload_id: " << _upload_id;
+ return Status::OK();
+ }
+
+ // TODO: add check_after_upload like S3 (off by default via config)
+ return _complete_multipart_upload();
+}
+
+#include "common/compile_check_end.h"
+
+} // namespace doris::io
diff --git a/be/src/io/fs/oss_file_writer.h b/be/src/io/fs/oss_file_writer.h
new file mode 100644
index 00000000000..76119c1b06f
--- /dev/null
+++ b/be/src/io/fs/oss_file_writer.h
@@ -0,0 +1,98 @@
+// 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.
+
+#pragma once
+
+#include <alibabacloud/oss/model/Part.h>
+#include <bthread/countdown_event.h>
+
+#include <atomic>
+#include <future>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+#include "common/status.h"
+#include "io/fs/file_writer.h"
+#include "io/fs/oss_file_system.h"
+#include "io/fs/path.h"
+#include "io/fs/s3_file_bufferpool.h"
+
+namespace doris::io {
+
+class OSSFileWriter final : public FileWriter {
+public:
+ OSSFileWriter(std::shared_ptr<OSSClientHolder> client, std::string bucket, std::string key,
+ const FileWriterOptions* opts);
+ ~OSSFileWriter() override;
+
+ Status appendv(const Slice* data, size_t data_cnt) override;
+
+ const Path& path() const override { return _path; }
+ size_t bytes_appended() const override { return _bytes_appended; }
+ State state() const override { return _state; }
+
+ Status close(bool non_block = false) override;
+
+private:
+ Status _close_impl();
+ Status _create_multipart_upload();
+
+ void _upload_one_part(int64_t part_num, UploadFileBuffer& buf);
+
+ Status _complete_multipart_upload();
+ Status _abort_multipart_upload();
+ Status _put_object(UploadFileBuffer& buf);
+
+ Status _build_upload_buffer();
+
+ bool _complete_part_task_callback(Status s);
+
+ Status _set_upload_to_remote_less_than_buffer_size();
+
+ void _wait_until_finish(std::string_view task_name);
+
+ Path _path;
+ std::string _bucket;
+ std::string _key;
+ std::shared_ptr<OSSClientHolder> _client;
+
+ std::string _upload_id;
+ int64_t _cur_part_num = 1;
+ std::vector<AlibabaCloud::OSS::Part> _completed_parts;
+ std::mutex _completed_lock;
+
+ std::shared_ptr<FileBuffer> _pending_buf;
+ size_t _buffer_size;
+ size_t _bytes_appended = 0;
+
+ bthread::CountdownEvent _countdown_event {0};
+
+ std::unique_ptr<AsyncCloseStatusPack> _async_close_pack;
+
+ std::mutex _close_lock;
+
+ // OSS committer mode: FE completes multipart upload
+ bool _used_by_oss_committer;
+
+ State _state {State::OPENED};
+ std::atomic_bool _failed {false};
+ Status _st;
+};
+
+} // namespace doris::io
diff --git a/be/src/io/fs/oss_v2_obj_storage_client.cpp b/be/src/io/fs/oss_v2_obj_storage_client.cpp
new file mode 100644
index 00000000000..7390b699fd7
--- /dev/null
+++ b/be/src/io/fs/oss_v2_obj_storage_client.cpp
@@ -0,0 +1,443 @@
+// 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 "io/fs/oss_v2_obj_storage_client.h"
+
+#ifdef USE_OSS
+
+#include <alibabacloud/oss/OssClient.h>
+#include <fmt/format.h>
+#include <glog/logging.h>
+
+#include <algorithm>
+#include <ctime>
+#include <iostream>
+#include <streambuf>
+#include <string>
+#include <vector>
+
+#include "common/config.h"
+#include "common/status.h"
+#include "io/fs/file_system.h"
+#include "io/fs/obj_storage_client.h"
+#include "util/bvar_helper.h"
+#include "util/oss_util.h"
+#include "util/s3_util.h"
+
+namespace doris::io {
+
+namespace {
+
+// Read-only iostream wrapper around an existing buffer (no AWS SDK dependency).
+class OSSStringViewStream : public std::streambuf, public std::iostream {
+public:
+ OSSStringViewStream(const char* data, size_t size) : std::streambuf(), std::iostream(this) {
+ // const_cast is safe: read-only streambuf (get-area only, no put-area).
+ char* p = const_cast<char*>(data);
+ setg(p, p, p + size);
+ }
+};
+
+// Rate limiting helpers — reuse shared S3RateLimiter infrastructure (parallel to s3_obj_storage_client.cpp).
+inline AlibabaCloud::OSS::OssError oss_rate_limit_error() {
+ return {"ExceedsRateLimit", "request rate exceeds configured limit"};
+}
+
+template <typename Func>
+auto oss_rate_limit(doris::S3RateLimitType op, Func callback) -> decltype(callback()) {
+ using T = decltype(callback());
+ if (!doris::config::enable_s3_rate_limiter) {
+ return callback();
+ }
+ auto sleep_duration = doris::S3ClientFactory::instance().rate_limiter(op)->add(1);
+ if (sleep_duration < 0) {
+ return T(oss_rate_limit_error());
+ }
+ return callback();
+}
+
+template <typename Func>
+auto oss_get_rate_limit(Func callback) -> decltype(callback()) {
+ return oss_rate_limit(doris::S3RateLimitType::GET, std::move(callback));
+}
+
+template <typename Func>
+auto oss_put_rate_limit(Func callback) -> decltype(callback()) {
+ return oss_rate_limit(doris::S3RateLimitType::PUT, std::move(callback));
+}
+
+// Build a failed ObjectStorageResponse from an OSS error
+inline ObjectStorageResponse oss_error_response(const std::string& op, const std::string& bucket,
+ const std::string& key, const std::string& code,
+ const std::string& msg) {
+ ObjectStorageResponse resp;
+ resp.status.code = -1;
+ resp.status.msg = fmt::format("OSS {} failed [{}/{}]: {} - {}", op, bucket, key, code, msg);
+ return resp;
+}
+
+// OssError has no HTTP status code; Code() string is the only discriminator.
+inline ObjectStorageHeadResponse oss_head_error_response(const std::string& bucket,
+ const std::string& key,
+ const std::string& code,
+ const std::string& msg) {
+ if (code == "NoSuchKey") {
+ return {.resp = {convert_to_obj_response(Status::Error<ErrorCode::NOT_FOUND, false>(""))}};
+ }
+ ObjectStorageHeadResponse r;
+ r.resp.status.code = -1;
+ r.resp.status.msg =
+ fmt::format("OSS HeadObject failed [{}/{}]: {} - {}", bucket, key, code, msg);
+ return r;
+}
+
+} // namespace
+
+OSSv2ObjStorageClient::OSSv2ObjStorageClient(std::shared_ptr<AlibabaCloud::OSS::OssClient> client,
+ std::string bucket)
+ : _client(std::move(client)), _bucket(std::move(bucket)) {}
+
+// ----------------------------------------------------------------------------
+// create_multipart_upload
+// ----------------------------------------------------------------------------
+ObjectStorageUploadResponse OSSv2ObjStorageClient::create_multipart_upload(
+ const ObjectStoragePathOptions& opts) {
+ ObjectStorageUploadResponse resp;
+ const std::string& bucket = resolve_bucket(opts);
+
+ AlibabaCloud::OSS::InitiateMultipartUploadRequest request(bucket, opts.key);
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_multi_part_upload_latency);
+ auto outcome = oss_put_rate_limit([&]() { return _client->InitiateMultipartUpload(request); });
+
+ if (!outcome.isSuccess()) {
+ resp.resp = oss_error_response("InitiateMultipartUpload", bucket, opts.key,
+ outcome.error().Code(), outcome.error().Message());
+ LOG(WARNING) << resp.resp.status.msg;
+ return resp;
+ }
+
+ resp.upload_id = outcome.result().UploadId();
+ VLOG(2) << "OSS InitiateMultipartUpload: " << bucket << "/" << opts.key
+ << " upload_id=" << *resp.upload_id;
+ return resp;
+}
+
+// ----------------------------------------------------------------------------
+// put_object
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::put_object(const ObjectStoragePathOptions& opts,
+ std::string_view stream) {
+ const std::string& bucket = resolve_bucket(opts);
+ auto content = std::make_shared<OSSStringViewStream>(stream.data(), stream.size());
+
+ AlibabaCloud::OSS::PutObjectRequest request(bucket, opts.key, content);
+ request.MetaData().setContentLength(static_cast<int64_t>(stream.size()));
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_put_latency);
+ auto outcome = oss_put_rate_limit([&]() { return _client->PutObject(request); });
+
+ if (!outcome.isSuccess()) {
+ return oss_error_response("PutObject", bucket, opts.key, outcome.error().Code(),
+ outcome.error().Message());
+ }
+
+ VLOG(2) << "OSS PutObject: " << bucket << "/" << opts.key << " size=" << stream.size();
+ return ObjectStorageResponse::OK();
+}
+
+// ----------------------------------------------------------------------------
+// upload_part
+// ----------------------------------------------------------------------------
+ObjectStorageUploadResponse OSSv2ObjStorageClient::upload_part(const ObjectStoragePathOptions& opts,
+ std::string_view stream,
+ int part_num) {
+ ObjectStorageUploadResponse resp;
+ const std::string& bucket = resolve_bucket(opts);
+
+ if (!opts.upload_id.has_value()) {
+ resp.resp.status.code = -1;
+ resp.resp.status.msg = "upload_id is required for OSS UploadPart";
+ return resp;
+ }
+
+ auto content = std::make_shared<OSSStringViewStream>(stream.data(), stream.size());
+
+ AlibabaCloud::OSS::UploadPartRequest request(bucket, opts.key, content);
+ request.setPartNumber(part_num);
+ request.setUploadId(*opts.upload_id);
+ request.setContentLength(static_cast<uint64_t>(stream.size()));
+
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_multi_part_upload_latency);
+ auto outcome = oss_put_rate_limit([&]() { return _client->UploadPart(request); });
+
+ if (!outcome.isSuccess()) {
+ resp.resp = oss_error_response("UploadPart", bucket, opts.key, outcome.error().Code(),
+ outcome.error().Message());
+ LOG(WARNING) << resp.resp.status.msg;
+ return resp;
+ }
+
+ resp.etag = outcome.result().ETag();
+ VLOG(2) << "OSS UploadPart " << part_num << ": " << bucket << "/" << opts.key
+ << " etag=" << *resp.etag;
+ return resp;
+}
+
+// ----------------------------------------------------------------------------
+// complete_multipart_upload
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::complete_multipart_upload(
+ const ObjectStoragePathOptions& opts,
+ const std::vector<ObjectCompleteMultiPart>& completed_parts) {
+ const std::string& bucket = resolve_bucket(opts);
+
+ if (!opts.upload_id.has_value()) {
+ return oss_error_response("CompleteMultipartUpload", bucket, opts.key, "InvalidArgument",
+ "upload_id is required");
+ }
+
+ AlibabaCloud::OSS::PartList part_list;
+ part_list.reserve(completed_parts.size());
+ for (const auto& part : completed_parts) {
+ part_list.emplace_back(part.part_num, part.etag);
+ }
+ // Server requires ascending part-number order; SDK does not enforce this locally.
+ std::sort(part_list.begin(), part_list.end(),
+ [](const AlibabaCloud::OSS::Part& a, const AlibabaCloud::OSS::Part& b) {
+ return a.PartNumber() < b.PartNumber();
+ });
+
+ AlibabaCloud::OSS::CompleteMultipartUploadRequest request(bucket, opts.key, part_list,
+ *opts.upload_id);
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_multi_part_upload_latency);
+ auto outcome = oss_put_rate_limit([&]() { return _client->CompleteMultipartUpload(request); });
+
+ if (!outcome.isSuccess()) {
+ return oss_error_response("CompleteMultipartUpload", bucket, opts.key,
+ outcome.error().Code(), outcome.error().Message());
+ }
+
+ VLOG(1) << "OSS CompleteMultipartUpload: " << bucket << "/" << opts.key
+ << " parts=" << completed_parts.size();
+ return ObjectStorageResponse::OK();
+}
+
+// ----------------------------------------------------------------------------
+// head_object
+// ----------------------------------------------------------------------------
+ObjectStorageHeadResponse OSSv2ObjStorageClient::head_object(const ObjectStoragePathOptions& opts) {
+ ObjectStorageHeadResponse resp;
+ const std::string& bucket = resolve_bucket(opts);
+
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_head_latency);
+ auto outcome = oss_get_rate_limit([&]() { return _client->HeadObject(bucket, opts.key); });
+
+ if (!outcome.isSuccess()) {
+ return oss_head_error_response(bucket, opts.key, outcome.error().Code(),
+ outcome.error().Message());
+ }
+
+ resp.file_size = outcome.result().ContentLength();
+ return resp;
+}
+
+// ----------------------------------------------------------------------------
+// get_object
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::get_object(const ObjectStoragePathOptions& opts,
+ void* buffer, size_t offset,
+ size_t bytes_read, size_t* size_return) {
+ const std::string& bucket = resolve_bucket(opts);
+
+ if (bytes_read == 0) {
+ *size_return = 0;
+ return ObjectStorageResponse::OK();
+ }
+
+ AlibabaCloud::OSS::GetObjectRequest request(bucket, opts.key);
+ request.setRange(static_cast<int64_t>(offset), static_cast<int64_t>(offset + bytes_read - 1));
+
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_get_latency);
+ auto outcome = oss_get_rate_limit([&]() { return _client->GetObject(request); });
+
+ if (!outcome.isSuccess()) {
+ return oss_error_response("GetObject", bucket, opts.key, outcome.error().Code(),
+ outcome.error().Message());
+ }
+
+ auto& content = outcome.result().Content();
+ content->read(static_cast<char*>(buffer), static_cast<std::streamsize>(bytes_read));
+ *size_return = static_cast<size_t>(content->gcount());
+ return ObjectStorageResponse::OK();
+}
+
+// ----------------------------------------------------------------------------
+// list_objects
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::list_objects(const ObjectStoragePathOptions& opts,
+ std::vector<FileInfo>* files) {
+ const std::string& bucket = resolve_bucket(opts);
+ bool is_truncated = true;
+ std::string marker;
+
+ while (is_truncated) {
+ AlibabaCloud::OSS::ListObjectsRequest request(bucket);
+ request.setPrefix(opts.prefix);
+ request.setMaxKeys(1000);
+ if (!marker.empty()) {
+ request.setMarker(marker);
+ }
+
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_list_latency);
+ auto outcome = oss_get_rate_limit([&]() { return _client->ListObjects(request); });
+ if (!outcome.isSuccess()) {
+ return oss_error_response("ListObjects", bucket, opts.prefix, outcome.error().Code(),
+ outcome.error().Message());
+ }
+
+ const auto& result = outcome.result();
+ for (const auto& obj : result.ObjectSummarys()) {
+ FileInfo fi;
+ fi.file_name = obj.Key();
+ fi.file_size = obj.Size();
+ fi.is_file = true;
+ files->push_back(std::move(fi));
+ }
+
+ is_truncated = result.IsTruncated();
+ if (is_truncated) {
+ // OSS v1 ListObjects may omit NextMarker without a delimiter; fall back to last key.
+ const auto& summaries = result.ObjectSummarys();
+ marker = result.NextMarker();
+ if (marker.empty() && !summaries.empty()) {
+ marker = summaries.back().Key();
+ }
+ if (marker.empty()) {
+ return oss_error_response("ListObjects", bucket, opts.prefix, "InvalidResponse",
+ "IsTruncated=true but no continuation marker available");
+ }
+ }
+ }
+
+ return ObjectStorageResponse::OK();
+}
+
+// ----------------------------------------------------------------------------
+// delete_objects (batch, up to 1000 per OSS call)
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::delete_objects(const ObjectStoragePathOptions& opts,
+ std::vector<std::string> objs) {
+ if (objs.empty()) {
+ return ObjectStorageResponse::OK();
+ }
+
+ const std::string& bucket = resolve_bucket(opts);
+ constexpr size_t OSS_BATCH_DELETE_LIMIT = 1000;
+
+ for (size_t i = 0; i < objs.size(); i += OSS_BATCH_DELETE_LIMIT) {
+ AlibabaCloud::OSS::DeletedKeyList keys;
+ size_t end = std::min(i + OSS_BATCH_DELETE_LIMIT, objs.size());
+ for (size_t j = i; j < end; ++j) {
+ keys.push_back(objs[j]);
+ }
+
+ AlibabaCloud::OSS::DeleteObjectsRequest request(bucket);
+ request.setKeyList(keys);
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_delete_objects_latency);
+ auto outcome = oss_put_rate_limit([&]() { return _client->DeleteObjects(request); });
+
+ if (!outcome.isSuccess()) {
+ return oss_error_response("DeleteObjects", bucket, opts.prefix, outcome.error().Code(),
+ outcome.error().Message());
+ }
+ // OSS has no per-key error objects in batch delete (unlike S3 GetErrors()).
+ // Detect partial failure via count: keyList() returns confirmed-deleted keys in Verbose mode.
+ const auto& confirmed = outcome.result().keyList();
+ if (confirmed.size() < keys.size()) {
+ LOG(WARNING) << "OSS BatchDelete partial failure: sent " << keys.size()
+ << " keys, only " << confirmed.size() << " confirmed deleted in bucket "
+ << bucket << "; some objects may still exist";
+ }
+ }
+
+ return ObjectStorageResponse::OK();
+}
+
+// ----------------------------------------------------------------------------
+// delete_object (single object, idempotent on NoSuchKey)
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::delete_object(const ObjectStoragePathOptions& opts) {
+ const std::string& bucket = resolve_bucket(opts);
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_delete_object_latency);
+ auto outcome = oss_put_rate_limit([&]() { return _client->DeleteObject(bucket, opts.key); });
+
+ if (!outcome.isSuccess()) {
+ const std::string& code = outcome.error().Code();
+ if (code == "NoSuchKey") {
+ return ObjectStorageResponse::OK(); // idempotent
+ }
+ return oss_error_response("DeleteObject", bucket, opts.key, code,
+ outcome.error().Message());
+ }
+
+ return ObjectStorageResponse::OK();
+}
+
+// ----------------------------------------------------------------------------
+// delete_objects_recursively (list all under prefix then batch delete)
+// ----------------------------------------------------------------------------
+ObjectStorageResponse OSSv2ObjStorageClient::delete_objects_recursively(
+ const ObjectStoragePathOptions& opts) {
+ std::vector<FileInfo> files;
+ if (auto resp = list_objects(opts, &files); resp.status.code != 0) {
+ return resp;
+ }
+ std::vector<std::string> keys;
+ keys.reserve(files.size());
+ for (auto& fi : files) {
+ keys.push_back(std::move(fi.file_name));
+ }
+ return delete_objects(opts, std::move(keys));
+}
+
+// ----------------------------------------------------------------------------
+// generate_presigned_url
+// ----------------------------------------------------------------------------
+std::string OSSv2ObjStorageClient::generate_presigned_url(const ObjectStoragePathOptions& opts,
+ int64_t expiration_secs,
+ const S3ClientConf& /*conf*/) {
+ // `conf` unused: OSS SDK signs with credentials embedded at client construction time.
+ // Unlike S3/Azure, GeneratePresignedUrl does not accept a per-call credential override.
+ const std::string& bucket = resolve_bucket(opts);
+ time_t expiration_time = std::time(nullptr) + static_cast<time_t>(expiration_secs);
+
+ AlibabaCloud::OSS::GeneratePresignedUrlRequest request(bucket, opts.key,
+ AlibabaCloud::OSS::Http::Get);
+ request.setExpires(expiration_time);
+
+ auto outcome = _client->GeneratePresignedUrl(request);
+ if (!outcome.isSuccess()) {
+ LOG(WARNING) << "OSS GeneratePresignedUrl failed [" << bucket << "/" << opts.key
+ << "]: " << outcome.error().Code() << " - " << outcome.error().Message();
+ return "";
+ }
+
+ return outcome.result();
+}
+
+} // namespace doris::io
+
+#endif // USE_OSS
diff --git a/be/src/io/fs/oss_v2_obj_storage_client.h b/be/src/io/fs/oss_v2_obj_storage_client.h
new file mode 100644
index 00000000000..838d017f59b
--- /dev/null
+++ b/be/src/io/fs/oss_v2_obj_storage_client.h
@@ -0,0 +1,93 @@
+// 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.
+
+#pragma once
+
+#ifdef USE_OSS
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "io/fs/obj_storage_client.h"
+
+// Forward declare OSS SDK types to avoid heavy header in .h
+namespace AlibabaCloud {
+namespace OSS {
+class OssClient;
+} // namespace OSS
+} // namespace AlibabaCloud
+
+namespace doris::io {
+
+// OSSv2ObjStorageClient implements ObjStorageClient using the native Alibaba Cloud OSS SDK.
+//
+// This is used for all non-cloud-vault OSS paths where previously the S3-compatible AWS SDK
+// was used (cold/tiered storage, external tables, load/export, CREATE RESOURCE OSS).
+// It is plugged into S3ClientFactory::create() when provider == ObjStorageType::OSS.
+//
+// Cloud vault OSS continues to use OSSFileSystem → OSSClientHolder directly (unchanged).
+class OSSv2ObjStorageClient final : public ObjStorageClient {
+public:
+ OSSv2ObjStorageClient(std::shared_ptr<AlibabaCloud::OSS::OssClient> client, std::string bucket);
+ ~OSSv2ObjStorageClient() override = default;
+
+ ObjectStorageUploadResponse create_multipart_upload(
+ const ObjectStoragePathOptions& opts) override;
+
+ ObjectStorageResponse put_object(const ObjectStoragePathOptions& opts,
+ std::string_view stream) override;
+
+ ObjectStorageUploadResponse upload_part(const ObjectStoragePathOptions& opts,
+ std::string_view stream, int part_num) override;
+
+ ObjectStorageResponse complete_multipart_upload(
+ const ObjectStoragePathOptions& opts,
+ const std::vector<ObjectCompleteMultiPart>& completed_parts) override;
+
+ ObjectStorageHeadResponse head_object(const ObjectStoragePathOptions& opts) override;
+
+ ObjectStorageResponse get_object(const ObjectStoragePathOptions& opts, void* buffer,
+ size_t offset, size_t bytes_read,
+ size_t* size_return) override;
+
+ ObjectStorageResponse list_objects(const ObjectStoragePathOptions& opts,
+ std::vector<FileInfo>* files) override;
+
+ ObjectStorageResponse delete_objects(const ObjectStoragePathOptions& opts,
+ std::vector<std::string> objs) override;
+
+ ObjectStorageResponse delete_object(const ObjectStoragePathOptions& opts) override;
+
+ ObjectStorageResponse delete_objects_recursively(const ObjectStoragePathOptions& opts) override;
+
+ std::string generate_presigned_url(const ObjectStoragePathOptions& opts,
+ int64_t expiration_secs, const S3ClientConf& conf) override;
+
+private:
+ // Returns bucket: opts.bucket if set, else falls back to _bucket
+ const std::string& resolve_bucket(const ObjectStoragePathOptions& opts) const {
+ return opts.bucket.empty() ? _bucket : opts.bucket;
+ }
+
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> _client;
+ std::string _bucket;
+};
+
+} // namespace doris::io
+
+#endif // USE_OSS
diff --git a/be/src/util/CMakeLists.txt b/be/src/util/CMakeLists.txt
index de4d27eeebb..9f267a82caf 100644
--- a/be/src/util/CMakeLists.txt
+++ b/be/src/util/CMakeLists.txt
@@ -31,6 +31,10 @@ endif()
list(REMOVE_ITEM UTIL_FILES ${CMAKE_CURRENT_SOURCE_DIR}/libjvm_loader.cpp)
+if(BUILD_OSS STREQUAL "OFF")
+ list(REMOVE_ITEM UTIL_FILES ${CMAKE_CURRENT_SOURCE_DIR}/oss_util.cpp)
+endif()
+
add_library(Util STATIC
${UTIL_FILES}
)
diff --git a/be/src/util/oss_util.cpp b/be/src/util/oss_util.cpp
new file mode 100644
index 00000000000..88c49599dab
--- /dev/null
+++ b/be/src/util/oss_util.cpp
@@ -0,0 +1,290 @@
+// 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 "util/oss_util.h"
+
+#include <alibabacloud/oss/OssClient.h>
+#include <alibabacloud/oss/client/ClientConfiguration.h>
+#include <bvar/reducer.h>
+
+#include "common/config.h"
+#include "common/logging.h"
+#include "cpp/aws_common.h"
+#include "cpp/oss_credential_provider.h"
+#include "util/s3_util.h"
+#include "util/string_util.h"
+
+namespace doris {
+
+namespace oss_bvar {
+bvar::LatencyRecorder oss_get_latency("oss_get");
+bvar::LatencyRecorder oss_put_latency("oss_put");
+bvar::LatencyRecorder oss_delete_object_latency("oss_delete_object");
+bvar::LatencyRecorder oss_delete_objects_latency("oss_delete_objects");
+bvar::LatencyRecorder oss_head_latency("oss_head");
+bvar::LatencyRecorder oss_list_latency("oss_list");
+bvar::LatencyRecorder oss_multi_part_upload_latency("oss_multi_part_upload");
+} // namespace oss_bvar
+
+OSSConf OSSConf::get_oss_conf(const cloud::ObjectStoreInfoPB& obj_info) {
+ OSSConf conf;
+ conf.bucket = obj_info.bucket();
+ conf.prefix = obj_info.prefix();
+
+ conf.client_conf.endpoint = normalize_oss_endpoint(obj_info.endpoint());
+ conf.client_conf.region = obj_info.region();
+ conf.client_conf.bucket = obj_info.bucket();
+ conf.client_conf.role_arn = obj_info.role_arn();
+ conf.client_conf.external_id = obj_info.external_id();
+
+ if (obj_info.has_cred_provider_type()) {
+ switch (obj_info.cred_provider_type()) {
+ case cloud::CredProviderTypePB::DEFAULT:
+ conf.client_conf.cred_provider_type = OSSCredProviderType::DEFAULT;
+ VLOG(2) << "Using OSS DEFAULT credential provider";
+ break;
+ case cloud::CredProviderTypePB::INSTANCE_PROFILE:
+ conf.client_conf.cred_provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ VLOG(2) << "Using OSS INSTANCE_PROFILE credential provider";
+ break;
+ case cloud::CredProviderTypePB::SIMPLE:
+ conf.client_conf.cred_provider_type = OSSCredProviderType::SIMPLE;
+ conf.client_conf.ak = obj_info.ak();
+ conf.client_conf.sk = obj_info.sk();
+ VLOG(2) << "Using OSS SIMPLE credential provider";
+ break;
+ default:
+ conf.client_conf.cred_provider_type = OSSCredProviderType::DEFAULT;
+ VLOG(2) << "Unknown credential provider type, defaulting to DEFAULT";
+ break;
+ }
+ } else {
+ if (!obj_info.ak().empty() && !obj_info.sk().empty()) {
+ conf.client_conf.cred_provider_type = OSSCredProviderType::SIMPLE;
+ conf.client_conf.ak = obj_info.ak();
+ conf.client_conf.sk = obj_info.sk();
+ VLOG(2) << "Using OSS SIMPLE credential provider (from AK/SK)";
+ } else {
+ conf.client_conf.cred_provider_type = OSSCredProviderType::DEFAULT;
+ VLOG(2) << "No AK/SK provided, using OSS DEFAULT credential provider";
+ }
+ }
+
+ if (!conf.client_conf.role_arn.empty()) {
+ VLOG(2) << "OSS AssumeRole enabled with role_arn: " << conf.client_conf.role_arn;
+ }
+
+ return conf;
+}
+
+Status OSSClientFactory::convert_properties_to_oss_conf(
+ const std::map<std::string, std::string>& prop, OSSConf* oss_conf) {
+ auto get_property = [&](const std::string& key, std::string* value) -> bool {
+ auto it = prop.find(key);
+ if (it != prop.end()) {
+ *value = it->second;
+ return true;
+ }
+ return false;
+ };
+
+ std::string endpoint, bucket, prefix, region, ak, sk, token, provider, role_arn, external_id;
+
+ if (!get_property("oss.endpoint", &endpoint)) {
+ return Status::InvalidArgument("Missing oss.endpoint");
+ }
+ if (!get_property("oss.bucket", &bucket)) {
+ return Status::InvalidArgument("Missing oss.bucket");
+ }
+
+ get_property("oss.prefix", &prefix);
+ get_property("oss.region", ®ion);
+ get_property("oss.access_key", &ak);
+ get_property("oss.secret_key", &sk);
+ get_property("oss.session_token", &token);
+ get_property("oss.provider", &provider);
+ get_property("oss.role_arn", &role_arn);
+ get_property("oss.external_id", &external_id);
+
+ oss_conf->bucket = bucket;
+ oss_conf->prefix = prefix;
+ oss_conf->client_conf.endpoint = normalize_oss_endpoint(endpoint);
+ oss_conf->client_conf.region = region;
+ oss_conf->client_conf.bucket = bucket;
+ oss_conf->client_conf.role_arn = role_arn;
+ oss_conf->client_conf.external_id = external_id;
+
+ if (!role_arn.empty()) {
+ oss_conf->client_conf.cred_provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ } else if (provider == "INSTANCE_PROFILE" || provider == "instance_profile") {
+ oss_conf->client_conf.cred_provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ } else if (provider == "DEFAULT" || provider == "default") {
+ oss_conf->client_conf.cred_provider_type = OSSCredProviderType::DEFAULT;
+ } else if (provider == "SIMPLE" || provider == "simple") {
+ oss_conf->client_conf.cred_provider_type = OSSCredProviderType::SIMPLE;
+ oss_conf->client_conf.ak = ak;
+ oss_conf->client_conf.sk = sk;
+ oss_conf->client_conf.token = token;
+ } else if (!ak.empty() && !sk.empty()) {
+ oss_conf->client_conf.cred_provider_type = OSSCredProviderType::SIMPLE;
+ oss_conf->client_conf.ak = ak;
+ oss_conf->client_conf.sk = sk;
+ oss_conf->client_conf.token = token;
+ } else {
+ oss_conf->client_conf.cred_provider_type = OSSCredProviderType::DEFAULT;
+ }
+
+ return Status::OK();
+}
+
+OSSClientFactory::OSSClientFactory() {
+ static std::once_flag init_flag;
+ std::call_once(init_flag, []() {
+ AlibabaCloud::OSS::InitializeSdk();
+ LOG(INFO) << "Alibaba Cloud OSS SDK initialized";
+ });
+ _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
+}
+
+OSSClientFactory::~OSSClientFactory() {
+ AlibabaCloud::OSS::ShutdownSdk();
+ LOG(INFO) << "Alibaba Cloud OSS SDK shut down";
+}
+
+OSSClientFactory& OSSClientFactory::instance() {
+ static OSSClientFactory instance;
+ return instance;
+}
+
+std::shared_ptr<AlibabaCloud::OSS::OssClient> OSSClientFactory::create(
+ const OSSClientConf& oss_conf) {
+ if (oss_conf.endpoint.empty() || oss_conf.region.empty() || oss_conf.bucket.empty()) {
+ LOG(ERROR) << "Invalid OSS conf: endpoint, region and bucket are required";
+ return nullptr;
+ }
+ // SIMPLE + non-empty role_arn is valid: role_arn takes priority in the if-chain below
+ // (STS path), using AK/SK as the base credential. Only reject SIMPLE with no AK/SK and no role_arn.
+ if (oss_conf.cred_provider_type == OSSCredProviderType::SIMPLE && oss_conf.role_arn.empty() &&
+ (oss_conf.ak.empty() || oss_conf.sk.empty())) {
+ LOG(ERROR) << "Invalid OSS conf: ak and sk required for SIMPLE credential provider";
+ return nullptr;
+ }
+
+ uint64_t hash = oss_conf.get_hash();
+
+ {
+ std::lock_guard<std::mutex> lock(_lock);
+ auto it = _cache.find(hash);
+ if (it != _cache.end()) {
+ VLOG(2) << "Reusing cached OSS client for endpoint: " << oss_conf.endpoint;
+ return it->second;
+ }
+ }
+ // TOCTOU: concurrent calls with the same hash may both miss the cache and create duplicate
+ // clients. Accepted pattern matching S3ClientFactory; last writer wins under the lock below.
+
+ AlibabaCloud::OSS::ClientConfiguration oss_client_config;
+ oss_client_config.maxConnections = oss_conf.max_connections;
+ oss_client_config.requestTimeoutMs = oss_conf.request_timeout_ms;
+ oss_client_config.connectTimeoutMs = oss_conf.connect_timeout_ms;
+
+ if (_ca_cert_file_path.empty()) {
+ _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
+ }
+ if (!_ca_cert_file_path.empty()) {
+ oss_client_config.caFile = _ca_cert_file_path;
+ }
+
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> client;
+
+ try {
+ if (!oss_conf.role_arn.empty()) {
+ std::shared_ptr<OSSSTSCredentialProvider> sts_provider;
+ {
+ std::lock_guard<std::mutex> lock(_lock);
+ auto it = _sts_credential_providers.find(hash);
+ if (it != _sts_credential_providers.end()) {
+ sts_provider = it->second;
+ } else {
+ std::string region = oss_conf.region.empty() ? "cn-hangzhou" : oss_conf.region;
+ sts_provider = std::make_shared<OSSSTSCredentialProvider>(
+ oss_conf.role_arn, region, oss_conf.external_id, _ca_cert_file_path,
+ oss_conf.sts_endpoint);
+ _sts_credential_providers[hash] = sts_provider;
+ }
+ }
+ client = std::make_shared<AlibabaCloud::OSS::OssClient>(
+ oss_conf.endpoint,
+ std::static_pointer_cast<AlibabaCloud::OSS::CredentialsProvider>(sts_provider),
+ oss_client_config);
+ LOG(INFO) << "OSS client created with AssumeRole, endpoint=" << oss_conf.endpoint
+ << ", role_arn=" << oss_conf.role_arn;
+ } else if (oss_conf.cred_provider_type == OSSCredProviderType::INSTANCE_PROFILE) {
+ std::shared_ptr<ECSMetadataCredentialsProvider> provider;
+ {
+ std::lock_guard<std::mutex> lock(_lock);
+ auto it = _ecs_credential_providers.find(hash);
+ if (it != _ecs_credential_providers.end()) {
+ provider = it->second;
+ } else {
+ provider = std::make_shared<ECSMetadataCredentialsProvider>();
+ _ecs_credential_providers[hash] = provider;
+ }
+ }
+ client = std::make_shared<AlibabaCloud::OSS::OssClient>(
+ oss_conf.endpoint,
+ std::static_pointer_cast<AlibabaCloud::OSS::CredentialsProvider>(provider),
+ oss_client_config);
+ LOG(INFO) << "OSS client created with INSTANCE_PROFILE, endpoint=" << oss_conf.endpoint;
+ } else if (oss_conf.cred_provider_type == OSSCredProviderType::DEFAULT) {
+ std::shared_ptr<OSSDefaultCredentialsProvider> provider;
+ {
+ std::lock_guard<std::mutex> lock(_lock);
+ auto it = _default_credential_providers.find(hash);
+ if (it != _default_credential_providers.end()) {
+ provider = it->second;
+ } else {
+ provider = std::make_shared<OSSDefaultCredentialsProvider>();
+ _default_credential_providers[hash] = provider;
+ }
+ }
+ client = std::make_shared<AlibabaCloud::OSS::OssClient>(
+ oss_conf.endpoint,
+ std::static_pointer_cast<AlibabaCloud::OSS::CredentialsProvider>(provider),
+ oss_client_config);
+ LOG(INFO) << "OSS client created with DEFAULT provider, endpoint=" << oss_conf.endpoint;
+ } else {
+ AlibabaCloud::OSS::Credentials creds(oss_conf.ak, oss_conf.sk, oss_conf.token);
+ client = std::make_shared<AlibabaCloud::OSS::OssClient>(oss_conf.endpoint, creds,
+ oss_client_config);
+ LOG(INFO) << "OSS client created with SIMPLE credentials, endpoint="
+ << oss_conf.endpoint;
+ }
+ } catch (const std::exception& e) {
+ LOG(ERROR) << "Failed to create OSS client: " << e.what();
+ return nullptr;
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(_lock);
+ _cache[hash] = client;
+ }
+
+ return client;
+}
+
+} // namespace doris
diff --git a/be/src/util/oss_util.h b/be/src/util/oss_util.h
new file mode 100644
index 00000000000..8c981d2f4d9
--- /dev/null
+++ b/be/src/util/oss_util.h
@@ -0,0 +1,146 @@
+// 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.
+
+#pragma once
+
+#include <bvar/bvar.h>
+#include <fmt/format.h>
+#include <gen_cpp/cloud.pb.h>
+
+#include <map>
+#include <memory>
+#include <mutex>
+#include <string>
+
+#include "common/status.h"
+#include "cpp/oss_common.h"
+#include "util/s3_util.h"
+
+// Forward declare OSS SDK types
+namespace AlibabaCloud {
+namespace OSS {
+class OssClient;
+} // namespace OSS
+} // namespace AlibabaCloud
+
+namespace doris {
+
+class ECSMetadataCredentialsProvider;
+class OSSSTSCredentialProvider;
+class OSSDefaultCredentialsProvider;
+
+namespace oss_bvar {
+extern bvar::LatencyRecorder oss_get_latency;
+extern bvar::LatencyRecorder oss_put_latency;
+extern bvar::LatencyRecorder oss_delete_object_latency;
+extern bvar::LatencyRecorder oss_delete_objects_latency;
+extern bvar::LatencyRecorder oss_head_latency;
+extern bvar::LatencyRecorder oss_list_latency;
+extern bvar::LatencyRecorder oss_multi_part_upload_latency;
+} // namespace oss_bvar
+
+// OSS Client Configuration
+struct OSSClientConf {
+ std::string endpoint;
+ std::string region;
+ std::string ak;
+ std::string sk;
+ std::string token;
+ std::string bucket;
+ std::string role_arn; // For STS AssumeRole
+ std::string external_id; // For STS AssumeRole (cross-account security)
+ // Override STS endpoint; empty = "sts.<region>.aliyuncs.com" (standard public cloud).
+ // Set for Alibaba Cloud finance/gov cloud regions that use non-standard STS endpoints.
+ std::string sts_endpoint;
+
+ int max_connections = 100;
+ int request_timeout_ms = 30000;
+ int connect_timeout_ms = 10000;
+
+ OSSCredProviderType cred_provider_type = OSSCredProviderType::DEFAULT;
+
+ uint64_t get_hash() const {
+ uint64_t hash_code = 0;
+ hash_code ^= crc32_hash(ak + sk);
+ hash_code ^= crc32_hash(token);
+ hash_code ^= crc32_hash(endpoint);
+ hash_code ^= crc32_hash(region);
+ hash_code ^= crc32_hash(bucket);
+ hash_code ^= crc32_hash(role_arn);
+ hash_code ^= crc32_hash(external_id);
+ hash_code ^= crc32_hash(sts_endpoint);
+ hash_code ^= max_connections;
+ hash_code ^= request_timeout_ms;
+ hash_code ^= connect_timeout_ms;
+ hash_code ^= static_cast<int>(cred_provider_type);
+ return hash_code;
+ }
+
+ std::string to_string() const {
+ return fmt::format(
+ "(ak={}, token={}, endpoint={}, region={}, bucket={}, role_arn={}, external_id={}, "
+ "max_connections={}, request_timeout_ms={}, connect_timeout_ms={}, "
+ "cred_provider_type={})",
+ hide_access_key(ak), hide_access_key(token), endpoint, region, bucket, role_arn,
+ external_id, max_connections, request_timeout_ms, connect_timeout_ms,
+ static_cast<int>(cred_provider_type));
+ }
+};
+
+// OSS Configuration
+struct OSSConf {
+ std::string bucket;
+ std::string prefix;
+ OSSClientConf client_conf;
+
+ static OSSConf get_oss_conf(const cloud::ObjectStoreInfoPB& obj_info);
+
+ std::string to_string() const {
+ return fmt::format("(bucket={}, prefix={}, client_conf={})", bucket, prefix,
+ client_conf.to_string());
+ }
+};
+
+// Factory for creating OSS clients
+class OSSClientFactory {
+public:
+ ~OSSClientFactory();
+
+ static OSSClientFactory& instance();
+
+ // Create or get cached OSS client
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> create(const OSSClientConf& oss_conf);
+
+ // Convert properties map to OSSConf
+ static Status convert_properties_to_oss_conf(const std::map<std::string, std::string>& prop,
+ OSSConf* oss_conf);
+
+private:
+ OSSClientFactory();
+
+ std::mutex _lock;
+ std::unordered_map<uint64_t, std::shared_ptr<AlibabaCloud::OSS::OssClient>> _cache;
+ std::unordered_map<uint64_t, std::shared_ptr<ECSMetadataCredentialsProvider>>
+ _ecs_credential_providers;
+ std::unordered_map<uint64_t, std::shared_ptr<OSSSTSCredentialProvider>>
+ _sts_credential_providers;
+ std::unordered_map<uint64_t, std::shared_ptr<OSSDefaultCredentialsProvider>>
+ _default_credential_providers;
+ std::string _ca_cert_file_path;
+};
+
+} // namespace doris
diff --git a/be/src/util/s3_util.cpp b/be/src/util/s3_util.cpp
index 2013c3c4b74..5dd807db691 100644
--- a/be/src/util/s3_util.cpp
+++ b/be/src/util/s3_util.cpp
@@ -41,6 +41,10 @@
#include <azure/core/http/curl_transport.hpp>
#include <azure/storage/blobs/blob_container_client.hpp>
#endif
+#ifdef USE_OSS
+#include "io/fs/oss_v2_obj_storage_client.h"
+#include "util/oss_util.h"
+#endif
#include <cstdlib>
#include <filesystem>
#include <fstream>
@@ -142,6 +146,7 @@ std::string build_azure_tls_debug_context(const std::string& selected_ca_file) {
constexpr char USE_PATH_STYLE[] = "use_path_style";
constexpr char AZURE_PROVIDER_STRING[] = "AZURE";
+constexpr char OSS_PROVIDER_STRING[] = "OSS";
constexpr char S3_PROVIDER[] = "provider";
constexpr char S3_AK[] = "AWS_ACCESS_KEY";
constexpr char S3_SK[] = "AWS_SECRET_KEY";
@@ -156,6 +161,26 @@ constexpr char S3_NEED_OVERRIDE_ENDPOINT[] = "AWS_NEED_OVERRIDE_ENDPOINT";
constexpr char S3_ROLE_ARN[] = "AWS_ROLE_ARN";
constexpr char S3_EXTERNAL_ID[] = "AWS_EXTERNAL_ID";
constexpr char S3_CREDENTIALS_PROVIDER_TYPE[] = "AWS_CREDENTIALS_PROVIDER_TYPE";
+
+#ifdef USE_OSS
+// Map S3/AWS CredProviderType to OSSCredProviderType
+OSSCredProviderType s3_cred_to_oss_cred(CredProviderType type) {
+ switch (type) {
+ case CredProviderType::InstanceProfile:
+ return OSSCredProviderType::INSTANCE_PROFILE;
+ case CredProviderType::Simple:
+ return OSSCredProviderType::SIMPLE;
+ case CredProviderType::Default:
+ return OSSCredProviderType::DEFAULT;
+ default:
+ LOG(WARNING) << "Credential provider type " << static_cast<int>(type)
+ << " is not directly supported for OSS; falling back to DEFAULT "
+ "(OSSDefaultCredentialsProvider chain).";
+ return OSSCredProviderType::DEFAULT;
+ }
+}
+#endif
+
} // namespace
bvar::Adder<int64_t> get_rate_limit_ns("get_rate_limit_ns");
@@ -311,9 +336,16 @@ std::shared_ptr<io::ObjStorageClient> S3ClientFactory::create(const S3ClientConf
}
}
- auto obj_client = (s3_conf.provider == io::ObjStorageType::AZURE)
- ? _create_azure_client(s3_conf)
- : _create_s3_client(s3_conf);
+ std::shared_ptr<io::ObjStorageClient> obj_client;
+ if (s3_conf.provider == io::ObjStorageType::AZURE) {
+ obj_client = _create_azure_client(s3_conf);
+#ifdef USE_OSS
+ } else if (s3_conf.provider == io::ObjStorageType::OSS && config::enable_oss_native_sdk) {
+ obj_client = _create_oss_client(s3_conf);
+#endif
+ } else {
+ obj_client = _create_s3_client(s3_conf);
+ }
{
uint64_t hash = s3_conf.get_hash();
@@ -580,6 +612,8 @@ Status S3ClientFactory::convert_properties_to_s3_conf(
// S3 Provider properties should be case insensitive.
if (0 == strcasecmp(it->second.c_str(), AZURE_PROVIDER_STRING)) {
s3_conf->client_conf.provider = io::ObjStorageType::AZURE;
+ } else if (0 == strcasecmp(it->second.c_str(), OSS_PROVIDER_STRING)) {
+ s3_conf->client_conf.provider = io::ObjStorageType::OSS;
}
}
@@ -785,4 +819,39 @@ std::string hide_access_key(const std::string& ak) {
return key;
}
+#ifdef USE_OSS
+std::shared_ptr<io::ObjStorageClient> S3ClientFactory::_create_oss_client(
+ const S3ClientConf& s3_conf) {
+ // Convert S3ClientConf → OSSClientConf, mapping fields 1:1
+ OSSClientConf oss_conf;
+ oss_conf.endpoint = normalize_oss_endpoint(s3_conf.endpoint);
+ oss_conf.region = s3_conf.region;
+ oss_conf.ak = s3_conf.ak;
+ oss_conf.sk = s3_conf.sk;
+ oss_conf.token = s3_conf.token;
+ oss_conf.bucket = s3_conf.bucket;
+ oss_conf.role_arn = s3_conf.role_arn;
+ oss_conf.external_id = s3_conf.external_id;
+ oss_conf.max_connections = s3_conf.max_connections > 0 ? s3_conf.max_connections : 100;
+ oss_conf.request_timeout_ms =
+ s3_conf.request_timeout_ms > 0 ? s3_conf.request_timeout_ms : 30000;
+ oss_conf.connect_timeout_ms =
+ s3_conf.connect_timeout_ms > 0 ? s3_conf.connect_timeout_ms : 10000;
+ oss_conf.cred_provider_type = s3_cred_to_oss_cred(s3_conf.cred_provider_type);
+ // Mirror AWS SDK v2 behavior: role_arn alone is sufficient to trigger STS AssumeRole.
+ if (!oss_conf.role_arn.empty() && oss_conf.cred_provider_type == OSSCredProviderType::DEFAULT) {
+ oss_conf.cred_provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ }
+
+ auto native_client = OSSClientFactory::instance().create(oss_conf);
+ if (!native_client) {
+ LOG(WARNING) << "failed to create native oss client with conf " << s3_conf.to_string();
+ return nullptr;
+ }
+
+ LOG_INFO("create one oss client (native SDK) with {}", s3_conf.to_string());
+ return std::make_shared<io::OSSv2ObjStorageClient>(std::move(native_client), s3_conf.bucket);
+}
+#endif
+
} // end namespace doris
diff --git a/be/src/util/s3_util.h b/be/src/util/s3_util.h
index 5cedee997ee..718b904a620 100644
--- a/be/src/util/s3_util.h
+++ b/be/src/util/s3_util.h
@@ -166,6 +166,9 @@ public:
private:
std::shared_ptr<io::ObjStorageClient> _create_s3_client(const S3ClientConf& s3_conf);
std::shared_ptr<io::ObjStorageClient> _create_azure_client(const S3ClientConf& s3_conf);
+#ifdef USE_OSS
+ std::shared_ptr<io::ObjStorageClient> _create_oss_client(const S3ClientConf& s3_conf);
+#endif
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> _get_aws_credentials_provider_v1(
const S3ClientConf& s3_conf);
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> _get_aws_credentials_provider_v2(
diff --git a/be/test/util/oss_credential_provider_test.cpp b/be/test/util/oss_credential_provider_test.cpp
new file mode 100644
index 00000000000..f3891d1c817
--- /dev/null
+++ b/be/test/util/oss_credential_provider_test.cpp
@@ -0,0 +1,326 @@
+// 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 "cpp/oss_credential_provider.h"
+
+#ifdef USE_OSS
+
+#include <gtest/gtest.h>
+
+#include <atomic>
+#include <chrono>
+#include <thread>
+#include <vector>
+
+#include "common/logging.h"
+
+namespace doris {
+
+// ---------------------------------------------------------------------------
+// Helper
+// ---------------------------------------------------------------------------
+static bool credentials_non_empty(const AlibabaCloud::OSS::Credentials& c) {
+ return !c.AccessKeyId().empty() && !c.AccessKeySecret().empty();
+}
+
+// ---------------------------------------------------------------------------
+// ECSMetadataCredentialsProvider tests
+// All tests that require a real ECS RAM role use GTEST_SKIP() gracefully —
+// same pattern as oss_credential_provider_test.cpp.
+// ---------------------------------------------------------------------------
+class ECSMetadataProviderTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ // Quick probe: if metadata service is unreachable, skip all ECS tests.
+ // We detect this by attempting a single credential fetch.
+ ECSMetadataCredentialsProvider probe;
+ auto creds = probe.getCredentials();
+ if (creds.AccessKeyId().empty()) {
+ skip_ = true;
+ }
+ }
+ bool skip_ = false;
+};
+
+TEST_F(ECSMetadataProviderTest, returns_non_empty_credentials) {
+ if (skip_) GTEST_SKIP() << "Not running on ECS with RAM role";
+
+ ECSMetadataCredentialsProvider provider;
+ auto creds = provider.getCredentials();
+ EXPECT_FALSE(creds.AccessKeyId().empty());
+ EXPECT_FALSE(creds.AccessKeySecret().empty());
+ EXPECT_FALSE(creds.SessionToken().empty());
+}
+
+TEST_F(ECSMetadataProviderTest, second_call_returns_cached_credentials) {
+ if (skip_) GTEST_SKIP() << "Not running on ECS with RAM role";
+
+ ECSMetadataCredentialsProvider provider;
+ auto creds1 = provider.getCredentials();
+ auto creds2 = provider.getCredentials();
+
+ EXPECT_EQ(creds1.AccessKeyId(), creds2.AccessKeyId())
+ << "Second call should return cached credentials";
+ EXPECT_EQ(creds1.AccessKeySecret(), creds2.AccessKeySecret());
+ EXPECT_EQ(creds1.SessionToken(), creds2.SessionToken());
+}
+
+TEST_F(ECSMetadataProviderTest, concurrent_calls_all_succeed) {
+ if (skip_) GTEST_SKIP() << "Not running on ECS with RAM role";
+
+ ECSMetadataCredentialsProvider provider;
+
+ const int num_threads = 10;
+ const int calls_per_thread = 5;
+ std::atomic<int> success_count {0};
+ std::atomic<int> failure_count {0};
+
+ std::vector<std::thread> threads;
+ threads.reserve(num_threads);
+ for (int i = 0; i < num_threads; ++i) {
+ threads.emplace_back([&]() {
+ for (int j = 0; j < calls_per_thread; ++j) {
+ auto creds = provider.getCredentials();
+ if (credentials_non_empty(creds)) {
+ ++success_count;
+ } else {
+ ++failure_count;
+ }
+ }
+ });
+ }
+ for (auto& t : threads) t.join();
+
+ // At least 90% of calls should succeed (allow for transient network blips)
+ EXPECT_GT(success_count.load(), num_threads * calls_per_thread * 9 / 10)
+ << "success=" << success_count << " failure=" << failure_count;
+}
+
+TEST_F(ECSMetadataProviderTest, multiple_instances_get_same_credentials) {
+ if (skip_) GTEST_SKIP() << "Not running on ECS with RAM role";
+
+ ECSMetadataCredentialsProvider p1;
+ ECSMetadataCredentialsProvider p2;
+
+ auto c1 = p1.getCredentials();
+ auto c2 = p2.getCredentials();
+
+ EXPECT_EQ(c1.AccessKeyId(), c2.AccessKeyId())
+ << "Independent providers on the same ECS instance must return the same credentials";
+}
+
+// ---------------------------------------------------------------------------
+// OSSSTSCredentialProvider tests
+// ---------------------------------------------------------------------------
+class OSSSTSProviderTest : public ::testing::Test {
+protected:
+ // Populated from environment variables so CI can override.
+ // Required: OSS_ROLE_ARN, OSS_REGION
+ // Optional: OSS_EXTERNAL_ID
+ static void SetUpTestSuite() {
+ if (std::getenv("OSS_ROLE_ARN")) role_arn = std::getenv("OSS_ROLE_ARN");
+ if (std::getenv("OSS_REGION")) region = std::getenv("OSS_REGION");
+ if (std::getenv("OSS_EXTERNAL_ID")) external_id = std::getenv("OSS_EXTERNAL_ID");
+ }
+
+ void SetUp() override {
+ if (role_arn.empty() || region.empty()) {
+ GTEST_SKIP() << "OSS_ROLE_ARN and OSS_REGION env vars required for STS tests";
+ }
+ // Also requires ECS metadata (base credential for STS)
+ ECSMetadataCredentialsProvider probe;
+ auto creds = probe.getCredentials();
+ if (creds.AccessKeyId().empty()) {
+ GTEST_SKIP() << "ECS RAM role required as base credential for STS AssumeRole";
+ }
+ }
+
+public:
+ static std::string role_arn;
+ static std::string region;
+ static std::string external_id;
+};
+
+std::string OSSSTSProviderTest::role_arn;
+std::string OSSSTSProviderTest::region;
+std::string OSSSTSProviderTest::external_id;
+
+TEST_F(OSSSTSProviderTest, constructor_rejects_empty_role_arn) {
+ // This must throw regardless of environment
+ EXPECT_THROW(OSSSTSCredentialProvider("", "cn-hangzhou"), std::invalid_argument);
+}
+
+TEST_F(OSSSTSProviderTest, returns_valid_sts_credentials) {
+ OSSSTSCredentialProvider provider(role_arn, region);
+ auto creds = provider.getCredentials();
+
+ EXPECT_FALSE(creds.AccessKeyId().empty()) << "STS must return a non-empty AccessKeyId";
+ EXPECT_FALSE(creds.AccessKeySecret().empty());
+ EXPECT_FALSE(creds.SessionToken().empty())
+ << "STS assumed credentials must include a SecurityToken";
+}
+
+TEST_F(OSSSTSProviderTest, second_call_returns_cached_credentials) {
+ OSSSTSCredentialProvider provider(role_arn, region);
+
+ auto creds1 = provider.getCredentials();
+ auto creds2 = provider.getCredentials();
+
+ EXPECT_EQ(creds1.AccessKeyId(), creds2.AccessKeyId())
+ << "Second call within TTL must return cached STS credentials";
+ EXPECT_EQ(creds1.SessionToken(), creds2.SessionToken());
+}
+
+TEST_F(OSSSTSProviderTest, with_external_id_returns_valid_credentials) {
+ if (external_id.empty()) {
+ GTEST_SKIP() << "OSS_EXTERNAL_ID not set, skipping external_id test";
+ }
+
+ OSSSTSCredentialProvider provider(role_arn, region, external_id);
+ auto creds = provider.getCredentials();
+
+ EXPECT_FALSE(creds.AccessKeyId().empty());
+ EXPECT_FALSE(creds.SessionToken().empty());
+}
+
+TEST_F(OSSSTSProviderTest, empty_external_id_not_sent_to_sts) {
+ // Provider with empty external_id should work fine (does not pass ExternalId to STS)
+ OSSSTSCredentialProvider provider(role_arn, region, /*external_id=*/"");
+ auto creds = provider.getCredentials();
+
+ EXPECT_FALSE(creds.AccessKeyId().empty());
+ EXPECT_FALSE(creds.SessionToken().empty());
+}
+
+TEST_F(OSSSTSProviderTest, concurrent_calls_are_thread_safe) {
+ OSSSTSCredentialProvider provider(role_arn, region);
+
+ const int num_threads = 8;
+ std::atomic<int> success_count {0};
+ std::atomic<int> failure_count {0};
+
+ std::vector<std::thread> threads;
+ threads.reserve(num_threads);
+ for (int i = 0; i < num_threads; ++i) {
+ threads.emplace_back([&]() {
+ auto creds = provider.getCredentials();
+ if (credentials_non_empty(creds)) {
+ ++success_count;
+ } else {
+ ++failure_count;
+ }
+ });
+ }
+ for (auto& t : threads) t.join();
+
+ EXPECT_EQ(failure_count.load(), 0) << "All concurrent STS credential requests must succeed";
+ EXPECT_EQ(success_count.load(), num_threads);
+}
+
+// ---------------------------------------------------------------------------
+// OSSSTSCredentialProvider — no-ECS fallback safety
+// When STS fails AND there is no cached credential, getCredentials() must
+// return empty credentials instead of throwing (prevents BE crash).
+// This is the regression test for the std::runtime_error crash fix.
+// ---------------------------------------------------------------------------
+TEST(OSSSTSProviderSafetyTest, empty_role_arn_throws_on_construction) {
+ EXPECT_THROW(OSSSTSCredentialProvider("", "cn-hangzhou"), std::invalid_argument)
+ << "Constructor must reject empty role_arn immediately";
+}
+
+// ---------------------------------------------------------------------------
+// OSSDefaultCredentialsProvider tests
+// ---------------------------------------------------------------------------
+class OSSDefaultProviderTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ // Default provider uses Alibaba Cloud credential chain
+ // (env vars, config file, ECS metadata). Skip if none available.
+ OSSDefaultCredentialsProvider probe;
+ auto creds = probe.getCredentials();
+ if (creds.AccessKeyId().empty()) {
+ GTEST_SKIP() << "No Alibaba Cloud credentials available for default provider test";
+ }
+ }
+};
+
+TEST_F(OSSDefaultProviderTest, returns_non_empty_credentials) {
+ OSSDefaultCredentialsProvider provider;
+ auto creds = provider.getCredentials();
+
+ EXPECT_FALSE(creds.AccessKeyId().empty());
+ EXPECT_FALSE(creds.AccessKeySecret().empty());
+}
+
+TEST_F(OSSDefaultProviderTest, second_call_returns_cached_credentials) {
+ OSSDefaultCredentialsProvider provider;
+
+ auto creds1 = provider.getCredentials();
+ auto creds2 = provider.getCredentials();
+
+ EXPECT_EQ(creds1.AccessKeyId(), creds2.AccessKeyId())
+ << "Default provider must cache and return same credentials on second call";
+}
+
+TEST_F(OSSDefaultProviderTest, concurrent_calls_are_thread_safe) {
+ OSSDefaultCredentialsProvider provider;
+
+ const int num_threads = 10;
+ std::atomic<int> success_count {0};
+
+ std::vector<std::thread> threads;
+ threads.reserve(num_threads);
+ for (int i = 0; i < num_threads; ++i) {
+ threads.emplace_back([&]() {
+ auto creds = provider.getCredentials();
+ if (credentials_non_empty(creds)) ++success_count;
+ });
+ }
+ for (auto& t : threads) t.join();
+
+ EXPECT_GT(success_count.load(), num_threads * 9 / 10)
+ << "At least 90% of concurrent default provider calls must succeed";
+}
+
+// ---------------------------------------------------------------------------
+// OSSDefaultCredentialsProvider — safety: must not throw on failure
+// ---------------------------------------------------------------------------
+TEST(OSSDefaultProviderSafetyTest, returns_empty_credentials_when_no_chain_available) {
+ // When no credential sources are configured, getCredentials() must return
+ // empty credentials, NOT throw. Throwing would crash the BE via std::terminate.
+ // We cannot guarantee the environment has no credentials, so we verify the
+ // return type contract: whatever is returned must be an AlibabaCloud::OSS::Credentials.
+ OSSDefaultCredentialsProvider provider;
+ EXPECT_NO_THROW({
+ auto creds = provider.getCredentials();
+ // Either empty (no chain) or non-empty (chain found) — both are valid.
+ // The important thing is: no exception thrown.
+ (void)creds.AccessKeyId();
+ });
+}
+
+} // namespace doris
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ google::InitGoogleLogging(argv[0]);
+ google::SetStderrLogging(google::INFO);
+ LOG(INFO) << "Starting OSS credential provider tests";
+ return RUN_ALL_TESTS();
+}
+
+#endif // USE_OSS
diff --git a/build.sh b/build.sh
index 66c9836cf0a..3bf69632178 100755
--- a/build.sh
+++ b/build.sh
@@ -79,6 +79,7 @@ Usage: $0 <options>
DISABLE_BUILD_AZURE If set DISABLE_BUILD_AZURE=ON, it will not build azure into BE.
DISABLE_BUILD_JUICEFS If set DISABLE_BUILD_JUICEFS=OFF, it will package juicefs-hadoop jar into FE/BE output. Default is ON (skip).
DISABLE_BUILD_JINDOFS If set DISABLE_BUILD_JINDOFS=OFF, it will package jindofs jars into FE/BE output. Default is ON (skip).
+ DISABLE_BUILD_OSS If set DISABLE_BUILD_OSS=ON, it will not build OSS SDK and STS SDK V2 into BE.
Eg.
$0 build all
@@ -188,6 +189,7 @@ PARAMETER_COUNT="$#"
PARAMETER_FLAG=0
DENABLE_CLANG_COVERAGE='OFF'
BUILD_AZURE='ON'
+BUILD_OSS='ON'
BUILD_UI=1
if [[ "$#" == 1 ]]; then
# default
@@ -499,6 +501,10 @@ else
fi
export DISABLE_BUILD_JUICEFS
+if [[ "$(echo "${DISABLE_BUILD_OSS}" | tr '[:lower:]' '[:upper:]')" == "ON" ]]; then
+ BUILD_OSS='OFF'
+fi
+
if [[ -z "${ENABLE_INJECTION_POINT}" ]]; then
ENABLE_INJECTION_POINT='OFF'
fi
@@ -691,6 +697,7 @@ if [[ "${BUILD_BE}" -eq 1 ]]; then
-DENABLE_CLANG_COVERAGE="${DENABLE_CLANG_COVERAGE}" \
-DDORIS_JAVA_HOME="${JAVA_HOME}" \
-DBUILD_AZURE="${BUILD_AZURE}" \
+ -DBUILD_OSS="${BUILD_OSS}" \
-DWITH_TDE_DIR="${WITH_TDE_DIR}" \
"${DORIS_HOME}/be"
diff --git a/cloud/CMakeLists.txt b/cloud/CMakeLists.txt
index fe7062e3fcc..57318f2d2d6 100644
--- a/cloud/CMakeLists.txt
+++ b/cloud/CMakeLists.txt
@@ -343,6 +343,12 @@ if(BUILD_AZURE STREQUAL "ON")
add_definitions(-DUSE_AZURE)
endif()
+option(BUILD_OSS "ON for building OSS support or OFF for not" ON)
+message(STATUS "build OSS: ${BUILD_OSS}")
+if(BUILD_OSS STREQUAL "ON")
+ add_definitions(-DUSE_OSS)
+endif()
+
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(ASAN_LIBS -static-libasan)
set(LSAN_LIBS -static-liblsan)
diff --git a/cloud/cmake/thirdparty.cmake b/cloud/cmake/thirdparty.cmake
index 6b1a614b395..5eed4f1cce5 100644
--- a/cloud/cmake/thirdparty.cmake
+++ b/cloud/cmake/thirdparty.cmake
@@ -107,6 +107,19 @@ add_thirdparty(lzma LIB64)
add_thirdparty(idn LIB64)
add_thirdparty(gsasl)
# end krb5 libs
+# begin oss libs
+if(BUILD_OSS STREQUAL "ON")
+ # STS SDK V2 for AssumeRole (must be before OSS SDK)
+ add_thirdparty(darabonba_core)
+ add_thirdparty(alibabacloud_credentials)
+ add_thirdparty(alibabacloud_open_api_v2)
+ add_thirdparty(alibabacloud_sts20150401)
+ # OSS SDK
+ add_thirdparty(alibabacloud-oss-cpp-sdk LIB64)
+ add_thirdparty(apr)
+ add_thirdparty(aprutil)
+endif()
+# end oss libs
# begin azure libs
if(BUILD_AZURE STREQUAL "ON")
add_thirdparty(azure-core)
diff --git a/cloud/src/meta-service/meta_service_resource.cpp b/cloud/src/meta-service/meta_service_resource.cpp
index b4e5e0d0b15..afdfdf41ead 100644
--- a/cloud/src/meta-service/meta_service_resource.cpp
+++ b/cloud/src/meta-service/meta_service_resource.cpp
@@ -186,6 +186,13 @@ int decrypt_instance_info(InstanceInfoPB& instance, const std::string& instance_
static int decrypt_and_update_ak_sk(ObjectStoreInfoPB& obj_info, MetaServiceCode& code,
std::string& msg) {
+ // Skip decryption if credentials are empty
+ // This handles INSTANCE_PROFILE vaults (ECS metadata) and broken legacy vaults
+ // Empty credentials = nothing to decrypt = safe to skip
+ if (obj_info.ak().empty() || obj_info.sk().empty()) {
+ return 0;
+ }
+
if (obj_info.has_encryption_info()) {
AkSkPair plain_ak_sk_pair;
if (int ret = decrypt_ak_sk_helper(obj_info.ak(), obj_info.sk(), obj_info.encryption_info(),
@@ -681,32 +688,52 @@ static void create_object_info_with_encrypt(const InstanceInfoPB& instance, Obje
if (obj->has_role_arn()) {
if (obj->role_arn().empty() || !obj->has_cred_provider_type() ||
obj->cred_provider_type() != CredProviderTypePB::INSTANCE_PROFILE ||
- !obj->has_provider() || obj->provider() != ObjectStoreInfoPB::S3 || bucket.empty() ||
- endpoint.empty() || region.empty()) {
+ !obj->has_provider() ||
+ (obj->provider() != ObjectStoreInfoPB::S3 &&
+ obj->provider() != ObjectStoreInfoPB::OSS) ||
+ bucket.empty() || endpoint.empty() || region.empty()) {
code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "s3 conf info err with role_arn, please check it";
+ msg = "object storage conf info err with role_arn, please check it";
return;
}
} else {
- // ATTN: prefix may be empty
- if (plain_ak.empty() || plain_sk.empty() || bucket.empty() || endpoint.empty() ||
- region.empty() || !obj->has_provider() || external_endpoint.empty()) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "s3 conf info err, please check it";
- return;
- }
+ // Check if this is INSTANCE_PROFILE without role_arn (ECS instance metadata mode)
+ bool is_instance_profile =
+ obj->has_cred_provider_type() &&
+ obj->cred_provider_type() == CredProviderTypePB::INSTANCE_PROFILE;
+
+ if (!is_instance_profile) {
+ // external_endpoint is required for S3 but not for OSS.
+ bool needs_external_endpoint =
+ obj->has_provider() && obj->provider() != ObjectStoreInfoPB::OSS;
+ if (plain_ak.empty() || plain_sk.empty() || bucket.empty() || endpoint.empty() ||
+ region.empty() || !obj->has_provider() ||
+ (needs_external_endpoint && external_endpoint.empty())) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "s3 conf info err, please check it";
+ return;
+ }
- EncryptionInfoPB encryption_info;
- AkSkPair cipher_ak_sk_pair;
- auto ret = encrypt_ak_sk_helper(plain_ak, plain_sk, &encryption_info, &cipher_ak_sk_pair,
- code, msg);
- TEST_SYNC_POINT_CALLBACK("create_object_info_with_encrypt", &ret, &code, &msg);
- if (ret != 0) {
- return;
+ EncryptionInfoPB encryption_info;
+ AkSkPair cipher_ak_sk_pair;
+ auto ret = encrypt_ak_sk_helper(plain_ak, plain_sk, &encryption_info,
+ &cipher_ak_sk_pair, code, msg);
+ TEST_SYNC_POINT_CALLBACK("create_object_info_with_encrypt", &ret, &code, &msg);
+ if (ret != 0) {
+ return;
+ }
+ obj->set_ak(std::move(cipher_ak_sk_pair.first));
+ obj->set_sk(std::move(cipher_ak_sk_pair.second));
+ obj->mutable_encryption_info()->CopyFrom(encryption_info);
+ } else {
+ // INSTANCE_PROFILE without role_arn - validate basic requirements
+ if (bucket.empty() || endpoint.empty() || region.empty() || !obj->has_provider()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "s3 conf info err, please check it";
+ return;
+ }
+ // Don't set ak/sk/encryption_info for INSTANCE_PROFILE without credentials
}
- obj->set_ak(std::move(cipher_ak_sk_pair.first));
- obj->set_sk(std::move(cipher_ak_sk_pair.second));
- obj->mutable_encryption_info()->CopyFrom(encryption_info);
}
obj->set_bucket(bucket);
@@ -1107,24 +1134,34 @@ static int extract_object_storage_info(const AlterObjStoreInfoRequest* request,
auto& [ak, sk, bucket, prefix, endpoint, external_endpoint, region, use_path_style, role_arn,
external_id] = obj_desc;
+ // Check credential configuration
+ bool is_instance_profile =
+ obj.has_cred_provider_type() &&
+ obj.cred_provider_type() == cloud::CredProviderTypePB::INSTANCE_PROFILE;
+
if (!obj.has_role_arn()) {
- if (!obj.has_ak() || !obj.has_sk()) {
+ // For INSTANCE_PROFILE, ak/sk are optional (obtained from instance metadata)
+ // For other modes, ak/sk are required
+ if (!is_instance_profile && (!obj.has_ak() || !obj.has_sk())) {
code = MetaServiceCode::INVALID_ARGUMENT;
msg = "s3 obj info err " + proto_to_json(*request);
LOG(INFO) << msg;
return -1;
}
- std::string plain_ak = obj.has_ak() ? obj.ak() : "";
- std::string plain_sk = obj.has_sk() ? obj.sk() : "";
- auto ret = encrypt_ak_sk_helper(plain_ak, plain_sk, &encryption_info, &cipher_ak_sk_pair,
- code, msg);
- if (ret != 0) {
- return -1;
- }
+ // Only encrypt ak/sk if they are provided
+ if (obj.has_ak() && obj.has_sk()) {
+ std::string plain_ak = obj.ak();
+ std::string plain_sk = obj.sk();
+ auto ret = encrypt_ak_sk_helper(plain_ak, plain_sk, &encryption_info,
+ &cipher_ak_sk_pair, code, msg);
+ if (ret != 0) {
+ return -1;
+ }
- ak = cipher_ak_sk_pair.first;
- sk = cipher_ak_sk_pair.second;
+ ak = cipher_ak_sk_pair.first;
+ sk = cipher_ak_sk_pair.second;
+ }
} else {
if (obj.has_ak() || obj.has_sk()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -1164,9 +1201,18 @@ static ObjectStoreInfoPB object_info_pb_factory(ObjectStorageDesc& obj_desc,
}
if (!obj.has_role_arn()) {
- last_item.set_ak(std::move(cipher_ak_sk_pair.first));
- last_item.set_sk(std::move(cipher_ak_sk_pair.second));
- last_item.mutable_encryption_info()->CopyFrom(encryption_info);
+ // Only set ak/sk and encryption_info if they are actually provided
+ // For INSTANCE_PROFILE without credentials, skip ak/sk/encryption_info entirely
+ if (!cipher_ak_sk_pair.first.empty() || !cipher_ak_sk_pair.second.empty()) {
+ last_item.set_ak(std::move(cipher_ak_sk_pair.first));
+ last_item.set_sk(std::move(cipher_ak_sk_pair.second));
+ last_item.mutable_encryption_info()->CopyFrom(encryption_info);
+ }
+ // Set INSTANCE_PROFILE if neither role_arn nor ak/sk are provided
+ if (obj.has_cred_provider_type() &&
+ obj.cred_provider_type() == CredProviderTypePB::INSTANCE_PROFILE) {
+ last_item.set_cred_provider_type(CredProviderTypePB::INSTANCE_PROFILE);
+ }
} else {
last_item.set_role_arn(role_arn);
last_item.set_external_id(external_id);
@@ -1322,8 +1368,16 @@ void MetaServiceImpl::alter_storage_vault(google::protobuf::RpcController* contr
return;
}
// ATTN: prefix may be empty
- if (((ak.empty() || sk.empty()) && role_arn.empty()) || bucket.empty() ||
- endpoint.empty() || region.empty()) {
+ // Check credential configuration
+ bool is_instance_profile = obj.has_cred_provider_type() &&
+ obj.cred_provider_type() == CredProviderTypePB::INSTANCE_PROFILE;
+
+ // For INSTANCE_PROFILE, credentials are obtained from instance metadata service
+ // For other modes, either ak/sk or role_arn is required
+ bool has_valid_credentials =
+ is_instance_profile || (!ak.empty() && !sk.empty()) || !role_arn.empty();
+
+ if (!has_valid_credentials || bucket.empty() || endpoint.empty() || region.empty()) {
code = MetaServiceCode::INVALID_ARGUMENT;
msg = "s3 conf info err, please check it";
return;
@@ -1332,9 +1386,11 @@ void MetaServiceImpl::alter_storage_vault(google::protobuf::RpcController* contr
if (!role_arn.empty()) {
if (!obj.has_cred_provider_type() ||
obj.cred_provider_type() != CredProviderTypePB::INSTANCE_PROFILE ||
- !obj.has_provider() || obj.provider() != ObjectStoreInfoPB::S3) {
+ !obj.has_provider() ||
+ (obj.provider() != ObjectStoreInfoPB::S3 &&
+ obj.provider() != ObjectStoreInfoPB::OSS)) {
code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "s3 conf info err with role_arn, please check it";
+ msg = "object storage conf info err with role_arn, please check it";
return;
}
}
@@ -1620,9 +1676,10 @@ void MetaServiceImpl::alter_obj_store_info(google::protobuf::RpcController* cont
return;
}
- if (it.provider() != ObjectStoreInfoPB::S3) {
+ if (it.provider() != ObjectStoreInfoPB::S3 &&
+ it.provider() != ObjectStoreInfoPB::OSS) {
code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "role_arn is only supported for s3 provider";
+ msg = "role_arn is only supported for S3 and OSS providers";
LOG(INFO) << msg << " provider=" << it.provider();
return;
}
diff --git a/cloud/src/recycler/CMakeLists.txt b/cloud/src/recycler/CMakeLists.txt
index 12dc7351853..207caac52ea 100644
--- a/cloud/src/recycler/CMakeLists.txt
+++ b/cloud/src/recycler/CMakeLists.txt
@@ -17,6 +17,10 @@ if(BUILD_AZURE STREQUAL "OFF")
list(REMOVE_ITEM SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/azure_obj_client.cpp")
endif()
+if(BUILD_OSS STREQUAL "OFF")
+ list(REMOVE_ITEM SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/oss_accessor.cpp")
+endif()
+
if(BUILD_CHECK_META STREQUAL "OFF")
list(REMOVE_ITEM SRC_LIST ${CMAKE_CURRENT_SOURCE_DIR}/meta_checker.cpp)
endif ()
diff --git a/cloud/src/recycler/oss_accessor.cpp b/cloud/src/recycler/oss_accessor.cpp
new file mode 100644
index 00000000000..186c4e909cd
--- /dev/null
+++ b/cloud/src/recycler/oss_accessor.cpp
@@ -0,0 +1,659 @@
+// 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 "recycler/oss_accessor.h"
+
+#include <alibabacloud/oss/OssClient.h>
+#include <alibabacloud/oss/client/ClientConfiguration.h>
+#include <bvar/reducer.h>
+#include <gen_cpp/cloud.pb.h>
+#include <time.h>
+
+#include <iomanip>
+#include <memory>
+#include <sstream>
+#include <stdexcept>
+#include <utility>
+
+#include "common/config.h"
+#include "common/encryption_util.h"
+#include "common/logging.h"
+#include "common/stopwatch.h"
+#include "common/string_util.h"
+#include "common/util.h"
+#include "cpp/aws_common.h"
+#include "cpp/oss_credential_provider.h"
+#include "recycler/util.h"
+
+namespace doris::cloud {
+
+namespace oss_bvar {
+bvar::LatencyRecorder oss_get_latency("oss_get");
+bvar::LatencyRecorder oss_put_latency("oss_put");
+bvar::LatencyRecorder oss_delete_object_latency("oss_delete_object");
+bvar::LatencyRecorder oss_delete_objects_latency("oss_delete_objects");
+bvar::LatencyRecorder oss_head_latency("oss_head");
+bvar::LatencyRecorder oss_list_latency("oss_list");
+} // namespace oss_bvar
+
+// Parse OSS LastModified (ISO 8601 UTC) to Unix timestamp
+static int64_t parse_oss_last_modified(const std::string& last_modified_str) {
+ std::tm tm = {};
+ std::istringstream ss(last_modified_str);
+ ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S");
+
+ if (ss.fail()) {
+ LOG(WARNING) << "Failed to parse OSS LastModified: " << last_modified_str;
+ return INT64_MAX; // Treat as infinitely new to avoid premature deletion
+ }
+
+ return static_cast<int64_t>(timegm(&tm)); // timegm() for UTC time
+}
+
+// OSS List Iterator implementation
+class OSSListIterator final : public ListIterator {
+public:
+ OSSListIterator(std::shared_ptr<AlibabaCloud::OSS::OssClient> client, const std::string& bucket,
+ const std::string& prefix, size_t prefix_length)
+ : client_(std::move(client)),
+ bucket_(bucket),
+ prefix_(prefix),
+ prefix_length_(prefix_length),
+ is_truncated_(true),
+ current_index_(0) {
+ // Fetch first batch
+ fetch_next_batch();
+ }
+
+ ~OSSListIterator() override = default;
+
+ bool is_valid() override { return valid_; }
+
+ bool has_next() override {
+ if (current_index_ < objects_.size()) {
+ return true;
+ }
+
+ // Need to fetch next batch
+ if (is_truncated_) {
+ fetch_next_batch();
+ return current_index_ < objects_.size();
+ }
+
+ return false;
+ }
+
+ std::optional<FileMeta> next() override {
+ if (!has_next()) {
+ return std::nullopt;
+ }
+
+ const auto& obj = objects_[current_index_++];
+ return FileMeta {.path = get_relative_path(obj.Key()),
+ .size = obj.Size(),
+ .mtime_s = parse_oss_last_modified(obj.LastModified())};
+ }
+
+private:
+ void fetch_next_batch() {
+ AlibabaCloud::OSS::ListObjectsRequest request(bucket_);
+ request.setPrefix(prefix_);
+ request.setMaxKeys(1000); // OSS default max keys per request
+
+ if (!next_marker_.empty()) {
+ request.setMarker(next_marker_);
+ }
+
+ auto outcome = client_->ListObjects(request);
+ if (!outcome.isSuccess()) {
+ LOG(WARNING) << "OSS ListObjects failed: " << outcome.error().Code() << " - "
+ << outcome.error().Message();
+ valid_ = false;
+ is_truncated_ = false;
+ return;
+ }
+
+ const auto& result = outcome.result();
+ objects_ = result.ObjectSummarys();
+ is_truncated_ = result.IsTruncated();
+ next_marker_ = result.NextMarker();
+ current_index_ = 0;
+ valid_ = true;
+ }
+
+ std::string get_relative_path(const std::string& key) const {
+ if (key.length() >= prefix_length_) {
+ return key.substr(prefix_length_);
+ }
+ return key;
+ }
+
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> client_;
+ std::string bucket_;
+ std::string prefix_;
+ size_t prefix_length_;
+ bool valid_ {false};
+ bool is_truncated_;
+ std::string next_marker_;
+ AlibabaCloud::OSS::ObjectSummaryList objects_;
+ size_t current_index_;
+};
+
+// OSSConf implementation
+
+std::optional<OSSConf> OSSConf::from_obj_store_info(const ObjectStoreInfoPB& obj_info,
+ bool skip_aksk) {
+ // Only process OSS provider
+ if (obj_info.provider() != ObjectStoreInfoPB_Provider_OSS) {
+ return std::nullopt;
+ }
+
+ OSSConf conf;
+ conf.endpoint = normalize_oss_endpoint(obj_info.endpoint());
+ conf.bucket = obj_info.bucket();
+ conf.prefix = obj_info.prefix();
+ conf.region = obj_info.region();
+
+ if (!skip_aksk) {
+ if (obj_info.has_cred_provider_type()) {
+ switch (obj_info.cred_provider_type()) {
+ case CredProviderTypePB::INSTANCE_PROFILE:
+ conf.provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ break;
+ case CredProviderTypePB::DEFAULT:
+ conf.provider_type = OSSCredProviderType::DEFAULT;
+ break;
+ case CredProviderTypePB::SIMPLE:
+ conf.provider_type = OSSCredProviderType::SIMPLE;
+ if (!obj_info.ak().empty() && !obj_info.sk().empty()) {
+ if (obj_info.has_encryption_info()) {
+ AkSkPair plain;
+ int ret = decrypt_ak_sk_helper(obj_info.ak(), obj_info.sk(),
+ obj_info.encryption_info(), &plain);
+ if (ret != 0) {
+ LOG(WARNING) << "Failed to decrypt OSS ak/sk";
+ return std::nullopt;
+ }
+ conf.access_key_id = std::move(plain.first);
+ conf.access_key_secret = std::move(plain.second);
+ } else {
+ conf.access_key_id = obj_info.ak();
+ conf.access_key_secret = obj_info.sk();
+ }
+ }
+ break;
+ default:
+ conf.provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ break;
+ }
+ } else {
+ if (!obj_info.ak().empty() && !obj_info.sk().empty()) {
+ conf.provider_type = OSSCredProviderType::SIMPLE;
+ if (obj_info.has_encryption_info()) {
+ AkSkPair plain;
+ int ret = decrypt_ak_sk_helper(obj_info.ak(), obj_info.sk(),
+ obj_info.encryption_info(), &plain);
+ if (ret != 0) {
+ LOG(WARNING) << "Failed to decrypt OSS ak/sk";
+ return std::nullopt;
+ }
+ conf.access_key_id = std::move(plain.first);
+ conf.access_key_secret = std::move(plain.second);
+ } else {
+ conf.access_key_id = obj_info.ak();
+ conf.access_key_secret = obj_info.sk();
+ }
+ } else {
+ conf.provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+ }
+ }
+
+ if (obj_info.has_role_arn() && !obj_info.role_arn().empty()) {
+ conf.role_arn = obj_info.role_arn();
+ conf.external_id = obj_info.external_id();
+ }
+ }
+
+ return conf;
+}
+
+// OSSAccessor implementation
+
+OSSAccessor::OSSAccessor(OSSConf conf)
+ : StorageVaultAccessor(AccessorType::OSS), conf_(std::move(conf)) {
+ uri_ = fmt::format("oss://{}/{}", conf_.bucket, conf_.prefix.empty() ? "" : conf_.prefix + "/");
+}
+
+OSSAccessor::~OSSAccessor() = default;
+
+int OSSAccessor::create(OSSConf conf, std::shared_ptr<OSSAccessor>* accessor) {
+ *accessor = std::make_shared<OSSAccessor>(std::move(conf));
+ return (*accessor)->init();
+}
+
+int OSSAccessor::init() {
+ static std::once_flag init_flag;
+ std::call_once(init_flag, []() {
+ AlibabaCloud::OSS::InitializeSdk();
+ LOG(INFO) << "Alibaba Cloud OSS SDK initialized";
+ });
+ _ca_cert_file_path =
+ get_valid_ca_cert_path(doris::cloud::split(config::ca_cert_file_paths, ';'));
+ return create_oss_client();
+}
+
+int OSSAccessor::create_oss_client() {
+ std::lock_guard<std::mutex> lock(client_mutex_);
+
+ AlibabaCloud::OSS::ClientConfiguration oss_config;
+ oss_config.maxConnections = conf_.max_connections;
+ oss_config.connectTimeoutMs = conf_.connect_timeout_ms;
+ oss_config.requestTimeoutMs = conf_.request_timeout_ms;
+
+ if (_ca_cert_file_path.empty()) {
+ _ca_cert_file_path =
+ get_valid_ca_cert_path(doris::cloud::split(config::ca_cert_file_paths, ';'));
+ }
+ if (!_ca_cert_file_path.empty()) {
+ oss_config.caFile = _ca_cert_file_path;
+ }
+
+ try {
+ if (conf_.provider_type == OSSCredProviderType::INSTANCE_PROFILE) {
+ if (!conf_.role_arn.empty()) {
+ if (!sts_credential_provider_) {
+ std::string region = conf_.region.empty() ? "cn-hangzhou" : conf_.region;
+ sts_credential_provider_ = std::make_shared<OSSSTSCredentialProvider>(
+ conf_.role_arn, region, conf_.external_id, _ca_cert_file_path);
+ }
+ oss_client_ = std::make_shared<AlibabaCloud::OSS::OssClient>(
+ conf_.endpoint,
+ std::static_pointer_cast<AlibabaCloud::OSS::CredentialsProvider>(
+ sts_credential_provider_),
+ oss_config);
+ LOG(INFO) << "OSS client created with AssumeRole, endpoint=" << conf_.endpoint
+ << ", role_arn=" << conf_.role_arn;
+ } else {
+ if (!credentials_provider_) {
+ credentials_provider_ = std::make_shared<ECSMetadataCredentialsProvider>();
+ }
+ oss_client_ = std::make_shared<AlibabaCloud::OSS::OssClient>(
+ conf_.endpoint,
+ std::static_pointer_cast<AlibabaCloud::OSS::CredentialsProvider>(
+ credentials_provider_),
+ oss_config);
+ LOG(INFO) << "OSS client created with INSTANCE_PROFILE, endpoint="
+ << conf_.endpoint;
+ }
+ } else if (conf_.provider_type == OSSCredProviderType::DEFAULT) {
+ if (!default_credential_provider_) {
+ default_credential_provider_ = std::make_shared<OSSDefaultCredentialsProvider>();
+ }
+ oss_client_ = std::make_shared<AlibabaCloud::OSS::OssClient>(
+ conf_.endpoint,
+ std::static_pointer_cast<AlibabaCloud::OSS::CredentialsProvider>(
+ default_credential_provider_),
+ oss_config);
+ LOG(INFO) << "OSS client created with DEFAULT provider, endpoint=" << conf_.endpoint;
+ } else if (conf_.provider_type == OSSCredProviderType::SIMPLE) {
+ AlibabaCloud::OSS::Credentials creds(conf_.access_key_id, conf_.access_key_secret,
+ conf_.security_token);
+ oss_client_ = std::make_shared<AlibabaCloud::OSS::OssClient>(conf_.endpoint, creds,
+ oss_config);
+ LOG(INFO) << "OSS client created with SIMPLE credentials, endpoint=" << conf_.endpoint;
+ } else {
+ LOG(ERROR) << "Unsupported OSS credential provider type";
+ return -1;
+ }
+ } catch (const std::exception& e) {
+ LOG(ERROR) << "Failed to create OSS client: " << e.what();
+ return -1;
+ }
+
+ return 0;
+}
+
+int OSSAccessor::refresh_client_if_needed() {
+ // Credential providers manage their own refresh internally via getCredentials().
+ return 0;
+}
+
+std::string OSSAccessor::get_key(const std::string& relative_path) const {
+ std::string path = relative_path;
+ if (!path.empty() && path[0] == '/') {
+ LOG(WARNING) << "OSS relative path should not start with '/': " << relative_path;
+ path = path.substr(1);
+ }
+ return conf_.prefix.empty() ? path : conf_.prefix + "/" + path;
+}
+
+std::string OSSAccessor::to_uri(const std::string& relative_path) const {
+ return uri_ + relative_path;
+}
+
+int OSSAccessor::convert_oss_error_code(const std::string& error_code) const {
+ if (error_code == "NoSuchKey" || error_code == "NoSuchBucket") {
+ return 1; // Not found
+ } else if (error_code == "AccessDenied" || error_code == "InvalidAccessKeyId") {
+ return -2; // Access denied
+ } else if (error_code == "SecurityTokenExpired") {
+ LOG(WARNING) << "OSS security token expired, will refresh on next operation";
+ return -3; // Credentials expired
+ } else if (error_code == "RequestTimeout" || error_code == "ConnectionTimeout") {
+ return -4; // Timeout
+ }
+
+ LOG(WARNING) << "OSS operation failed with error code: " << error_code;
+ return -1; // Generic error
+}
+
+std::shared_ptr<AlibabaCloud::OSS::OssClient> OSSAccessor::get_client() const {
+ std::lock_guard<std::mutex> lock(client_mutex_);
+ return oss_client_;
+}
+
+int OSSAccessor::put_file(const std::string& path, const std::string& content) {
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_put_latency);
+
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+
+ std::string key = get_key(path);
+
+ // Create stream from content
+ std::shared_ptr<std::stringstream> content_stream =
+ std::make_shared<std::stringstream>(content);
+
+ AlibabaCloud::OSS::PutObjectRequest request(conf_.bucket, key, content_stream);
+
+ auto outcome = client->PutObject(request);
+ if (!outcome.isSuccess()) {
+ LOG(WARNING) << "OSS PutObject failed: " << outcome.error().Code() << " - "
+ << outcome.error().Message() << ", key: " << key;
+ return convert_oss_error_code(outcome.error().Code());
+ }
+
+ VLOG(1) << "OSS PutObject success: " << key << ", size: " << content.size();
+ return 0;
+}
+
+int OSSAccessor::delete_file(const std::string& path) {
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_delete_object_latency);
+
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+
+ std::string key = get_key(path);
+
+ auto outcome = client->DeleteObject(conf_.bucket, key);
+ if (!outcome.isSuccess()) {
+ // OSS DeleteObject returns success even if object doesn't exist
+ // Only log real errors
+ std::string error_code = outcome.error().Code();
+ if (error_code != "NoSuchKey") {
+ LOG(WARNING) << "OSS DeleteObject failed: " << error_code << " - "
+ << outcome.error().Message() << ", key: " << key;
+ return convert_oss_error_code(error_code);
+ }
+ }
+
+ VLOG(1) << "OSS DeleteObject success: " << key;
+ return 0;
+}
+
+int OSSAccessor::delete_files(const std::vector<std::string>& paths) {
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_delete_objects_latency);
+
+ if (paths.empty()) {
+ return 0;
+ }
+
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+
+ // OSS DeleteObjects supports batch delete (max 1000 keys per request)
+ const size_t batch_size = 1000;
+
+ for (size_t i = 0; i < paths.size(); i += batch_size) {
+ size_t end = std::min(i + batch_size, paths.size());
+
+ AlibabaCloud::OSS::DeletedKeyList keys;
+ for (size_t j = i; j < end; ++j) {
+ keys.push_back(get_key(paths[j]));
+ }
+
+ AlibabaCloud::OSS::DeleteObjectsRequest request(conf_.bucket);
+ request.setKeyList(keys);
+
+ auto outcome = client->DeleteObjects(request);
+ if (!outcome.isSuccess()) {
+ LOG(WARNING) << "OSS DeleteObjects failed: " << outcome.error().Code() << " - "
+ << outcome.error().Message();
+ return convert_oss_error_code(outcome.error().Code());
+ }
+
+ VLOG(1) << "OSS DeleteObjects success: deleted " << outcome.result().keyList().size()
+ << " objects (" << (end - i) << " requested)";
+ }
+
+ return 0;
+}
+
+int OSSAccessor::delete_prefix(const std::string& path_prefix, int64_t expiration_time) {
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+
+ std::string prefix = get_key(path_prefix);
+
+ // List all objects with prefix and delete them in batches
+ std::vector<std::string> keys_to_delete;
+ const size_t batch_size = 1000;
+
+ bool is_truncated = true;
+ std::string marker;
+
+ while (is_truncated) {
+ AlibabaCloud::OSS::ListObjectsRequest list_request(conf_.bucket);
+ list_request.setPrefix(prefix);
+ list_request.setMaxKeys(1000);
+
+ if (!marker.empty()) {
+ list_request.setMarker(marker);
+ }
+
+ auto outcome = client->ListObjects(list_request);
+ if (!outcome.isSuccess()) {
+ LOG(WARNING) << "OSS ListObjects failed: " << outcome.error().Code() << " - "
+ << outcome.error().Message();
+ return convert_oss_error_code(outcome.error().Code());
+ }
+
+ const auto& result = outcome.result();
+ const auto& objects = result.ObjectSummarys();
+
+ for (const auto& obj : objects) {
+ // Check expiration time if specified
+ if (expiration_time > 0) {
+ int64_t obj_mtime = parse_oss_last_modified(obj.LastModified());
+ if (obj_mtime >= expiration_time) {
+ continue; // Skip objects newer than expiration time
+ }
+ }
+
+ keys_to_delete.push_back(obj.Key());
+
+ // Delete in batches
+ if (keys_to_delete.size() >= batch_size) {
+ AlibabaCloud::OSS::DeletedKeyList batch_keys(keys_to_delete.begin(),
+ keys_to_delete.end());
+ AlibabaCloud::OSS::DeleteObjectsRequest delete_request(conf_.bucket);
+ delete_request.setKeyList(batch_keys);
+
+ auto delete_outcome = client->DeleteObjects(delete_request);
+ if (!delete_outcome.isSuccess()) {
+ LOG(WARNING) << "OSS DeleteObjects failed: " << delete_outcome.error().Code()
+ << " - " << delete_outcome.error().Message();
+ return convert_oss_error_code(delete_outcome.error().Code());
+ }
+
+ VLOG(1) << "OSS deleted batch of " << delete_outcome.result().keyList().size()
+ << " objects";
+ keys_to_delete.clear();
+ }
+ }
+
+ is_truncated = result.IsTruncated();
+ marker = result.NextMarker();
+ }
+
+ // Delete remaining keys
+ if (!keys_to_delete.empty()) {
+ AlibabaCloud::OSS::DeletedKeyList batch_keys(keys_to_delete.begin(), keys_to_delete.end());
+ AlibabaCloud::OSS::DeleteObjectsRequest delete_request(conf_.bucket);
+ delete_request.setKeyList(batch_keys);
+
+ auto delete_outcome = client->DeleteObjects(delete_request);
+ if (!delete_outcome.isSuccess()) {
+ LOG(WARNING) << "OSS DeleteObjects failed: " << delete_outcome.error().Code() << " - "
+ << delete_outcome.error().Message();
+ return convert_oss_error_code(delete_outcome.error().Code());
+ }
+
+ VLOG(1) << "OSS deleted final batch of " << delete_outcome.result().keyList().size()
+ << " objects";
+ }
+
+ return 0;
+}
+
+int OSSAccessor::delete_directory(const std::string& dir_path) {
+ auto norm_dir_path = dir_path;
+ strip_leading(norm_dir_path, "/");
+ if (norm_dir_path.empty()) {
+ LOG(WARNING) << "invalid dir_path " << dir_path;
+ return -1;
+ }
+
+ if (!norm_dir_path.ends_with('/')) {
+ norm_dir_path += '/';
+ }
+ return delete_prefix(norm_dir_path, 0);
+}
+
+int OSSAccessor::delete_all(int64_t expiration_time) {
+ // Delete all objects under the prefix
+ return delete_prefix("", expiration_time);
+}
+
+int OSSAccessor::list_directory(const std::string& dir_path, std::unique_ptr<ListIterator>* res) {
+ auto norm_dir_path = dir_path;
+ strip_leading(norm_dir_path, "/");
+ if (norm_dir_path.empty()) {
+ LOG(WARNING) << "invalid dir_path " << dir_path;
+ return -1;
+ }
+
+ if (!norm_dir_path.ends_with('/')) {
+ norm_dir_path += '/';
+ }
+ return list_prefix(norm_dir_path, res);
+}
+
+int OSSAccessor::list_all(std::unique_ptr<ListIterator>* res) {
+ return list_prefix("", res);
+}
+
+int OSSAccessor::list_prefix(const std::string& path_prefix, std::unique_ptr<ListIterator>* res) {
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_list_latency);
+
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+
+ std::string prefix = get_key(path_prefix);
+
+ *res = std::make_unique<OSSListIterator>(client, conf_.bucket, prefix,
+ conf_.prefix.empty() ? 0 : conf_.prefix.length() + 1);
+ return 0;
+}
+
+int OSSAccessor::exists(const std::string& path) {
+ SCOPED_BVAR_LATENCY(oss_bvar::oss_head_latency);
+
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+
+ std::string key = get_key(path);
+
+ auto outcome = client->HeadObject(conf_.bucket, key);
+ if (outcome.isSuccess()) {
+ VLOG(2) << "OSS exists check: " << key << " -> found";
+ return 0;
+ } else if (outcome.error().Code() == "NoSuchKey") {
+ VLOG(2) << "OSS exists check: " << key << " -> not found";
+ return 1;
+ } else {
+ LOG(WARNING) << "OSS HeadObject failed: " << outcome.error().Code() << " - "
+ << outcome.error().Message() << ", key=" << key;
+ return -1;
+ }
+}
+
+int OSSAccessor::abort_multipart_upload(const std::string& path, const std::string& upload_id) {
+ int ret = refresh_client_if_needed();
+ if (ret != 0) {
+ return ret;
+ }
+
+ auto client = get_client();
+ std::string key = get_key(path);
+
+ AlibabaCloud::OSS::AbortMultipartUploadRequest request(conf_.bucket, key, upload_id);
+ auto outcome = client->AbortMultipartUpload(request);
+ if (!outcome.isSuccess()) {
+ LOG(WARNING) << "OSS AbortMultipartUpload failed: " << outcome.error().Code() << " - "
+ << outcome.error().Message() << ", key=" << key << ", upload_id=" << upload_id;
+ return -1;
+ }
+
+ return 0;
+}
+
+} // namespace doris::cloud
diff --git a/cloud/src/recycler/oss_accessor.h b/cloud/src/recycler/oss_accessor.h
new file mode 100644
index 00000000000..8d7195e4544
--- /dev/null
+++ b/cloud/src/recycler/oss_accessor.h
@@ -0,0 +1,167 @@
+// 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.
+
+#pragma once
+
+#include <bvar/latency_recorder.h>
+
+#include <cstdint>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "cpp/oss_common.h"
+#include "recycler/storage_vault_accessor.h"
+
+// Forward declare OSS SDK types to avoid header dependency in .h
+namespace AlibabaCloud {
+namespace OSS {
+class OssClient;
+class Credentials;
+} // namespace OSS
+} // namespace AlibabaCloud
+
+namespace doris {
+// Forward declare credential providers
+class ECSMetadataCredentialsProvider;
+class OSSSTSCredentialProvider;
+class OSSDefaultCredentialsProvider;
+} // namespace doris
+
+namespace doris::cloud {
+class ObjectStoreInfoPB;
+
+namespace oss_bvar {
+extern bvar::LatencyRecorder oss_get_latency;
+extern bvar::LatencyRecorder oss_put_latency;
+extern bvar::LatencyRecorder oss_delete_object_latency;
+extern bvar::LatencyRecorder oss_delete_objects_latency;
+extern bvar::LatencyRecorder oss_head_latency;
+extern bvar::LatencyRecorder oss_list_latency;
+} // namespace oss_bvar
+
+// OSS Configuration
+struct OSSConf {
+ std::string endpoint;
+ std::string bucket;
+ std::string prefix;
+ std::string region;
+
+ // Credentials (empty for instance profile)
+ std::string access_key_id;
+ std::string access_key_secret;
+ std::string security_token;
+
+ // AssumeRole configuration (for cross-account or elevated permissions)
+ std::string role_arn; // RAM role ARN to assume
+ std::string external_id; // External ID for cross-account AssumeRole security
+
+ OSSCredProviderType provider_type = OSSCredProviderType::INSTANCE_PROFILE;
+
+ // Connection settings
+ int max_connections = 100;
+ int connect_timeout_ms = 10000;
+ int request_timeout_ms = 30000;
+
+ // Create OSSConf from ObjectStoreInfoPB
+ // skip_aksk: if true, don't extract AK/SK from obj_info (used for logging)
+ static std::optional<OSSConf> from_obj_store_info(const ObjectStoreInfoPB& obj_info,
+ bool skip_aksk = false);
+};
+
+class OSSAccessor : public StorageVaultAccessor {
+public:
+ explicit OSSAccessor(OSSConf conf);
+ ~OSSAccessor() override;
+
+ // Create OSSAccessor instance and initialize
+ // returns 0 for success otherwise error
+ static int create(OSSConf conf, std::shared_ptr<OSSAccessor>* accessor);
+
+ // Initialize OSS client
+ // returns 0 for success otherwise error
+ int init();
+
+ // StorageVaultAccessor interface implementations
+ // All methods return 0 for success, negative for error
+
+ // Delete objects with path prefix
+ // If expiration_time > 0, only delete objects older than expiration_time
+ int delete_prefix(const std::string& path_prefix, int64_t expiration_time = 0) override;
+
+ // Delete entire directory recursively
+ int delete_directory(const std::string& dir_path) override;
+
+ // Delete all objects in the vault
+ int delete_all(int64_t expiration_time = 0) override;
+
+ // Delete multiple files in a batch
+ int delete_files(const std::vector<std::string>& paths) override;
+
+ // Delete a single file
+ int delete_file(const std::string& path) override;
+
+ // List files in directory recursively
+ int list_directory(const std::string& dir_path, std::unique_ptr<ListIterator>* res) override;
+
+ // List all files in the vault
+ int list_all(std::unique_ptr<ListIterator>* res) override;
+
+ // Upload a file (for testing)
+ int put_file(const std::string& path, const std::string& content) override;
+
+ // Check if file exists
+ // returns 0 if exists, 1 if not found, negative for error
+ int exists(const std::string& path) override;
+
+ // Abort an in-progress multipart upload
+ int abort_multipart_upload(const std::string& path, const std::string& upload_id) override;
+
+protected:
+ // List objects with given prefix
+ int list_prefix(const std::string& path_prefix, std::unique_ptr<ListIterator>* res);
+
+ // Get full OSS key from relative path
+ std::string get_key(const std::string& relative_path) const;
+
+ // Convert relative path to full URI
+ std::string to_uri(const std::string& relative_path) const;
+
+ // Refresh OSS client if credentials expired
+ int refresh_client_if_needed();
+
+ // Create OSS client based on credential provider type
+ int create_oss_client();
+
+ // Convert OSS error to return code
+ int convert_oss_error_code(const std::string& error_code) const;
+
+ // Get thread-safe copy of OSS client (for internal use by accessor methods)
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> get_client() const;
+
+ OSSConf conf_;
+ std::shared_ptr<ECSMetadataCredentialsProvider> credentials_provider_;
+ std::shared_ptr<OSSSTSCredentialProvider> sts_credential_provider_;
+ std::shared_ptr<doris::OSSDefaultCredentialsProvider> default_credential_provider_;
+ std::shared_ptr<AlibabaCloud::OSS::OssClient> oss_client_;
+ mutable std::mutex client_mutex_;
+ std::string _ca_cert_file_path;
+};
+
+} // namespace doris::cloud
diff --git a/cloud/src/recycler/recycler.cpp b/cloud/src/recycler/recycler.cpp
index 00cf9045622..d212feef10b 100644
--- a/cloud/src/recycler/recycler.cpp
+++ b/cloud/src/recycler/recycler.cpp
@@ -58,6 +58,9 @@
#ifdef ENABLE_HDFS_STORAGE_VAULT
#include "recycler/hdfs_accessor.h"
#endif
+#ifdef USE_OSS
+#include "recycler/oss_accessor.h"
+#endif
#include "recycler/s3_accessor.h"
#include "recycler/storage_vault_accessor.h"
#ifdef UNIT_TEST
@@ -605,6 +608,28 @@ int InstanceRecycler::init_obj_store_accessors() {
#ifdef UNIT_TEST
auto accessor = std::make_shared<MockAccessor>();
#else
+#ifdef USE_OSS
+ // Check if this is OSS provider
+ if (obj_info.provider() == ObjectStoreInfoPB_Provider_OSS) {
+ auto oss_conf = OSSConf::from_obj_store_info(obj_info);
+ if (!oss_conf) {
+ LOG(WARNING) << "failed to init OSS accessor, instance_id=" << instance_id_
+ << " resource_id=" << obj_info.id();
+ return -1;
+ }
+
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(std::move(*oss_conf), &accessor);
+ if (ret != 0) {
+ LOG(WARNING) << "failed to init OSS accessor. instance_id=" << instance_id_
+ << " resource_id=" << obj_info.id();
+ return ret;
+ }
+ accessor_map_.emplace(obj_info.id(), std::move(accessor));
+ continue;
+ }
+#endif
+ // S3, GCP, Azure, etc. - use S3Accessor
auto s3_conf = S3Conf::from_obj_store_info(obj_info);
if (!s3_conf) {
LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
@@ -682,26 +707,59 @@ int InstanceRecycler::init_storage_vault_accessors() {
<< "but HDFS storage vaults were detected";
#endif
} else if (vault.has_obj_info()) {
- auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
- if (!s3_conf) {
- LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
- << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
- continue;
- }
+ const auto& obj_info = vault.obj_info();
+
+#ifdef USE_OSS
+ // Check if this is OSS provider
+ if (obj_info.provider() == ObjectStoreInfoPB_Provider_OSS) {
+ auto oss_conf = OSSConf::from_obj_store_info(obj_info);
+ if (!oss_conf) {
+ LOG(WARNING) << "failed to init OSS accessor, invalid conf, instance_id="
+ << instance_id_ << " vault_id=" << vault.id()
+ << " oss_vault=" << encryt_sk(obj_info.ShortDebugString());
+ continue;
+ }
- std::shared_ptr<S3Accessor> accessor;
- int ret = S3Accessor::create(*s3_conf, &accessor);
- if (ret != 0) {
- LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
- << " resource_id=" << vault.id() << " name=" << vault.name()
- << " ret=" << ret
- << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
- continue;
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(*oss_conf, &accessor);
+ if (ret != 0) {
+ LOG(WARNING) << "failed to init OSS accessor. instance_id=" << instance_id_
+ << " resource_id=" << vault.id() << " name=" << vault.name()
+ << " ret=" << ret
+ << " oss_vault=" << encryt_sk(obj_info.ShortDebugString());
+ continue;
+ }
+ LOG(INFO) << "succeed to init OSS accessor. instance_id=" << instance_id_
+ << " resource_id=" << vault.id() << " name=" << vault.name()
+ << " ret=" << ret
+ << " oss_vault=" << encryt_sk(obj_info.ShortDebugString());
+ accessor_map_.emplace(vault.id(), std::move(accessor));
+ } else
+#endif
+ {
+ // S3, GCP, Azure, etc. - use S3Accessor
+ auto s3_conf = S3Conf::from_obj_store_info(obj_info);
+ if (!s3_conf) {
+ LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
+ << instance_id_
+ << " vault=" << encryt_sk(obj_info.ShortDebugString());
+ continue;
+ }
+
+ std::shared_ptr<S3Accessor> accessor;
+ int ret = S3Accessor::create(*s3_conf, &accessor);
+ if (ret != 0) {
+ LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
+ << " resource_id=" << vault.id() << " name=" << vault.name()
+ << " ret=" << ret
+ << " vault=" << encryt_sk(obj_info.ShortDebugString());
+ continue;
+ }
+ LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
+ << " resource_id=" << vault.id() << " name=" << vault.name()
+ << " ret=" << ret << " vault=" << encryt_sk(obj_info.ShortDebugString());
+ accessor_map_.emplace(vault.id(), std::move(accessor));
}
- LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
- << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
- << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
- accessor_map_.emplace(vault.id(), std::move(accessor));
}
}
diff --git a/cloud/src/recycler/storage_vault_accessor.h b/cloud/src/recycler/storage_vault_accessor.h
index 259148e544d..811a1355e15 100644
--- a/cloud/src/recycler/storage_vault_accessor.h
+++ b/cloud/src/recycler/storage_vault_accessor.h
@@ -38,6 +38,7 @@ enum class AccessorType : uint8_t {
MOCK,
S3,
HDFS,
+ OSS,
};
class ListIterator {
diff --git a/cloud/test/CMakeLists.txt b/cloud/test/CMakeLists.txt
index f57c9d46282..febd1e80572 100644
--- a/cloud/test/CMakeLists.txt
+++ b/cloud/test/CMakeLists.txt
@@ -75,6 +75,12 @@ add_executable(s3_accessor_client_test s3_accessor_client_test.cpp)
add_executable(s3_accessor_mock_test s3_accessor_mock_test.cpp)
+option(ENABLE_OSS_STORAGE_VAULT "Enable Alibaba Cloud OSS storage support" ON)
+if (ENABLE_OSS_STORAGE_VAULT)
+ add_compile_definitions(ENABLE_OSS_STORAGE_VAULT)
+ add_executable(oss_accessor_test oss_accessor_test.cpp)
+endif()
+
option(ENABLE_HDFS_STORAGE_VAULT "Enable HDFS storage support" ON)
if (ENABLE_HDFS_STORAGE_VAULT)
add_compile_definitions(ENABLE_HDFS_STORAGE_VAULT)
@@ -134,6 +140,11 @@ target_link_libraries(s3_accessor_client_test ${TEST_LINK_LIBS})
target_link_libraries(s3_accessor_mock_test ${TEST_LINK_LIBS})
+option(ENABLE_OSS_STORAGE_VAULT "Enable Alibaba Cloud OSS storage support" ON)
+if (ENABLE_OSS_STORAGE_VAULT)
+ target_link_libraries(oss_accessor_test ${TEST_LINK_LIBS})
+endif()
+
option(ENABLE_HDFS_STORAGE_VAULT "Enable HDFS storage support" ON)
if (ENABLE_HDFS_STORAGE_VAULT)
target_link_libraries(hdfs_accessor_test ${TEST_LINK_LIBS})
diff --git a/cloud/test/oss_accessor_test.cpp b/cloud/test/oss_accessor_test.cpp
new file mode 100644
index 00000000000..3b437f9f8a0
--- /dev/null
+++ b/cloud/test/oss_accessor_test.cpp
@@ -0,0 +1,562 @@
+// 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 "recycler/oss_accessor.h"
+
+#include <butil/guid.h>
+#include <gen_cpp/cloud.pb.h>
+#include <gtest/gtest.h>
+
+#include <chrono>
+#include <unordered_set>
+
+#include "common/config.h"
+#include "common/configbase.h"
+#include "common/logging.h"
+#include "cpp/sync_point.h"
+
+using namespace doris;
+
+int main(int argc, char** argv) {
+ const std::string conf_file = "doris_cloud.conf";
+ if (!cloud::config::init(conf_file.c_str(), true)) {
+ std::cerr << "failed to init config file, conf=" << conf_file << std::endl;
+ return -1;
+ }
+
+ if (!cloud::init_glog("oss_accessor_test")) {
+ std::cerr << "failed to init glog" << std::endl;
+ return -1;
+ }
+ LOG(INFO) << "oss_accessor_test starting";
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
+
+namespace doris::cloud {
+namespace {
+
+// ---------------------------------------------------------------------------
+// Shared test helper — mirrors test_s3_accessor() in s3_accessor_test.cpp
+// Exercises every StorageVaultAccessor operation in a deterministic sequence.
+// ---------------------------------------------------------------------------
+void test_oss_accessor(OSSAccessor& accessor) {
+ std::string file1 = "data/10000/1_0.dat";
+
+ // delete_directory with empty path must fail (guard against whole-bucket wipe)
+ int ret = accessor.delete_directory("");
+ ASSERT_NE(ret, 0);
+
+ // clean slate
+ ret = accessor.delete_all();
+ ASSERT_EQ(ret, 0);
+
+ // put + exists
+ ret = accessor.put_file(file1, "");
+ ASSERT_EQ(ret, 0);
+ ret = accessor.exists(file1);
+ ASSERT_EQ(ret, 0);
+
+ // list_directory — with and without trailing slash
+ std::unique_ptr<ListIterator> iter;
+ ret = accessor.list_directory("data", &iter);
+ ASSERT_EQ(ret, 0);
+ ASSERT_TRUE(iter);
+ ASSERT_TRUE(iter->is_valid());
+ ASSERT_TRUE(iter->has_next());
+ ASSERT_EQ(iter->next()->path, file1);
+ ASSERT_FALSE(iter->has_next());
+
+ ret = accessor.list_directory("data/", &iter);
+ ASSERT_EQ(ret, 0);
+ ASSERT_TRUE(iter->is_valid());
+ ASSERT_TRUE(iter->has_next());
+ ASSERT_EQ(iter->next()->path, file1);
+ ASSERT_FALSE(iter->has_next());
+ ASSERT_FALSE(iter->next());
+
+ // list_directory with non-matching prefix returns empty
+ ret = accessor.list_directory("data/100", &iter);
+ ASSERT_EQ(ret, 0);
+ ASSERT_FALSE(iter->has_next());
+ ASSERT_FALSE(iter->next());
+
+ // delete_file + existence check
+ ret = accessor.delete_file(file1);
+ ASSERT_EQ(ret, 0);
+ ret = accessor.exists(file1);
+ ASSERT_EQ(ret, 1); // 1 = not found
+
+ // list_directory with empty path must fail
+ ret = accessor.list_directory("", &iter);
+ ASSERT_NE(ret, 0);
+
+ // list_all on empty vault
+ ret = accessor.list_all(&iter);
+ ASSERT_EQ(ret, 0);
+ ASSERT_FALSE(iter->has_next());
+ ASSERT_FALSE(iter->next());
+
+ // delete_file on already-deleted key is idempotent
+ ret = accessor.delete_file(file1);
+ EXPECT_EQ(ret, 0);
+
+ // -----------------------------------------------------------------------
+ // Bulk operations: 5 dirs × 5 files = 25 objects
+ // -----------------------------------------------------------------------
+ std::vector<std::string> files;
+ for (int dir = 10000; dir < 10005; ++dir) {
+ for (int suffix = 0; suffix < 5; ++suffix) {
+ files.push_back(fmt::format("data/{}/1/{}.dat", dir, suffix));
+ }
+ }
+ for (auto&& file : files) {
+ ret = accessor.put_file(file, "");
+ ASSERT_EQ(ret, 0);
+ }
+
+ // list_all — verify all 25 files present, mtime is recent
+ std::unordered_set<std::string> list_files;
+ ret = accessor.list_all(&iter);
+ ASSERT_EQ(ret, 0);
+ using namespace std::chrono;
+ int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
+ for (auto f = iter->next(); f.has_value(); f = iter->next()) {
+ EXPECT_LT(now - f->mtime_s, 60) << "mtime should be within last 60s: " << f->path;
+ list_files.insert(std::move(f->path));
+ }
+ ASSERT_EQ(list_files.size(), files.size());
+ for (auto&& file : files) {
+ EXPECT_TRUE(list_files.contains(file));
+ }
+
+ // delete_files (batch) — remove 5 files from the back
+ std::vector<std::string> to_delete_files;
+ to_delete_files.reserve(5);
+ for (int i = 0; i < 5; ++i) {
+ to_delete_files.push_back(std::move(files.back()));
+ files.pop_back();
+ }
+ ret = accessor.delete_files(to_delete_files);
+ ASSERT_EQ(ret, 0);
+
+ ret = accessor.list_all(&iter);
+ ASSERT_EQ(ret, 0);
+ list_files.clear();
+ for (auto f = iter->next(); f.has_value(); f = iter->next()) {
+ list_files.insert(std::move(f->path));
+ }
+ ASSERT_EQ(list_files.size(), files.size());
+ for (auto&& file : files) {
+ EXPECT_TRUE(list_files.contains(file));
+ }
+
+ // delete_directory — remove entire data/10001/ subtree
+ std::string to_delete_dir = "data/10001";
+ ret = accessor.delete_directory(to_delete_dir);
+ ASSERT_EQ(ret, 0);
+ files.erase(std::remove_if(files.begin(), files.end(),
+ [&](auto&& file) { return file.starts_with(to_delete_dir); }),
+ files.end());
+ ret = accessor.list_all(&iter);
+ ASSERT_EQ(ret, 0);
+ list_files.clear();
+ for (auto f = iter->next(); f.has_value(); f = iter->next()) {
+ list_files.insert(std::move(f->path));
+ }
+ ASSERT_EQ(list_files.size(), files.size());
+ for (auto&& file : files) {
+ EXPECT_TRUE(list_files.contains(file));
+ }
+
+ // delete_prefix — remove data/10003/ using prefix deletion
+ std::string to_delete_prefix = "data/10003/";
+ ret = accessor.delete_prefix(to_delete_prefix);
+ ASSERT_EQ(ret, 0);
+ files.erase(std::remove_if(files.begin(), files.end(),
+ [&](auto&& file) { return file.starts_with(to_delete_prefix); }),
+ files.end());
+ ret = accessor.list_all(&iter);
+ ASSERT_EQ(ret, 0);
+ list_files.clear();
+ for (auto f = iter->next(); f.has_value(); f = iter->next()) {
+ list_files.insert(std::move(f->path));
+ }
+ ASSERT_EQ(list_files.size(), files.size());
+ for (auto&& file : files) {
+ EXPECT_TRUE(list_files.contains(file));
+ }
+
+ // final cleanup
+ ret = accessor.delete_all();
+ ASSERT_EQ(ret, 0);
+ ret = accessor.list_all(&iter);
+ ASSERT_EQ(ret, 0);
+ ASSERT_FALSE(iter->has_next());
+ ASSERT_FALSE(iter->next());
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+// OSSAccessorTest — AK/SK static credentials (mirrors S3AccessorTest::s3)
+// Skipped when test_oss_ak config is empty.
+// ---------------------------------------------------------------------------
+class OSSAccessorTest : public testing::Test {
+ void SetUp() override {
+ if (cloud::config::test_oss_ak.empty()) {
+ GTEST_SKIP() << "empty test_oss_ak, skip OSSAccessorTest";
+ }
+ }
+};
+
+TEST_F(OSSAccessorTest, oss_simple_credentials) {
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(
+ OSSConf {
+ .endpoint = config::test_oss_endpoint,
+ .bucket = config::test_oss_bucket,
+ .prefix = config::test_oss_prefix + "/OSSAccessorTest/" + butil::GenerateGUID(),
+ .region = config::test_oss_region,
+ .access_key_id = config::test_oss_ak,
+ .access_key_secret = config::test_oss_sk,
+ .provider_type = OSSCredProviderType::SIMPLE,
+ },
+ &accessor);
+ ASSERT_EQ(ret, 0);
+
+ // Use SyncPoint to force small page size — exercises pagination logic
+ auto* sp = SyncPoint::get_instance();
+ std::vector<SyncPoint::CallbackGuard> guards;
+ sp->set_call_back(
+ "OSSListIterator::max_keys",
+ [](auto&& args) {
+ auto* max_keys = try_any_cast<int*>(args[0]);
+ *max_keys = 7;
+ },
+ &guards.emplace_back());
+ sp->set_call_back(
+ "OSSAccessor::delete_objects_batch_size",
+ [](auto&& args) {
+ auto* batch_size = try_any_cast<size_t*>(args[0]);
+ *batch_size = 7;
+ },
+ &guards.emplace_back());
+
+ test_oss_accessor(*accessor);
+}
+
+// ---------------------------------------------------------------------------
+// OSSAccessorTest — from_obj_store_info with SIMPLE provider
+// Mirrors S3AccessorTest::path_style_test for conf construction path.
+// ---------------------------------------------------------------------------
+TEST_F(OSSAccessorTest, oss_conf_from_obj_store_info) {
+ ObjectStoreInfoPB obj_info;
+ obj_info.set_provider(ObjectStoreInfoPB_Provider_OSS);
+ obj_info.set_ak(config::test_oss_ak);
+ obj_info.set_sk(config::test_oss_sk);
+ obj_info.set_endpoint(config::test_oss_endpoint);
+ obj_info.set_region(config::test_oss_region);
+ obj_info.set_bucket(config::test_oss_bucket);
+ obj_info.set_prefix(config::test_oss_prefix + "/OSSAccessorTest/conf/" + butil::GenerateGUID());
+
+ auto conf = OSSConf::from_obj_store_info(obj_info);
+ ASSERT_TRUE(conf.has_value());
+ EXPECT_FALSE(conf->endpoint.empty());
+ EXPECT_FALSE(conf->bucket.empty());
+ EXPECT_FALSE(conf->region.empty());
+ EXPECT_FALSE(conf->access_key_id.empty());
+ EXPECT_FALSE(conf->access_key_secret.empty());
+
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(*conf, &accessor);
+ ASSERT_EQ(ret, 0);
+
+ // Basic smoke test: put → exists → delete → not-exists
+ const std::string test_file = "smoke/conf_test.dat";
+ ret = accessor->put_file(test_file, "hello");
+ ASSERT_EQ(ret, 0);
+ ret = accessor->exists(test_file);
+ ASSERT_EQ(ret, 0);
+ ret = accessor->delete_file(test_file);
+ ASSERT_EQ(ret, 0);
+ ret = accessor->exists(test_file);
+ ASSERT_EQ(ret, 1);
+
+ ret = accessor->delete_all();
+ ASSERT_EQ(ret, 0);
+}
+
+// ---------------------------------------------------------------------------
+// OSSAccessorTest — skip_aksk flag (used for logging paths)
+// ---------------------------------------------------------------------------
+TEST_F(OSSAccessorTest, oss_conf_skip_aksk) {
+ ObjectStoreInfoPB obj_info;
+ obj_info.set_provider(ObjectStoreInfoPB_Provider_OSS);
+ obj_info.set_ak(config::test_oss_ak);
+ obj_info.set_sk(config::test_oss_sk);
+ obj_info.set_endpoint(config::test_oss_endpoint);
+ obj_info.set_region(config::test_oss_region);
+ obj_info.set_bucket(config::test_oss_bucket);
+ obj_info.set_prefix(config::test_oss_prefix);
+
+ auto conf = OSSConf::from_obj_store_info(obj_info, /*skip_aksk=*/true);
+ ASSERT_TRUE(conf.has_value());
+ EXPECT_TRUE(conf->access_key_id.empty()) << "skip_aksk=true must not populate access_key_id";
+ EXPECT_TRUE(conf->access_key_secret.empty())
+ << "skip_aksk=true must not populate access_key_secret";
+ EXPECT_FALSE(conf->endpoint.empty());
+ EXPECT_FALSE(conf->bucket.empty());
+}
+
+// ---------------------------------------------------------------------------
+// OSSAccessorRoleTest — AssumeRole via ECS instance profile + STS
+// Mirrors S3AccessorRoleTest::s3 exactly.
+// Environment variables:
+// OSS_ROLE_ARN, OSS_EXTERNAL_ID, OSS_ENDPOINT, OSS_REGION, OSS_BUCKET,
+// OSS_PREFIX
+// ---------------------------------------------------------------------------
+class OSSAccessorRoleTest : public testing::Test {
+ static void SetUpTestSuite() {
+ if (!std::getenv("OSS_ROLE_ARN") || !std::getenv("OSS_EXTERNAL_ID") ||
+ !std::getenv("OSS_ENDPOINT") || !std::getenv("OSS_REGION") ||
+ !std::getenv("OSS_BUCKET") || !std::getenv("OSS_PREFIX")) {
+ return;
+ }
+ role_arn = std::getenv("OSS_ROLE_ARN");
+ external_id = std::getenv("OSS_EXTERNAL_ID");
+ endpoint = std::getenv("OSS_ENDPOINT");
+ region = std::getenv("OSS_REGION");
+ bucket = std::getenv("OSS_BUCKET");
+ prefix = std::getenv("OSS_PREFIX");
+ }
+
+ void SetUp() override {
+ if (role_arn.empty() || external_id.empty() || endpoint.empty() || region.empty() ||
+ bucket.empty() || prefix.empty()) {
+ GTEST_SKIP() << "Skipping OSS AssumeRole test, OSS environment variables not set";
+ }
+ }
+
+public:
+ static std::string endpoint;
+ static std::string region;
+ static std::string bucket;
+ static std::string prefix;
+ static std::string role_arn;
+ static std::string external_id;
+};
+
+std::string OSSAccessorRoleTest::endpoint;
+std::string OSSAccessorRoleTest::region;
+std::string OSSAccessorRoleTest::bucket;
+std::string OSSAccessorRoleTest::prefix;
+std::string OSSAccessorRoleTest::role_arn;
+std::string OSSAccessorRoleTest::external_id;
+
+TEST_F(OSSAccessorRoleTest, oss_assume_role) {
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(
+ OSSConf {
+ .endpoint = endpoint,
+ .bucket = bucket,
+ .prefix = prefix + "/OSSAccessorRoleTest/" + butil::GenerateGUID(),
+ .region = region,
+ .role_arn = role_arn,
+ .external_id = external_id,
+ .provider_type = OSSCredProviderType::INSTANCE_PROFILE,
+ },
+ &accessor);
+ ASSERT_EQ(ret, 0);
+
+ auto* sp = SyncPoint::get_instance();
+ std::vector<SyncPoint::CallbackGuard> guards;
+ sp->set_call_back(
+ "OSSListIterator::max_keys",
+ [](auto&& args) {
+ auto* max_keys = try_any_cast<int*>(args[0]);
+ *max_keys = 7;
+ },
+ &guards.emplace_back());
+ sp->set_call_back(
+ "OSSAccessor::delete_objects_batch_size",
+ [](auto&& args) {
+ auto* batch_size = try_any_cast<size_t*>(args[0]);
+ *batch_size = 7;
+ },
+ &guards.emplace_back());
+
+ test_oss_accessor(*accessor);
+}
+
+// AssumeRole without external_id (single-account scenario)
+TEST_F(OSSAccessorRoleTest, oss_assume_role_no_external_id) {
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(
+ OSSConf {
+ .endpoint = endpoint,
+ .bucket = bucket,
+ .prefix = prefix + "/OSSAccessorRoleTestNoExtId/" + butil::GenerateGUID(),
+ .region = region,
+ .role_arn = role_arn,
+ .external_id = "", // intentionally empty
+ .provider_type = OSSCredProviderType::INSTANCE_PROFILE,
+ },
+ &accessor);
+ ASSERT_EQ(ret, 0);
+
+ // Smoke: put → exists → delete
+ const std::string test_file = "smoke/no_ext_id.dat";
+ ret = accessor->put_file(test_file, "");
+ ASSERT_EQ(ret, 0);
+ ret = accessor->exists(test_file);
+ ASSERT_EQ(ret, 0);
+ ret = accessor->delete_file(test_file);
+ ASSERT_EQ(ret, 0);
+ ret = accessor->delete_all();
+ ASSERT_EQ(ret, 0);
+}
+
+// ---------------------------------------------------------------------------
+// OSSAccessorInstanceProfileTest — ECS instance profile (no AK/SK, no role)
+// Environment variables: OSS_ENDPOINT, OSS_REGION, OSS_BUCKET, OSS_PREFIX
+// ---------------------------------------------------------------------------
+class OSSAccessorInstanceProfileTest : public testing::Test {
+ static void SetUpTestSuite() {
+ if (!std::getenv("OSS_ENDPOINT") || !std::getenv("OSS_REGION") ||
+ !std::getenv("OSS_BUCKET") || !std::getenv("OSS_PREFIX")) {
+ return;
+ }
+ endpoint = std::getenv("OSS_ENDPOINT");
+ region = std::getenv("OSS_REGION");
+ bucket = std::getenv("OSS_BUCKET");
+ prefix = std::getenv("OSS_PREFIX");
+ }
+
+ void SetUp() override {
+ if (endpoint.empty() || region.empty() || bucket.empty() || prefix.empty()) {
+ GTEST_SKIP() << "Skipping OSS instance profile test, OSS environment variables not set";
+ }
+ }
+
+public:
+ static std::string endpoint;
+ static std::string region;
+ static std::string bucket;
+ static std::string prefix;
+};
+
+std::string OSSAccessorInstanceProfileTest::endpoint;
+std::string OSSAccessorInstanceProfileTest::region;
+std::string OSSAccessorInstanceProfileTest::bucket;
+std::string OSSAccessorInstanceProfileTest::prefix;
+
+TEST_F(OSSAccessorInstanceProfileTest, oss_instance_profile) {
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(
+ OSSConf {
+ .endpoint = endpoint,
+ .bucket = bucket,
+ .prefix = prefix + "/OSSAccessorIPTest/" + butil::GenerateGUID(),
+ .region = region,
+ .provider_type = OSSCredProviderType::INSTANCE_PROFILE,
+ },
+ &accessor);
+ ASSERT_EQ(ret, 0);
+
+ auto* sp = SyncPoint::get_instance();
+ std::vector<SyncPoint::CallbackGuard> guards;
+ sp->set_call_back(
+ "OSSListIterator::max_keys",
+ [](auto&& args) {
+ auto* max_keys = try_any_cast<int*>(args[0]);
+ *max_keys = 7;
+ },
+ &guards.emplace_back());
+ sp->set_call_back(
+ "OSSAccessor::delete_objects_batch_size",
+ [](auto&& args) {
+ auto* batch_size = try_any_cast<size_t*>(args[0]);
+ *batch_size = 7;
+ },
+ &guards.emplace_back());
+
+ test_oss_accessor(*accessor);
+}
+
+// ---------------------------------------------------------------------------
+// OSSAccessorDeletePrefixWithExpirationTest
+// Verifies that delete_prefix with expiration_time only removes old objects.
+// ---------------------------------------------------------------------------
+class OSSAccessorDeletePrefixExpirationTest : public testing::Test {
+ void SetUp() override {
+ if (cloud::config::test_oss_ak.empty()) {
+ GTEST_SKIP() << "empty test_oss_ak, skip OSSAccessorDeletePrefixExpirationTest";
+ }
+ }
+};
+
+TEST_F(OSSAccessorDeletePrefixExpirationTest, delete_prefix_with_expiration) {
+ std::shared_ptr<OSSAccessor> accessor;
+ int ret = OSSAccessor::create(
+ OSSConf {
+ .endpoint = config::test_oss_endpoint,
+ .bucket = config::test_oss_bucket,
+ .prefix = config::test_oss_prefix + "/OSSDeletePrefixExpTest/" +
+ butil::GenerateGUID(),
+ .region = config::test_oss_region,
+ .access_key_id = config::test_oss_ak,
+ .access_key_secret = config::test_oss_sk,
+ .provider_type = OSSCredProviderType::SIMPLE,
+ },
+ &accessor);
+ ASSERT_EQ(ret, 0);
+
+ // Put two files under the same prefix
+ ret = accessor->put_file("expire/old.dat", "old_content");
+ ASSERT_EQ(ret, 0);
+ ret = accessor->put_file("expire/new.dat", "new_content");
+ ASSERT_EQ(ret, 0);
+
+ // Use a far-future expiration time (year 2099) — nothing should be deleted
+ int64_t far_future = std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::time_point::max().time_since_epoch())
+ .count() /
+ 2; // safely in the future
+ ret = accessor->delete_prefix("expire/", far_future);
+ ASSERT_EQ(ret, 0);
+
+ // Both files must still exist
+ ret = accessor->exists("expire/old.dat");
+ EXPECT_EQ(ret, 0) << "old.dat should still exist (expiration time in future)";
+ ret = accessor->exists("expire/new.dat");
+ EXPECT_EQ(ret, 0) << "new.dat should still exist (expiration time in future)";
+
+ // Use epoch=0 (past) — all files under the prefix should be deleted
+ ret = accessor->delete_prefix("expire/", 1 /*epoch second 1, far in past*/);
+ ASSERT_EQ(ret, 0);
+
+ ret = accessor->exists("expire/old.dat");
+ EXPECT_EQ(ret, 1) << "old.dat should be deleted (expired)";
+ ret = accessor->exists("expire/new.dat");
+ EXPECT_EQ(ret, 1) << "new.dat should be deleted (expired)";
+
+ ret = accessor->delete_all();
+ ASSERT_EQ(ret, 0);
+}
+
+} // namespace doris::cloud
diff --git a/common/cpp/CMakeLists.txt b/common/cpp/CMakeLists.txt
index 81a600e57bf..cfdda6c78e4 100644
--- a/common/cpp/CMakeLists.txt
+++ b/common/cpp/CMakeLists.txt
@@ -19,4 +19,10 @@
set(LIBRARY_OUTPUT_PATH "${BUILD_DIR}/src/common_cpp")
file(GLOB_RECURSE SRC_FILES CONFIGURE_DEPENDS *.cpp)
+
+# Conditionally exclude OSS credential provider if OSS is disabled
+if(BUILD_OSS STREQUAL "OFF")
+ list(REMOVE_ITEM SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/oss_credential_provider.cpp")
+endif()
+
add_library(CommonCPP STATIC ${SRC_FILES})
diff --git a/common/cpp/oss_common.h b/common/cpp/oss_common.h
new file mode 100644
index 00000000000..9253f126406
--- /dev/null
+++ b/common/cpp/oss_common.h
@@ -0,0 +1,47 @@
+// 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.
+
+#pragma once
+
+#include <string>
+
+namespace doris {
+
+// Alibaba Cloud OSS Credentials Provider Type
+enum class OSSCredProviderType {
+ SIMPLE = 0, // Static AK/SK credentials
+ INSTANCE_PROFILE = 1, // ECS instance profile (metadata service)
+ DEFAULT = 2, // Default credential provider chain (matches S3)
+};
+
+// Normalize OSS endpoint by ensuring it has a scheme (http:// or https://)
+// Defaults to HTTPS if no scheme is specified for security and KMS bucket compatibility
+inline std::string normalize_oss_endpoint(const std::string& endpoint) {
+ if (endpoint.empty()) {
+ return endpoint;
+ }
+
+ // Already has scheme, return as-is
+ if (endpoint.starts_with("https://") || endpoint.starts_with("http://")) {
+ return endpoint;
+ }
+
+ // Default to HTTPS for security and KMS bucket compatibility
+ return "https://" + endpoint;
+}
+
+} // namespace doris
diff --git a/common/cpp/oss_credential_provider.cpp b/common/cpp/oss_credential_provider.cpp
new file mode 100644
index 00000000000..b49bbd8aafc
--- /dev/null
+++ b/common/cpp/oss_credential_provider.cpp
@@ -0,0 +1,489 @@
+// 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 "cpp/oss_credential_provider.h"
+
+#ifdef USE_OSS
+
+#include <alibabacloud/oss/auth/Credentials.h>
+#include <alibabacloud/oss/auth/CredentialsProvider.h>
+#include <curl/curl.h>
+#include <rapidjson/document.h>
+#include <ctime>
+#include <alibabacloud/Sts20150401.hpp>
+#include <alibabacloud/credentials/Client.hpp>
+#include <alibabacloud/utils/models/Config.hpp>
+#include <darabonba/Runtime.hpp>
+#include <iomanip>
+#include <sstream>
+#include <stdexcept>
+#include <unistd.h>
+
+#include "common/logging.h"
+
+namespace {
+std::string mask_credential(const std::string& cred) {
+ if (cred.empty()) return "";
+ size_t len = cred.length();
+ if (len <= 8) {
+ if (len <= 4) return std::string(len, '*');
+ return cred.substr(0, 2) + std::string(len - 4, '*') + cred.substr(len - 2);
+ }
+ return cred.substr(0, 4) + std::string(len - 8, '*') + cred.substr(len - 4);
+}
+} // namespace
+
+namespace doris {
+
+static size_t curl_write_callback(void* contents, size_t size, size_t nmemb, std::string* userp) {
+ size_t total_size = size * nmemb;
+ userp->append(static_cast<char*>(contents), total_size);
+ return total_size;
+}
+
+// ---- ECSMetadataCredentialsProvider ----
+
+ECSMetadataCredentialsProvider::ECSMetadataCredentialsProvider()
+ : _cached_credentials(nullptr), _expiration(std::chrono::system_clock::now()) {
+ LOG(INFO) << "ECSMetadataCredentialsProvider initialized";
+}
+
+bool ECSMetadataCredentialsProvider::_is_expired() const {
+ auto now = std::chrono::system_clock::now();
+ return std::chrono::duration_cast<std::chrono::seconds>(_expiration - now).count() <=
+ REFRESH_BEFORE_EXPIRY_SECONDS;
+}
+
+AlibabaCloud::OSS::Credentials ECSMetadataCredentialsProvider::getCredentials() {
+ {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials && !_is_expired()) {
+ VLOG(2) << "Returning cached ECS metadata credentials";
+ return *_cached_credentials;
+ }
+ if (_cached_credentials) {
+ auto t = std::chrono::system_clock::to_time_t(_expiration);
+ struct tm tm_buf;
+ LOG(INFO) << "ECS metadata credentials expiring ("
+ << std::put_time(localtime_r(&t, &tm_buf), "%Y-%m-%d %H:%M:%S")
+ << "), refreshing";
+ } else {
+ LOG(INFO) << "Fetching ECS metadata credentials (first time)";
+ }
+ }
+
+ std::unique_ptr<AlibabaCloud::OSS::Credentials> new_credentials;
+ std::chrono::system_clock::time_point new_expiration;
+
+ if (_fetch_credentials_outside_lock(new_credentials, new_expiration) != 0) {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials) {
+ LOG(WARNING) << "Using expired ECS metadata credentials as fallback";
+ return *_cached_credentials;
+ }
+ LOG(ERROR) << "Failed to fetch credentials from ECS metadata service and no cached "
+ "fallback available";
+ return AlibabaCloud::OSS::Credentials("", "", "");
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials && !_is_expired()) {
+ return *_cached_credentials;
+ }
+ _cached_credentials = std::move(new_credentials);
+ _expiration = new_expiration;
+ auto t = std::chrono::system_clock::to_time_t(_expiration);
+ struct tm tm_buf;
+ LOG(INFO) << "ECS metadata credentials refreshed, expiry: "
+ << std::put_time(localtime_r(&t, &tm_buf), "%Y-%m-%d %H:%M:%S");
+ return *_cached_credentials;
+ }
+}
+
+int ECSMetadataCredentialsProvider::_http_get(const std::string& url, std::string& response) {
+ CURL* curl = curl_easy_init();
+ if (!curl) {
+ LOG(ERROR) << "Failed to initialize CURL";
+ return -1;
+ }
+
+ response.clear();
+ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_callback);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
+ curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, METADATA_SERVICE_TIMEOUT_MS);
+ curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
+
+ CURLcode res = curl_easy_perform(curl);
+ if (res != CURLE_OK) {
+ LOG(ERROR) << "ECS metadata HTTP GET failed: " << curl_easy_strerror(res);
+ curl_easy_cleanup(curl);
+ return -1;
+ }
+
+ long http_code = 0;
+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
+ curl_easy_cleanup(curl);
+
+ if (http_code != 200) {
+ LOG(ERROR) << "ECS metadata service returned HTTP " << http_code;
+ return -1;
+ }
+ return 0;
+}
+
+int ECSMetadataCredentialsProvider::_get_role_name(std::string& role_name) {
+ std::string url = std::string("http://") + METADATA_SERVICE_HOST + METADATA_SERVICE_PATH;
+ std::string response;
+ if (_http_get(url, response) != 0) {
+ return -1;
+ }
+
+ role_name = response;
+ role_name.erase(role_name.begin(),
+ std::find_if(role_name.begin(), role_name.end(),
+ [](unsigned char ch) { return !std::isspace(ch); }));
+ role_name.erase(std::find_if(role_name.rbegin(), role_name.rend(),
+ [](unsigned char ch) { return !std::isspace(ch); })
+ .base(),
+ role_name.end());
+
+ if (role_name.empty()) {
+ LOG(ERROR) << "No RAM role attached to this ECS instance";
+ return -1;
+ }
+
+ size_t newline_pos = role_name.find('\n');
+ if (newline_pos != std::string::npos) {
+ std::string all_roles = role_name;
+ role_name = role_name.substr(0, newline_pos);
+ LOG(WARNING) << "Multiple RAM roles found on this ECS instance; using first: " << role_name
+ << ". All bound roles: " << all_roles
+ << ". Bind a single RAM role to this instance to avoid ambiguity.";
+ }
+
+ LOG(INFO) << "ECS RAM role: " << role_name;
+ return 0;
+}
+
+int ECSMetadataCredentialsProvider::_fetch_credentials_outside_lock(
+ std::unique_ptr<AlibabaCloud::OSS::Credentials>& out_credentials,
+ std::chrono::system_clock::time_point& out_expiration) {
+ std::string role_name;
+ if (_get_role_name(role_name) != 0) {
+ return -1;
+ }
+
+ std::string url =
+ std::string("http://") + METADATA_SERVICE_HOST + METADATA_SERVICE_PATH + role_name;
+ std::string response;
+ if (_http_get(url, response) != 0) {
+ return -1;
+ }
+
+ rapidjson::Document doc;
+ doc.Parse(response.c_str());
+
+ if (doc.HasParseError()) {
+ LOG(ERROR) << "Failed to parse ECS metadata JSON response";
+ return -1;
+ }
+ if (!doc.HasMember("Code") || std::string(doc["Code"].GetString()) != "Success") {
+ LOG(ERROR) << "ECS metadata error: "
+ << (doc.HasMember("Message") ? doc["Message"].GetString() : "unknown");
+ return -1;
+ }
+ if (!doc.HasMember("AccessKeyId") || !doc.HasMember("AccessKeySecret") ||
+ !doc.HasMember("SecurityToken") || !doc.HasMember("Expiration")) {
+ LOG(ERROR) << "ECS metadata response missing required fields";
+ return -1;
+ }
+
+ std::string ak = doc["AccessKeyId"].GetString();
+ std::string sk = doc["AccessKeySecret"].GetString();
+ std::string token = doc["SecurityToken"].GetString();
+ std::string expiry_str = doc["Expiration"].GetString();
+
+ if (ak.empty() || sk.empty() || token.empty()) {
+ LOG(ERROR) << "ECS metadata returned empty credentials";
+ return -1;
+ }
+
+ std::tm tm = {};
+ std::istringstream ss(expiry_str);
+ ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
+ if (ss.fail()) {
+ LOG(ERROR) << "Failed to parse expiration from ECS metadata: " << expiry_str;
+ return -1;
+ }
+
+ out_expiration = std::chrono::system_clock::from_time_t(timegm(&tm));
+ out_credentials = std::make_unique<AlibabaCloud::OSS::Credentials>(ak, sk, token);
+ VLOG(1) << "ECS metadata credentials: ak=" << mask_credential(ak) << ", expiry=" << expiry_str;
+ return 0;
+}
+
+// ---- OSSSTSCredentialProvider ----
+
+OSSSTSCredentialProvider::OSSSTSCredentialProvider(const std::string& role_arn,
+ const std::string& region,
+ const std::string& external_id,
+ const std::string& ca_cert_path,
+ const std::string& sts_endpoint)
+ : _cached_credentials(nullptr),
+ _expiration(std::chrono::system_clock::now()),
+ _role_arn(role_arn),
+ _region(region),
+ _external_id(external_id),
+ _ca_cert_path(ca_cert_path),
+ _sts_endpoint(sts_endpoint) {
+ if (_role_arn.empty()) {
+ throw std::invalid_argument("RAM role ARN cannot be empty for STS AssumeRole");
+ }
+ LOG(INFO) << "OSSSTSCredentialProvider: role_arn=" << _role_arn << ", region=" << _region
+ << ", external_id="
+ << (_external_id.empty() ? "(none)" : mask_credential(_external_id));
+}
+
+bool OSSSTSCredentialProvider::_is_expired() const {
+ auto now = std::chrono::system_clock::now();
+ return std::chrono::duration_cast<std::chrono::seconds>(_expiration - now).count() <=
+ REFRESH_BEFORE_EXPIRY_SECONDS;
+}
+
+AlibabaCloud::OSS::Credentials OSSSTSCredentialProvider::getCredentials() {
+ {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials && !_is_expired()) {
+ VLOG(2) << "Returning cached STS AssumeRole credentials";
+ return *_cached_credentials;
+ }
+ if (_cached_credentials) {
+ auto t = std::chrono::system_clock::to_time_t(_expiration);
+ struct tm tm_buf;
+ LOG(INFO) << "STS credentials expiring ("
+ << std::put_time(localtime_r(&t, &tm_buf), "%Y-%m-%d %H:%M:%S")
+ << "), refreshing";
+ } else {
+ LOG(INFO) << "Fetching STS AssumeRole credentials (first time)";
+ }
+ }
+
+ std::unique_ptr<AlibabaCloud::OSS::Credentials> new_credentials;
+ std::chrono::system_clock::time_point new_expiration;
+
+ if (_fetch_credentials_from_sts(new_credentials, new_expiration) != 0) {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials) {
+ LOG(WARNING) << "Using expired STS credentials as fallback";
+ return *_cached_credentials;
+ }
+ LOG(ERROR) << "Failed to fetch STS AssumeRole credentials and no cached fallback available";
+ return AlibabaCloud::OSS::Credentials("", "", "");
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials && !_is_expired()) {
+ return *_cached_credentials;
+ }
+ _cached_credentials = std::move(new_credentials);
+ _expiration = new_expiration;
+ auto t = std::chrono::system_clock::to_time_t(_expiration);
+ struct tm tm_buf;
+ LOG(INFO) << "STS AssumeRole credentials refreshed, expiry: "
+ << std::put_time(localtime_r(&t, &tm_buf), "%Y-%m-%d %H:%M:%S");
+ return *_cached_credentials;
+ }
+}
+
+int OSSSTSCredentialProvider::_fetch_credentials_from_sts(
+ std::unique_ptr<AlibabaCloud::OSS::Credentials>& out_credentials,
+ std::chrono::system_clock::time_point& out_expiration) {
+ try {
+ // TODO: support OIDC/RRSA as base credentials for AssumeRole (requires new
+ // CredProviderTypePB enum value and proto change); currently only INSTANCE_PROFILE
+ // (ECS RAM role) is supported as base, which is enforced by OSSProperties and
+ // convert_properties_to_oss_conf when role_arn is set.
+ AlibabaCloud::Credentials::Models::Config cred_config;
+ cred_config.setType("ecs_ram_role");
+ AlibabaCloud::Credentials::Client cred_client(cred_config);
+ AlibabaCloud::Credentials::Models::CredentialModel base_cred = cred_client.getCredential();
+ LOG(INFO) << "STS AssumeRole base credentials from provider: "
+ << base_cred.getProviderName();
+
+ AlibabaCloud::OpenApi::Utils::Models::Config config;
+ config.setAccessKeyId(base_cred.getAccessKeyId());
+ config.setAccessKeySecret(base_cred.getAccessKeySecret());
+ if (!base_cred.getSecurityToken().empty()) {
+ config.setSecurityToken(base_cred.getSecurityToken());
+ }
+ config.setRegionId(_region);
+ // Use override endpoint for non-standard regions; default: "sts.<region>.aliyuncs.com".
+ config.setEndpoint(_sts_endpoint.empty() ? "sts." + _region + ".aliyuncs.com"
+ : _sts_endpoint);
+
+ AlibabaCloud::Sts20150401::Client client(config);
+
+ AlibabaCloud::Sts20150401::Models::AssumeRoleRequest request;
+ request.setRoleArn(_role_arn);
+ // Include hostname in session name for ActionTrail audit traceability.
+ // STS session names allow [a-zA-Z0-9._-], max 32 chars.
+ char hostname_buf[64] = {};
+ if (gethostname(hostname_buf, sizeof(hostname_buf) - 1) != 0) {
+ strncpy(hostname_buf, "unknown", 7);
+ }
+ std::string session_name = "doris-";
+ for (int i = 0; hostname_buf[i] != '\0' && session_name.size() < 32; ++i) {
+ char c = hostname_buf[i];
+ if (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_' || c == '.') {
+ session_name += c;
+ }
+ }
+ if (session_name.size() < 2) {
+ session_name = "doris-oss-session";
+ }
+ request.setRoleSessionName(session_name);
+ request.setDurationSeconds(SESSION_DURATION_SECONDS);
+ if (!_external_id.empty()) {
+ request.setExternalId(_external_id);
+ }
+
+ Darabonba::RuntimeOptions runtime;
+ if (!_ca_cert_path.empty()) {
+ runtime.setCa(_ca_cert_path);
+ } else {
+ LOG(WARNING) << "OSSSTSCredentialProvider: no CA cert path, skipping SSL verification. "
+ "Set ca_cert_file_paths in be.conf.";
+ runtime.setIgnoreSSL(true);
+ }
+
+ AlibabaCloud::Sts20150401::Models::AssumeRoleResponse response =
+ client.assumeRoleWithOptions(request, runtime);
+
+ auto body = response.getBody();
+ auto creds = body.getCredentials();
+
+ std::string ak = creds.getAccessKeyId();
+ std::string sk = creds.getAccessKeySecret();
+ std::string token = creds.getSecurityToken();
+ std::string expiry_str = creds.getExpiration();
+
+ if (ak.empty() || sk.empty() || token.empty()) {
+ LOG(ERROR) << "STS AssumeRole returned empty credentials";
+ return -1;
+ }
+
+ std::tm tm = {};
+ std::istringstream ss(expiry_str);
+ ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
+ if (ss.fail()) {
+ LOG(ERROR) << "Failed to parse STS expiration: " << expiry_str;
+ return -1;
+ }
+
+ out_expiration = std::chrono::system_clock::from_time_t(timegm(&tm));
+ out_credentials = std::make_unique<AlibabaCloud::OSS::Credentials>(ak, sk, token);
+ VLOG(1) << "STS credentials: ak=" << mask_credential(ak) << ", expiry=" << expiry_str;
+ return 0;
+
+ } catch (const std::exception& e) {
+ LOG(ERROR) << "STS AssumeRole failed: " << e.what();
+ return -1;
+ }
+}
+
+// ---- OSSDefaultCredentialsProvider ----
+
+OSSDefaultCredentialsProvider::OSSDefaultCredentialsProvider()
+ : _cached_credentials(nullptr), _expiration(std::chrono::system_clock::now()) {
+ LOG(INFO) << "OSSDefaultCredentialsProvider initialized";
+}
+
+bool OSSDefaultCredentialsProvider::_is_expired() const {
+ auto now = std::chrono::system_clock::now();
+ return std::chrono::duration_cast<std::chrono::seconds>(_expiration - now).count() <=
+ REFRESH_BEFORE_EXPIRY_SECONDS;
+}
+
+AlibabaCloud::OSS::Credentials OSSDefaultCredentialsProvider::getCredentials() {
+ {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials && !_is_expired()) {
+ VLOG(2) << "Returning cached default provider credentials";
+ return *_cached_credentials;
+ }
+ if (_cached_credentials) {
+ LOG(INFO) << "Default provider credentials expiring, refreshing";
+ } else {
+ LOG(INFO) << "Fetching OSS credentials via default provider chain";
+ }
+ }
+
+ try {
+ AlibabaCloud::Credentials::Client cred_client;
+ AlibabaCloud::Credentials::Models::CredentialModel cred_model = cred_client.getCredential();
+
+ std::string ak = cred_model.getAccessKeyId();
+ std::string sk = cred_model.getAccessKeySecret();
+ std::string token = cred_model.getSecurityToken();
+
+ if (ak.empty() || sk.empty()) {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials) {
+ LOG(WARNING) << "Default provider returned empty credentials, using fallback";
+ return *_cached_credentials;
+ }
+ LOG(ERROR) << "Default provider chain returned empty credentials and no cached "
+ "fallback available";
+ return AlibabaCloud::OSS::Credentials("", "", "");
+ }
+
+ auto new_credentials =
+ token.empty() ? std::make_unique<AlibabaCloud::OSS::Credentials>(ak, sk)
+ : std::make_unique<AlibabaCloud::OSS::Credentials>(ak, sk, token);
+
+ auto new_expiration = std::chrono::system_clock::now() + std::chrono::hours(1);
+
+ {
+ std::lock_guard<std::mutex> lock(_mtx);
+ _cached_credentials = std::move(new_credentials);
+ _expiration = new_expiration;
+ auto t = std::chrono::system_clock::to_time_t(_expiration);
+ struct tm tm_buf;
+ LOG(INFO) << "Default provider credentials fetched, provider: "
+ << cred_model.getProviderName() << ", expiry: "
+ << std::put_time(localtime_r(&t, &tm_buf), "%Y-%m-%d %H:%M:%S");
+ return *_cached_credentials;
+ }
+ } catch (const std::exception& e) {
+ std::lock_guard<std::mutex> lock(_mtx);
+ if (_cached_credentials) {
+ LOG(WARNING) << "Default provider failed, using expired credentials as fallback: "
+ << e.what();
+ return *_cached_credentials;
+ }
+ LOG(ERROR) << "Failed to get OSS credentials and no cached fallback available: "
+ << e.what();
+ return AlibabaCloud::OSS::Credentials("", "", "");
+ }
+}
+
+} // namespace doris
+
+#endif // USE_OSS
diff --git a/common/cpp/oss_credential_provider.h b/common/cpp/oss_credential_provider.h
new file mode 100644
index 00000000000..ca2af8f1afb
--- /dev/null
+++ b/common/cpp/oss_credential_provider.h
@@ -0,0 +1,109 @@
+// 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.
+
+#pragma once
+
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <string>
+
+#ifdef USE_OSS
+
+#include <alibabacloud/oss/auth/Credentials.h>
+#include <alibabacloud/oss/auth/CredentialsProvider.h>
+
+namespace doris {
+
+using OSSCredentials = AlibabaCloud::OSS::Credentials;
+
+class ECSMetadataCredentialsProvider : public AlibabaCloud::OSS::CredentialsProvider {
+public:
+ ECSMetadataCredentialsProvider();
+ ~ECSMetadataCredentialsProvider() override = default;
+
+ AlibabaCloud::OSS::Credentials getCredentials() override;
+
+private:
+ int _fetch_credentials_outside_lock(
+ std::unique_ptr<AlibabaCloud::OSS::Credentials>& out_credentials,
+ std::chrono::system_clock::time_point& out_expiration);
+ int _get_role_name(std::string& role_name);
+ bool _is_expired() const;
+ int _http_get(const std::string& url, std::string& response);
+
+ mutable std::mutex _mtx;
+ std::unique_ptr<OSSCredentials> _cached_credentials;
+ std::chrono::system_clock::time_point _expiration;
+
+ static constexpr const char* METADATA_SERVICE_HOST = "100.100.100.200";
+ static constexpr const char* METADATA_SERVICE_PATH =
+ "/latest/meta-data/ram/security-credentials/";
+ static constexpr int METADATA_SERVICE_TIMEOUT_MS = 5000;
+ static constexpr int REFRESH_BEFORE_EXPIRY_SECONDS = 300;
+};
+
+class OSSSTSCredentialProvider : public AlibabaCloud::OSS::CredentialsProvider {
+public:
+ explicit OSSSTSCredentialProvider(const std::string& role_arn, const std::string& region,
+ const std::string& external_id = "",
+ const std::string& ca_cert_path = "",
+ const std::string& sts_endpoint = "");
+ ~OSSSTSCredentialProvider() override = default;
+
+ AlibabaCloud::OSS::Credentials getCredentials() override;
+
+private:
+ int _fetch_credentials_from_sts(
+ std::unique_ptr<AlibabaCloud::OSS::Credentials>& out_credentials,
+ std::chrono::system_clock::time_point& out_expiration);
+ bool _is_expired() const;
+
+ mutable std::mutex _mtx;
+ std::unique_ptr<OSSCredentials> _cached_credentials;
+ std::chrono::system_clock::time_point _expiration;
+ std::string _role_arn;
+ std::string _region;
+ std::string _external_id;
+ std::string _ca_cert_path;
+ // Non-empty overrides "sts.<region>.aliyuncs.com" (needed for finance/gov cloud regions).
+ std::string _sts_endpoint;
+
+ static constexpr int REFRESH_BEFORE_EXPIRY_SECONDS = 300;
+ static constexpr int SESSION_DURATION_SECONDS = 3600;
+};
+
+class OSSDefaultCredentialsProvider : public AlibabaCloud::OSS::CredentialsProvider {
+public:
+ OSSDefaultCredentialsProvider();
+ ~OSSDefaultCredentialsProvider() override = default;
+
+ AlibabaCloud::OSS::Credentials getCredentials() override;
+
+private:
+ bool _is_expired() const;
+
+ mutable std::mutex _mtx;
+ std::unique_ptr<OSSCredentials> _cached_credentials;
+ std::chrono::system_clock::time_point _expiration;
+
+ static constexpr int REFRESH_BEFORE_EXPIRY_SECONDS = 300;
+};
+
+} // namespace doris
+
+#endif // USE_OSS
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/OSSResource.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/OSSResource.java
new file mode 100644
index 00000000000..87d999e4abf
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/OSSResource.java
@@ -0,0 +1,238 @@
+// 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.catalog;
+
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.proc.BaseProcResult;
+import org.apache.doris.common.util.PrintableMap;
+import org.apache.doris.datasource.property.storage.OSSProperties;
+import org.apache.doris.datasource.property.storage.S3Properties;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Alibaba Cloud OSS resource. Accepts both {@code oss.*} and {@code s3.*} property prefixes;
+ * oss.* keys are normalised to s3.* equivalents so downstream logic uses a single key space.
+ * When role_arn is set without AK/SK the connectivity check is skipped -- the BE resolves
+ * credentials at query time.
+ * <pre>
+ * CREATE RESOURCE "remote_oss"
+ * PROPERTIES
+ * (
+ * "type" = "s3",
+ * "s3.endpoint" = "oss-cn-beijing.aliyuncs.com",
+ * "s3.region" = "cn-beijing",
+ * "s3.bucket" = "my-bucket",
+ * "s3.root.path" = "/path/to/root",
+ * "s3.access_key" = "ak",
+ * "s3.secret_key" = "sk"
+ * );
+ * </pre>
+ */
+public class OSSResource extends Resource {
+ private static final Logger LOG = LogManager.getLogger(OSSResource.class);
+ private Map<String, String> properties = Maps.newHashMap();
+
+ public OSSResource() {
+ super();
+ }
+
+ public OSSResource(String name) {
+ super(name, ResourceType.OSS);
+ }
+
+ @Override
+ protected void setProperties(ImmutableMap<String, String> newProperties) throws DdlException {
+ Preconditions.checkState(newProperties != null);
+ this.properties = Maps.newHashMap(newProperties);
+ normalizeOssToS3Keys(this.properties);
+ S3Properties.requiredS3PingProperties(this.properties);
+ boolean needCheck = isNeedCheck(this.properties);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("oss info need check validity : {}", needCheck);
+ }
+ String pingEndpoint = this.properties.get(S3Properties.ENDPOINT);
+ if (!pingEndpoint.startsWith("http://") && !pingEndpoint.startsWith("https://")) {
+ pingEndpoint = "https://" + pingEndpoint;
+ this.properties.put(S3Properties.ENDPOINT, pingEndpoint);
+ this.properties.put(S3Properties.Env.ENDPOINT, pingEndpoint);
+ }
+ if (needCheck) {
+ pingOSS(this.properties.get(S3Properties.BUCKET),
+ this.properties.get(S3Properties.ROOT_PATH), this.properties);
+ }
+ S3Properties.optionalS3Property(this.properties);
+ }
+
+ protected static void pingOSS(String bucketName, String rootPath,
+ Map<String, String> props) throws DdlException {
+ S3Resource.pingS3(bucketName, rootPath, props);
+ }
+
+ @Override
+ public void modifyProperties(Map<String, String> newProperties) throws DdlException {
+ if (references.containsValue(ReferenceType.POLICY)) {
+ List<String> cantChangeProperties = Arrays.asList(
+ OSSProperties.ENDPOINT_KEY, OSSProperties.REGION_KEY,
+ OSSProperties.ROOT_PATH_KEY, OSSProperties.BUCKET_KEY,
+ S3Properties.ENDPOINT, S3Properties.REGION,
+ S3Properties.ROOT_PATH, S3Properties.BUCKET,
+ S3Properties.Env.ENDPOINT, S3Properties.Env.REGION,
+ S3Properties.Env.ROOT_PATH, S3Properties.Env.BUCKET);
+ Optional<String> any = cantChangeProperties.stream()
+ .filter(newProperties::containsKey).findAny();
+ if (any.isPresent()) {
+ throw new DdlException("current not support modify property : " + any.get());
+ }
+ }
+ normalizeOssToS3Keys(newProperties);
+ boolean needCheck = isNeedCheck(newProperties);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("oss info need check validity : {}", needCheck);
+ }
+ if (needCheck) {
+ S3Properties.requiredS3PingProperties(this.properties);
+ Map<String, String> changedProperties = new HashMap<>(this.properties);
+ changedProperties.putAll(newProperties);
+ String bucket = newProperties.containsKey(S3Properties.BUCKET)
+ ? newProperties.get(S3Properties.BUCKET)
+ : this.properties.get(S3Properties.BUCKET);
+ if (bucket == null) {
+ throw new DdlException("Missing required property: " + S3Properties.BUCKET);
+ }
+ pingOSS(bucket,
+ newProperties.getOrDefault(S3Properties.ROOT_PATH,
+ this.properties.get(S3Properties.ROOT_PATH)),
+ changedProperties);
+ }
+ writeLock();
+ for (Map.Entry<String, String> kv : newProperties.entrySet()) {
+ replaceIfEffectiveValue(this.properties, kv.getKey(), kv.getValue());
+ if (kv.getKey().equals(S3Properties.SESSION_TOKEN)
+ || kv.getKey().equals(OSSProperties.SESSION_TOKEN_KEY)) {
+ // replaceIfEffectiveValue skips empty strings; force-put here so that setting
+ // session_token="" explicitly clears a previously stored temporary token.
+ this.properties.put(kv.getKey(), kv.getValue());
+ }
+ if ((kv.getKey().equalsIgnoreCase(OSSProperties.ROLE_ARN_KEY)
+ || kv.getKey().equalsIgnoreCase(S3Properties.ROLE_ARN))
+ && !Strings.isNullOrEmpty(kv.getValue())) {
+ this.properties.remove(OSSProperties.ACCESS_KEY_KEY);
+ this.properties.remove(OSSProperties.SECRET_KEY_KEY);
+ this.properties.remove(S3Properties.ACCESS_KEY);
+ this.properties.remove(S3Properties.Env.ACCESS_KEY);
+ this.properties.remove(S3Properties.SECRET_KEY);
+ this.properties.remove(S3Properties.Env.SECRET_KEY);
+ }
+ if ((kv.getKey().equalsIgnoreCase(OSSProperties.ACCESS_KEY_KEY)
+ || kv.getKey().equalsIgnoreCase(S3Properties.ACCESS_KEY))
+ && !Strings.isNullOrEmpty(kv.getValue())) {
+ this.properties.remove(OSSProperties.ROLE_ARN_KEY);
+ this.properties.remove(OSSProperties.EXTERNAL_ID_KEY);
+ this.properties.remove(S3Properties.ROLE_ARN);
+ this.properties.remove(S3Properties.Env.ROLE_ARN);
+ this.properties.remove(S3Properties.EXTERNAL_ID);
+ this.properties.remove(S3Properties.Env.EXTERNAL_ID);
+ }
+ }
+ ++version;
+ writeUnlock();
+ super.modifyProperties(newProperties);
+ }
+
+ // Skip check when role_arn is set without AK/SK (FE cannot call Alibaba Cloud STS).
+ // When both role_arn and AK/SK are set, ping uses AK/SK; STS is resolved by BE at query time.
+ private boolean isNeedCheck(Map<String, String> newProperties) {
+ String roleArn = newProperties.getOrDefault(S3Properties.ROLE_ARN,
+ newProperties.getOrDefault(OSSProperties.ROLE_ARN_KEY,
+ this.properties.getOrDefault(S3Properties.ROLE_ARN,
+ this.properties.getOrDefault(OSSProperties.ROLE_ARN_KEY, ""))));
+ String accessKey = newProperties.getOrDefault(S3Properties.ACCESS_KEY,
+ newProperties.getOrDefault(OSSProperties.ACCESS_KEY_KEY,
+ this.properties.getOrDefault(S3Properties.ACCESS_KEY,
+ this.properties.getOrDefault(OSSProperties.ACCESS_KEY_KEY, ""))));
+ if (!roleArn.isEmpty() && accessKey.isEmpty()) {
+ return false;
+ }
+ boolean needCheck = !this.properties.containsKey(S3Properties.VALIDITY_CHECK)
+ || Boolean.parseBoolean(this.properties.get(S3Properties.VALIDITY_CHECK));
+ if (newProperties != null && newProperties.containsKey(S3Properties.VALIDITY_CHECK)) {
+ needCheck = Boolean.parseBoolean(newProperties.get(S3Properties.VALIDITY_CHECK));
+ }
+ return needCheck;
+ }
+
+ private static void normalizeOssToS3Keys(Map<String, String> props) {
+ copyIfAbsent(props, OSSProperties.ENDPOINT_KEY, S3Properties.ENDPOINT);
+ copyIfAbsent(props, OSSProperties.REGION_KEY, S3Properties.REGION);
+ copyIfAbsent(props, OSSProperties.ACCESS_KEY_KEY, S3Properties.ACCESS_KEY);
+ copyIfAbsent(props, OSSProperties.SECRET_KEY_KEY, S3Properties.SECRET_KEY);
+ copyIfAbsent(props, OSSProperties.SESSION_TOKEN_KEY, S3Properties.SESSION_TOKEN);
+ copyIfAbsent(props, OSSProperties.BUCKET_KEY, S3Properties.BUCKET);
+ copyIfAbsent(props, OSSProperties.ROOT_PATH_KEY, S3Properties.ROOT_PATH);
+ copyIfAbsent(props, OSSProperties.ROLE_ARN_KEY, S3Properties.ROLE_ARN);
+ copyIfAbsent(props, OSSProperties.EXTERNAL_ID_KEY, S3Properties.EXTERNAL_ID);
+ }
+
+ private static void copyIfAbsent(Map<String, String> props, String srcKey, String dstKey) {
+ if (!props.containsKey(dstKey) && props.containsKey(srcKey)) {
+ props.put(dstKey, props.get(srcKey));
+ }
+ }
+
+ @Override
+ public Map<String, String> getCopiedProperties() {
+ return Maps.newHashMap(this.properties);
+ }
+
+ @Override
+ protected void getProcNodeData(BaseProcResult result) {
+ String lowerCaseType = type.name().toLowerCase();
+ result.addRow(Lists.newArrayList(name, lowerCaseType, "id", String.valueOf(id)));
+ readLock();
+ result.addRow(Lists.newArrayList(name, lowerCaseType, "version", String.valueOf(version)));
+ for (Map.Entry<String, String> entry : this.properties.entrySet()) {
+ if (PrintableMap.HIDDEN_KEY.contains(entry.getKey())) {
+ continue;
+ }
+ if (entry.getKey().equals(S3Properties.Env.SECRET_KEY)
+ || entry.getKey().equals(S3Properties.SECRET_KEY)
+ || entry.getKey().equals(OSSProperties.SECRET_KEY_KEY)
+ || entry.getKey().equals(S3Properties.Env.TOKEN)
+ || entry.getKey().equals(S3Properties.SESSION_TOKEN)
+ || entry.getKey().equals(OSSProperties.SESSION_TOKEN_KEY)) {
+ result.addRow(Lists.newArrayList(name, lowerCaseType, entry.getKey(), "******"));
+ } else {
+ result.addRow(Lists.newArrayList(name, lowerCaseType, entry.getKey(), entry.getValue()));
+ }
+ }
+ readUnlock();
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/Resource.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/Resource.java
index db0659c4b08..9a9af387310 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/Resource.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/Resource.java
@@ -58,7 +58,8 @@ public abstract class Resource implements Writable, GsonPostProcessable {
HMS,
ES,
AZURE,
- AI;
+ AI,
+ OSS;
public static ResourceType fromString(String resourceType) {
if ("jfs".equalsIgnoreCase(resourceType) || "juicefs".equalsIgnoreCase(resourceType)) {
@@ -180,6 +181,9 @@ public abstract class Resource implements Writable, GsonPostProcessable {
case AZURE:
resource = new AzureResource(name);
break;
+ case OSS:
+ resource = new OSSResource(name);
+ break;
case JDBC:
resource = new JdbcResource(name);
break;
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/S3StorageVault.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/S3StorageVault.java
index b2a8b61fff1..0e28e483b53 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/S3StorageVault.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/S3StorageVault.java
@@ -111,7 +111,6 @@ public class S3StorageVault extends StorageVault {
Preconditions.checkArgument(
!properties.get(PropertyKey.ROOT_PATH).isEmpty(),
"Property " + PropertyKey.ROOT_PATH + " cannot be empty");
-
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVault.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVault.java
index 67ccf49eef4..3200f544959 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVault.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVault.java
@@ -156,7 +156,7 @@ public abstract class StorageVault {
default:
throw new DdlException("Unknown StorageVault type: " + type);
}
- vault.checkCreationProperties(command.getProperties());
+ vault.checkCreationProperties(vault.getCopiedProperties());
vault.pathVersion = command.getPathVersion();
vault.numShard = command.getNumShard();
return vault;
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVaultMgr.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVaultMgr.java
index 1b3158b561a..ae9c691a004 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVaultMgr.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/StorageVaultMgr.java
@@ -25,6 +25,7 @@ import org.apache.doris.common.DdlException;
import org.apache.doris.common.Pair;
import org.apache.doris.common.UserException;
import org.apache.doris.common.lock.MonitoredReentrantReadWriteLock;
+import org.apache.doris.datasource.property.storage.OSSProperties;
import org.apache.doris.datasource.property.storage.S3Properties;
import org.apache.doris.datasource.property.storage.StorageProperties;
import org.apache.doris.nereids.trees.plans.commands.CreateStorageVaultCommand;
@@ -71,7 +72,7 @@ public class StorageVaultMgr {
break;
case UNKNOWN:
default:
- throw new DdlException("Only support S3, HDFS storage vault.");
+ throw new DdlException("Only support S3 and HDFS storage vault.");
}
// Make BE eagerly fetch the storage vault info from Meta Service
ALTER_BE_SYNC_THREAD_POOL.execute(() -> alterSyncVaultTask());
@@ -146,9 +147,18 @@ public class StorageVaultMgr {
}
}
+ private static Cloud.ObjectStoreInfoPB.Builder buildObjStoreInfoPB(
+ Map<String, String> properties) {
+ // OSS vaults do not carry "provider=OSS" in their stored property map; detect by endpoint.
+ if (OSSProperties.guessIsMe(properties)) {
+ return OSSProperties.getObjStoreInfoPB(properties);
+ }
+ return S3Properties.getObjStoreInfoPB(properties);
+ }
+
private Cloud.StorageVaultPB.Builder buildAlterS3VaultRequest(Map<String, String> properties, String name)
throws Exception {
- Cloud.ObjectStoreInfoPB.Builder objBuilder = S3Properties.getObjStoreInfoPB(properties);
+ Cloud.ObjectStoreInfoPB.Builder objBuilder = buildObjStoreInfoPB(properties);
Cloud.StorageVaultPB.Builder alterObjVaultBuilder = Cloud.StorageVaultPB.newBuilder();
alterObjVaultBuilder.setName(name);
alterObjVaultBuilder.setObjInfo(objBuilder.build());
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/property/storage/OSSProperties.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/property/storage/OSSProperties.java
index b38bc639076..3bf28cba1e1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/property/storage/OSSProperties.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/property/storage/OSSProperties.java
@@ -17,16 +17,22 @@
package org.apache.doris.datasource.property.storage;
+import org.apache.doris.cloud.proto.Cloud;
import org.apache.doris.common.UserException;
import org.apache.doris.datasource.property.ConnectorPropertiesUtils;
import org.apache.doris.datasource.property.ConnectorProperty;
+import org.apache.doris.thrift.TObjStorageType;
+import org.apache.doris.thrift.TS3StorageParam;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
@@ -42,6 +48,7 @@ import java.util.regex.Pattern;
import java.util.stream.Stream;
public class OSSProperties extends AbstractS3CompatibleProperties {
+ private static final Logger LOG = LogManager.getLogger(OSSProperties.class);
@Setter
@Getter
@@ -90,37 +97,33 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
description = "The session token of OSS.")
protected String sessionToken = "";
- /**
- * The maximum number of concurrent connections that can be made to the object storage system.
- * This value is optional and can be configured by the user.
- */
+ @Getter
+ @ConnectorProperty(names = {"oss.role_arn", "s3.role_arn", "AWS_ROLE_ARN"},
+ required = false,
+ description = "Alibaba Cloud RAM role ARN for STS AssumeRole.")
+ protected String ossRoleArn = "";
+
+ @Getter
+ @ConnectorProperty(names = {"oss.external_id", "s3.external_id", "AWS_EXTERNAL_ID"},
+ required = false,
+ description = "External ID for cross-account STS AssumeRole.")
+ protected String ossExternalId = "";
+
@Getter
@ConnectorProperty(names = {"oss.connection.maximum", "s3.connection.maximum"}, required = false,
description = "Maximum number of connections.")
protected String maxConnections = "100";
- /**
- * The timeout (in milliseconds) for requests made to the object storage system.
- * This value is optional and can be configured by the user.
- */
@Getter
@ConnectorProperty(names = {"oss.connection.request.timeout", "s3.connection.request.timeout"}, required = false,
- description = "Request timeout in seconds.")
+ description = "Request timeout in milliseconds.")
protected String requestTimeoutS = "10000";
- /**
- * The timeout (in milliseconds) for establishing a connection to the object storage system.
- * This value is optional and can be configured by the user.
- */
@Getter
@ConnectorProperty(names = {"oss.connection.timeout", "s3.connection.timeout"}, required = false,
- description = "Connection timeout in seconds.")
+ description = "Connection timeout in milliseconds.")
protected String connectionTimeoutS = "10000";
- /**
- * Flag indicating whether to use path-style URLs for the object storage system.
- * This value is optional and can be configured by the user.
- */
@Setter
@Getter
@ConnectorProperty(names = {"oss.use_path_style", "use_path_style", "s3.path-style-access"}, required = false,
@@ -160,7 +163,7 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
private static final List<String> URI_KEYWORDS = Arrays.asList("uri", "warehouse");
- private static List<String> DLF_TYPE_KEYWORDS = Arrays.asList("hive.metastore.type",
+ private static final List<String> DLF_TYPE_KEYWORDS = Arrays.asList("hive.metastore.type",
"iceberg.catalog.type", "paimon.catalog.type");
static final String JINDO_OSS_FILE_SYSTEM_IMPL = "com.aliyun.jindodata.oss.JindoOssFileSystem";
@@ -168,6 +171,17 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
private static final String DLS_URI_KEYWORDS = "oss-dls.aliyuncs";
+ public static final String OSS_PREFIX = "oss.";
+ public static final String ENDPOINT_KEY = "oss.endpoint";
+ public static final String REGION_KEY = "oss.region";
+ public static final String ACCESS_KEY_KEY = "oss.access_key";
+ public static final String SECRET_KEY_KEY = "oss.secret_key";
+ public static final String SESSION_TOKEN_KEY = "oss.session_token";
+ public static final String ROOT_PATH_KEY = "oss.root.path";
+ public static final String BUCKET_KEY = "oss.bucket";
+ public static final String ROLE_ARN_KEY = "oss.role_arn";
+ public static final String EXTERNAL_ID_KEY = "oss.external_id";
+
protected OSSProperties(Map<String, String> origProps) {
super(Type.OSS, origProps);
}
@@ -180,7 +194,7 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
return propertiesObj;
}
- protected static boolean guessIsMe(Map<String, String> origProps) {
+ public static boolean guessIsMe(Map<String, String> origProps) {
String value = Stream.of("oss.endpoint", "s3.endpoint", "AWS_ENDPOINT", "endpoint", "ENDPOINT",
"dlf.endpoint", "dlf.catalog.endpoint", "fs.oss.endpoint", "fs.oss.accessKeyId")
.map(origProps::get)
@@ -212,7 +226,7 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
.filter(Objects::nonNull)
.filter(OSSProperties::isKnownObjectStorage)
.findFirst();
- return uriValue.filter(OSSProperties::isKnownObjectStorage).isPresent();
+ return uriValue.isPresent();
}
private static boolean isKnownObjectStorage(String value) {
@@ -255,8 +269,6 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
.findFirst();
if (uriValueOpt.isPresent()) {
String uri = uriValueOpt.get();
- // If the URI does not start with http(s), derive endpoint from region
- // (http(s) URIs are handled by separate logic elsewhere)
if (!uri.startsWith("http://") && !uri.startsWith("https://")) {
this.endpoint = getOssEndpoint(region, BooleanUtils.toBoolean(dlfAccessPublic));
}
@@ -274,7 +286,13 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
@Override
public void initNormalizeAndCheckProps() {
super.initNormalizeAndCheckProps();
+ if (StringUtils.isNotBlank(ossExternalId) && StringUtils.isBlank(ossRoleArn)) {
+ throw new IllegalArgumentException("oss.external_id must be used with oss.role_arn");
+ }
if (StringUtils.isBlank(endpoint) || !STANDARD_ENDPOINT_PATTERN.matcher(endpoint).matches()) {
+ Preconditions.checkArgument(StringUtils.isNotBlank(region),
+ "OSS region is not set. Either provide a standard endpoint "
+ + "(e.g. oss-cn-hangzhou.aliyuncs.com) or specify oss.region explicitly.");
this.endpoint = getOssEndpoint(region, BooleanUtils.toBoolean(dlfAccessPublic));
}
}
@@ -295,6 +313,14 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
@Override
public AwsCredentialsProvider getAwsCredentialsProvider() {
+ // When role_arn is set, the FE cannot assume an Alibaba Cloud RAM role via
+ // the AWS SDK (which calls AWS STS endpoints, not Alibaba STS). Credential
+ // resolution is delegated to the BE via OSSSTSCredentialProvider (Alibaba
+ // STS v2 SDK). Return null here; role_arn/external_id are forwarded to the
+ // BE through getBackendConfigProperties().
+ if (StringUtils.isNotBlank(ossRoleArn)) {
+ return null;
+ }
AwsCredentialsProvider credentialsProvider = super.getAwsCredentialsProvider();
if (credentialsProvider != null) {
return credentialsProvider;
@@ -306,6 +332,21 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
return null;
}
+ @Override
+ public Map<String, String> getBackendConfigProperties() {
+ Map<String, String> backendProperties = super.getBackendConfigProperties();
+ backendProperties.put("provider", "OSS");
+ if (StringUtils.isNotBlank(ossRoleArn)) {
+ backendProperties.put("AWS_ROLE_ARN", ossRoleArn);
+ // OSS native SDK requires INSTANCE_PROFILE to activate STS AssumeRole.
+ backendProperties.put("AWS_CREDENTIALS_PROVIDER_TYPE", "INSTANCE_PROFILE");
+ }
+ if (StringUtils.isNotBlank(ossExternalId)) {
+ backendProperties.put("AWS_EXTERNAL_ID", ossExternalId);
+ }
+ return backendProperties;
+ }
+
@Override
protected Set<String> schemas() {
return ImmutableSet.of("oss");
@@ -355,7 +396,6 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
try {
parsed = URI.create(uri);
} catch (IllegalArgumentException e) {
- // Invalid URI, do not rewrite
return uri;
}
@@ -370,7 +410,6 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
return uri;
}
- // Handle bucket.endpoint format
int dotIndex = authority.indexOf('.');
if (dotIndex <= 0) {
return uri;
@@ -388,8 +427,130 @@ public class OSSProperties extends AbstractS3CompatibleProperties {
);
return rewritten.toString();
} catch (URISyntaxException e) {
- // Be conservative: fallback to original URI
return uri;
}
}
+
+ /**
+ * Builds an {@link Cloud.ObjectStoreInfoPB} from the bound (normalized) field values of
+ * this instance. Unlike the static overload which re-reads {@code origProps}, this method
+ * uses the fields already resolved by {@link #initNormalizeAndCheckProps()} — notably
+ * the endpoint that may have been derived from the region when not explicitly provided.
+ */
+ public Cloud.ObjectStoreInfoPB.Builder getObjStoreInfoPB() {
+ Cloud.ObjectStoreInfoPB.Builder builder = Cloud.ObjectStoreInfoPB.newBuilder();
+ builder.setProvider(Cloud.ObjectStoreInfoPB.Provider.OSS);
+ if (StringUtils.isNotBlank(endpoint)) {
+ // Endpoint is forwarded without scheme; BE normalises it in OSSConf::get_oss_conf.
+ builder.setEndpoint(endpoint);
+ }
+ if (StringUtils.isNotBlank(region)) {
+ builder.setRegion(region);
+ }
+ if (StringUtils.isNotBlank(accessKey)) {
+ builder.setAk(accessKey);
+ }
+ if (StringUtils.isNotBlank(secretKey)) {
+ builder.setSk(secretKey);
+ }
+ // bucket and rootPath are not bound fields; re-read from origProps.
+ String rootPath = Stream.of(ROOT_PATH_KEY, "s3.root.path", "root.path")
+ .map(origProps::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (rootPath != null) {
+ builder.setPrefix(rootPath);
+ }
+ String bucket = Stream.of(BUCKET_KEY, "s3.bucket", "bucket")
+ .map(origProps::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (bucket != null) {
+ builder.setBucket(bucket);
+ }
+ if (StringUtils.isNotBlank(ossRoleArn)) {
+ builder.setRoleArn(ossRoleArn);
+ if (StringUtils.isNotBlank(ossExternalId)) {
+ builder.setExternalId(ossExternalId);
+ }
+ builder.setCredProviderType(Cloud.CredProviderTypePB.INSTANCE_PROFILE);
+ } else {
+ builder.setCredProviderType(
+ (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey))
+ ? Cloud.CredProviderTypePB.DEFAULT
+ : Cloud.CredProviderTypePB.SIMPLE);
+ }
+ return builder;
+ }
+
+ /**
+ * Builds an {@link Cloud.ObjectStoreInfoPB} builder from an OSS property map.
+ * Always sets {@code provider=OSS} and handles role_arn / external_id for AssumeRole.
+ */
+ public static Cloud.ObjectStoreInfoPB.Builder getObjStoreInfoPB(Map<String, String> properties) {
+ Cloud.ObjectStoreInfoPB.Builder builder = Cloud.ObjectStoreInfoPB.newBuilder();
+ builder.setProvider(Cloud.ObjectStoreInfoPB.Provider.OSS);
+
+ String endpoint = Stream.of(ENDPOINT_KEY, "s3.endpoint", "endpoint")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (endpoint != null) {
+ builder.setEndpoint(endpoint);
+ }
+
+ String region = Stream.of(REGION_KEY, "s3.region", "region")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (region != null) {
+ builder.setRegion(region);
+ }
+
+ String accessKey = Stream.of(ACCESS_KEY_KEY, "s3.access_key", "access_key")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (accessKey != null) {
+ builder.setAk(accessKey);
+ }
+
+ String secretKey = Stream.of(SECRET_KEY_KEY, "s3.secret_key", "secret_key")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (secretKey != null) {
+ builder.setSk(secretKey);
+ }
+
+ String rootPath = Stream.of(ROOT_PATH_KEY, "s3.root.path", "root.path")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (rootPath != null) {
+ builder.setPrefix(rootPath);
+ }
+
+ String bucket = Stream.of(BUCKET_KEY, "s3.bucket", "bucket")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (bucket != null) {
+ builder.setBucket(bucket);
+ }
+
+ String roleArn = Stream.of(ROLE_ARN_KEY, "s3.role_arn")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (roleArn != null) {
+ builder.setRoleArn(roleArn);
+ String externalId = Stream.of(EXTERNAL_ID_KEY, "s3.external_id")
+ .map(properties::get).filter(StringUtils::isNotBlank).findFirst().orElse(null);
+ if (externalId != null) {
+ builder.setExternalId(externalId);
+ }
+ builder.setCredProviderType(Cloud.CredProviderTypePB.INSTANCE_PROFILE);
+ } else {
+ builder.setCredProviderType(
+ (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey))
+ ? Cloud.CredProviderTypePB.DEFAULT
+ : Cloud.CredProviderTypePB.SIMPLE);
+ }
+
+ return builder;
+ }
+
+ /**
+ * Builds a {@link TS3StorageParam} from an OSS property map for the Thrift/storage-policy path.
+ * Always sets {@code provider=OSS} so the BE routes to the correct SDK.
+ * Properties must already be normalized to s3.* keys (e.g. via OSSResource.getCopiedProperties()).
+ */
+ public static TS3StorageParam getS3TStorageParam(Map<String, String> properties) {
+ TS3StorageParam param = S3Properties.getS3TStorageParam(properties);
+ param.setProvider(TObjStorageType.OSS);
+ return param;
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/fs/StorageTypeMapper.java b/fe/fe-core/src/main/java/org/apache/doris/fs/StorageTypeMapper.java
index aacb098102f..68ce3345fd1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/fs/StorageTypeMapper.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/fs/StorageTypeMapper.java
@@ -30,6 +30,7 @@ import org.apache.doris.datasource.property.storage.S3Properties;
import org.apache.doris.datasource.property.storage.StorageProperties;
import org.apache.doris.fs.remote.AzureFileSystem;
import org.apache.doris.fs.remote.BrokerFileSystem;
+import org.apache.doris.fs.remote.OSSFileSystem;
import org.apache.doris.fs.remote.RemoteFileSystem;
import org.apache.doris.fs.remote.S3FileSystem;
import org.apache.doris.fs.remote.dfs.DFSFileSystem;
@@ -38,7 +39,7 @@ import java.util.Arrays;
import java.util.function.Function;
public enum StorageTypeMapper {
- OSS(OSSProperties.class, S3FileSystem::new),
+ OSS(OSSProperties.class, OSSFileSystem::new),
OBS(OBSProperties.class, S3FileSystem::new),
COS(COSProperties.class, S3FileSystem::new),
MINIO(MinioProperties.class, S3FileSystem::new),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/fs/obj/OSSObjStorage.java b/fe/fe-core/src/main/java/org/apache/doris/fs/obj/OSSObjStorage.java
new file mode 100644
index 00000000000..adb32c64c6d
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/fs/obj/OSSObjStorage.java
@@ -0,0 +1,639 @@
+// 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.fs.obj;
+
+import org.apache.doris.backup.Status;
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.util.S3URI;
+import org.apache.doris.common.util.S3Util;
+import org.apache.doris.common.util.Util;
+import org.apache.doris.datasource.property.storage.OSSProperties;
+import org.apache.doris.fs.GlobListResult;
+import org.apache.doris.fs.remote.RemoteFile;
+
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import com.aliyun.oss.OSSException;
+import com.aliyun.oss.common.auth.CredentialsProvider;
+import com.aliyun.oss.common.auth.DefaultCredentialProvider;
+import com.aliyun.oss.common.auth.EcsRamRoleCredentialsProvider;
+import com.aliyun.oss.model.CompleteMultipartUploadRequest;
+import com.aliyun.oss.model.ListObjectsV2Request;
+import com.aliyun.oss.model.ListObjectsV2Result;
+import com.aliyun.oss.model.OSSObjectSummary;
+import com.aliyun.oss.model.ObjectMetadata;
+import com.aliyun.oss.model.PartETag;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.Triple;
+import org.apache.hadoop.fs.Path;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.file.FileSystems;
+import java.nio.file.PathMatcher;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * ObjStorage implementation backed by the Alibaba Cloud OSS Java SDK (aliyun-sdk-oss:3.15.0).
+ * Used for FE-side file listing and metadata operations on OSS buckets.
+ *
+ * Handles all credential cases natively, avoiding AWS SDK SigV4 signing incompatibility
+ * with Alibaba STS tokens:
+ * 1. Static ak/sk → DefaultCredentialProvider(ak, sk)
+ * 2. Static ak/sk + session_token → DefaultCredentialProvider(ak, sk, token)
+ * 3. role_arn via ECS RAM role → ECS metadata (100.100.100.200) → STS AssumeRole
+ * 4. ECS direct (no role_arn) → EcsRamRoleCredentialsProvider(roleName from env)
+ */
+public class OSSObjStorage implements ObjStorage<OSS> {
+ private static final Logger LOG = LogManager.getLogger(OSSObjStorage.class);
+
+ private final OSSProperties ossProperties;
+ private volatile OSS client;
+
+ private final boolean isUsePathStyle;
+ private final boolean forceParsingByStandardUri;
+
+ public OSSObjStorage(OSSProperties ossProperties) {
+ this.ossProperties = ossProperties;
+ // OSS only supports virtual-hosted style (bucket.endpoint/key).
+ // Path style is not supported — always use false for S3URI parsing
+ // regardless of what the user configured.
+ this.isUsePathStyle = false;
+ this.forceParsingByStandardUri = Boolean.parseBoolean(ossProperties.getForceParsingByStandardUrl());
+ }
+
+ @Override
+ public OSS getClient() throws UserException {
+ if (client == null) {
+ synchronized (this) {
+ if (client == null) {
+ client = buildOssClient();
+ }
+ }
+ }
+ return client;
+ }
+
+ private OSS buildOssClient() {
+ String endpoint = ossProperties.getEndpoint();
+ if (!endpoint.startsWith("http://") && !endpoint.startsWith("https://")) {
+ endpoint = "https://" + endpoint;
+ }
+
+ String ak = ossProperties.getAccessKey();
+ String sk = ossProperties.getSecretKey();
+ String token = ossProperties.getSessionToken();
+ String roleArn = ossProperties.getOssRoleArn();
+ String externalId = ossProperties.getOssExternalId();
+ String region = ossProperties.getRegion();
+
+ CredentialsProvider provider;
+
+ if (StringUtils.isNotBlank(roleArn)) {
+ // role_arn: ECS RAM role → STS AssumeRole → temporary credentials
+ Triple<String, String, String> stsCreds =
+ resolveEcsRoleThenAssumeRole(roleArn, externalId, region);
+ provider = new DefaultCredentialProvider(
+ stsCreds.getLeft(), stsCreds.getMiddle(), stsCreds.getRight());
+ } else if (StringUtils.isNotBlank(ak) && StringUtils.isNotBlank(sk)) {
+ if (StringUtils.isNotBlank(token)) {
+ // STS temporary credentials: uses x-oss-security-token header correctly.
+ provider = new DefaultCredentialProvider(ak, sk, token);
+ } else {
+ provider = new DefaultCredentialProvider(ak, sk);
+ }
+ } else {
+ // No credentials: rely on ECS instance metadata directly.
+ // ALIBABA_CLOUD_ECS_METADATA env var must be set to the ECS RAM role name.
+ String roleName = System.getenv("ALIBABA_CLOUD_ECS_METADATA");
+ if (StringUtils.isBlank(roleName)) {
+ throw new IllegalArgumentException(
+ "OSS: no credentials provided and ALIBABA_CLOUD_ECS_METADATA is not set. "
+ + "Set oss.access_key/oss.secret_key, oss.role_arn, "
+ + "or ALIBABA_CLOUD_ECS_METADATA=<ecs-ram-role-name>.");
+ }
+ provider = new EcsRamRoleCredentialsProvider(roleName);
+ }
+
+ LOG.info("OSSObjStorage: building client endpoint={}", endpoint);
+ return new OSSClientBuilder().build(endpoint, provider);
+ }
+
+ /**
+ * Fetches ECS instance credentials via 100.100.100.200 then calls Alibaba STS AssumeRole.
+ * Mirrors the C++ OSSSTSCredentialProvider implementation.
+ */
+ private Triple<String, String, String> resolveEcsRoleThenAssumeRole(
+ String roleArn, String externalId, String region) {
+ try {
+ String roleName = fetchEcsRoleName();
+ String[] ecsCredentials = fetchEcsCredentials(roleName);
+ return callStsAssumeRole(
+ ecsCredentials[0], ecsCredentials[1], ecsCredentials[2],
+ roleArn, externalId, region);
+ } catch (Exception e) {
+ throw new RuntimeException(
+ "OSS: failed to assume role via ECS RAM role. role_arn=" + roleArn
+ + " error=" + e.getMessage(), e);
+ }
+ }
+
+ private String fetchEcsRoleName() throws Exception {
+ String response = httpGet(
+ "http://100.100.100.200/latest/meta-data/ram/security-credentials/", 5000);
+ String roleName = response.trim();
+ int newline = roleName.indexOf('\n');
+ if (newline > 0) {
+ roleName = roleName.substring(0, newline).trim();
+ }
+ if (StringUtils.isBlank(roleName)) {
+ throw new RuntimeException("No RAM role attached to this ECS instance");
+ }
+ return roleName;
+ }
+
+ private String[] fetchEcsCredentials(String roleName) throws Exception {
+ String json = httpGet(
+ "http://100.100.100.200/latest/meta-data/ram/security-credentials/" + roleName, 5000);
+ String ak = parseJsonField(json, "AccessKeyId");
+ String sk = parseJsonField(json, "AccessKeySecret");
+ String token = parseJsonField(json, "SecurityToken");
+ if (StringUtils.isAnyBlank(ak, sk, token)) {
+ throw new RuntimeException("ECS metadata returned empty credentials for role: " + roleName);
+ }
+ return new String[]{ak, sk, token};
+ }
+
+ private Triple<String, String, String> callStsAssumeRole(
+ String ecsAk, String ecsSk, String ecsToken,
+ String roleArn, String externalId, String region) throws Exception {
+ com.aliyuncs.profile.DefaultProfile profile =
+ com.aliyuncs.profile.DefaultProfile.getProfile(region);
+ com.aliyuncs.auth.BasicSessionCredentials baseCreds =
+ new com.aliyuncs.auth.BasicSessionCredentials(ecsAk, ecsSk, ecsToken);
+ com.aliyuncs.DefaultAcsClient stsClient = new com.aliyuncs.DefaultAcsClient(
+ profile, new com.aliyuncs.auth.StaticCredentialsProvider(baseCreds));
+
+ com.aliyuncs.auth.sts.AssumeRoleRequest req = new com.aliyuncs.auth.sts.AssumeRoleRequest();
+ req.setRoleArn(roleArn);
+ req.setRoleSessionName("doris-fe-oss-" + (System.currentTimeMillis() % 100000));
+ req.setDurationSeconds(3600L);
+ // TODO: pass externalId when aliyun-java-sdk-core version on build server
+ // supports AssumeRoleRequest.setExternalId(). Currently the bundled version
+ // does not expose this method. Track: https://github.com/aliyun/aliyun-openapi-java-sdk
+
+ com.aliyuncs.auth.sts.AssumeRoleResponse resp = stsClient.getAcsResponse(req);
+ com.aliyuncs.auth.sts.AssumeRoleResponse.Credentials creds = resp.getCredentials();
+ return Triple.of(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());
+ }
+
+ private String httpGet(String urlStr, int timeoutMs) throws Exception {
+ HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
+ conn.setConnectTimeout(timeoutMs);
+ conn.setReadTimeout(timeoutMs);
+ conn.setRequestMethod("GET");
+ int status = conn.getResponseCode();
+ if (status != 200) {
+ throw new RuntimeException("HTTP GET " + urlStr + " returned status " + status);
+ }
+ try (InputStream is = conn.getInputStream();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
+ StringBuilder sb = new StringBuilder();
+ String line;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line).append('\n');
+ }
+ return sb.toString();
+ }
+ }
+
+ private String parseJsonField(String json, String fieldName) {
+ String key = "\"" + fieldName + "\"";
+ int idx = json.indexOf(key);
+ if (idx < 0) {
+ return "";
+ }
+ int colon = json.indexOf(':', idx + key.length());
+ if (colon < 0) {
+ return "";
+ }
+ int start = json.indexOf('"', colon + 1);
+ if (start < 0) {
+ return "";
+ }
+ int end = json.indexOf('"', start + 1);
+ if (end < 0) {
+ return "";
+ }
+ return json.substring(start + 1, end);
+ }
+
+ // -------------------------------------------------------------------------
+ // ObjStorage interface implementation
+ // -------------------------------------------------------------------------
+
+ @Override
+ public Triple<String, String, String> getStsToken() throws DdlException {
+ throw new DdlException("getStsToken() not supported via OSSObjStorage");
+ }
+
+ @Override
+ public Status headObject(String remotePath) {
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ getClient().headObject(uri.getBucket(), uri.getKey());
+ return Status.OK;
+ } catch (OSSException e) {
+ if ("NoSuchKey".equals(e.getErrorCode()) || "NoSuchBucket".equals(e.getErrorCode())) {
+ return new Status(Status.ErrCode.NOT_FOUND, "remote path does not exist: " + remotePath);
+ }
+ return new Status(Status.ErrCode.COMMON_ERROR, "headObject failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "headObject failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ @Override
+ public Status getObject(String remoteFilePath, File localFile) {
+ try {
+ S3URI uri = S3URI.create(remoteFilePath, isUsePathStyle, forceParsingByStandardUri);
+ getClient().getObject(
+ new com.aliyun.oss.model.GetObjectRequest(uri.getBucket(), uri.getKey()),
+ localFile);
+ return Status.OK;
+ } catch (OSSException e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "getObject failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "getObject failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ @Override
+ public Status putObject(String remotePath, InputStream content, long contentLength) {
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ ObjectMetadata meta = new ObjectMetadata();
+ meta.setContentLength(contentLength);
+ getClient().putObject(uri.getBucket(), uri.getKey(), content, meta);
+ return Status.OK;
+ } catch (OSSException e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "putObject failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "putObject failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ @Override
+ public Status deleteObject(String remotePath) {
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ getClient().deleteObject(uri.getBucket(), uri.getKey());
+ return Status.OK;
+ } catch (OSSException e) {
+ if ("NoSuchKey".equals(e.getErrorCode())) {
+ return Status.OK;
+ }
+ return new Status(Status.ErrCode.COMMON_ERROR, "deleteObject failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "deleteObject failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ @Override
+ public Status deleteObjects(String absolutePath) {
+ try {
+ S3URI uri = S3URI.create(absolutePath, isUsePathStyle, forceParsingByStandardUri);
+ String prefix = uri.getKey();
+ String continuationToken = null;
+ do {
+ ListObjectsV2Request req = new ListObjectsV2Request(uri.getBucket())
+ .withPrefix(prefix).withMaxKeys(1000);
+ if (continuationToken != null) {
+ req.setContinuationToken(continuationToken);
+ }
+ ListObjectsV2Result result = getClient().listObjectsV2(req);
+ List<String> keys = new ArrayList<>();
+ for (OSSObjectSummary obj : result.getObjectSummaries()) {
+ keys.add(obj.getKey());
+ }
+ if (!keys.isEmpty()) {
+ getClient().deleteObjects(
+ new com.aliyun.oss.model.DeleteObjectsRequest(uri.getBucket()).withKeys(keys));
+ }
+ continuationToken = result.isTruncated() ? result.getNextContinuationToken() : null;
+ } while (continuationToken != null);
+ return Status.OK;
+ } catch (OSSException e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "deleteObjects failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "deleteObjects failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ @Override
+ public Status copyObject(String origFilePath, String destFilePath) {
+ try {
+ S3URI src = S3URI.create(origFilePath, isUsePathStyle, forceParsingByStandardUri);
+ S3URI dst = S3URI.create(destFilePath, isUsePathStyle, forceParsingByStandardUri);
+ getClient().copyObject(src.getBucket(), src.getKey(), dst.getBucket(), dst.getKey());
+ return Status.OK;
+ } catch (OSSException e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "copyObject failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR, "copyObject failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ @Override
+ public RemoteObjects listObjects(String remotePath, String continuationToken) throws DdlException {
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ String prefix = uri.getKey();
+ ListObjectsV2Request req = new ListObjectsV2Request(uri.getBucket())
+ .withPrefix(prefix).withMaxKeys(1000);
+ if (StringUtils.isNotBlank(continuationToken)) {
+ req.setContinuationToken(continuationToken);
+ }
+ ListObjectsV2Result result = getClient().listObjectsV2(req);
+ List<RemoteObject> objects = new ArrayList<>();
+ for (OSSObjectSummary obj : result.getObjectSummaries()) {
+ String relativePath = obj.getKey().length() > prefix.length()
+ ? obj.getKey().substring(prefix.length()) : obj.getKey();
+ objects.add(new RemoteObject(obj.getKey(), relativePath, obj.getETag(), obj.getSize()));
+ }
+ String nextToken = result.isTruncated() ? result.getNextContinuationToken() : "";
+ return new RemoteObjects(objects, result.isTruncated(), nextToken);
+ } catch (OSSException e) {
+ throw new DdlException("OSS listObjects failed: " + e.getErrorMessage());
+ } catch (Exception e) {
+ throw new DdlException("OSS listObjects failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // Extended operations used by OSSFileSystem
+ // -------------------------------------------------------------------------
+
+ /**
+ * Completes a multipart upload. Used by OSSFileSystem.completeMultipartUpload().
+ * Confirmed API: CompleteMultipartUploadRequest(bucket, key, uploadId, List<PartETag>)
+ * PartETag(int partNumber, String eTag)
+ */
+ public void completeMultipartUpload(String bucket, String key, String uploadId,
+ Map<Integer, String> parts) {
+ try {
+ List<PartETag> partETags = parts.entrySet().stream()
+ .sorted(Map.Entry.comparingByKey())
+ .map(e -> new PartETag(e.getKey(), e.getValue()))
+ .collect(Collectors.toList());
+ getClient().completeMultipartUpload(
+ new CompleteMultipartUploadRequest(bucket, key, uploadId, partETags));
+ } catch (Exception e) {
+ throw new RuntimeException("OSS completeMultipartUpload failed: " + Util.getRootCauseMessage(e), e);
+ }
+ }
+
+ public Status listFiles(String remotePath, boolean recursive, List<RemoteFile> result) {
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ String bucket = uri.getBucket();
+ String key = uri.getKey();
+ String schemaAndBucket = remotePath.substring(0, remotePath.length() - key.length());
+ String prefix = key.endsWith("/") ? key : key + "/";
+
+ String continuationToken = null;
+ do {
+ ListObjectsV2Request req = new ListObjectsV2Request(bucket).withPrefix(prefix);
+ if (!recursive) {
+ req.setDelimiter("/");
+ }
+ if (continuationToken != null) {
+ req.setContinuationToken(continuationToken);
+ }
+ ListObjectsV2Result res = getClient().listObjectsV2(req);
+ for (OSSObjectSummary obj : res.getObjectSummaries()) {
+ if (obj.getKey().equals(prefix)) {
+ continue;
+ }
+ result.add(new RemoteFile(toPath(schemaAndBucket, obj.getKey()),
+ false, obj.getSize(), 0L, obj.getLastModified().getTime(), null));
+ }
+ if (!recursive) {
+ for (String commonPrefix : res.getCommonPrefixes()) {
+ result.add(new RemoteFile(toPath(schemaAndBucket, commonPrefix),
+ true, 0L, 0L, 0L, null));
+ }
+ }
+ continuationToken = res.isTruncated() ? res.getNextContinuationToken() : null;
+ } while (continuationToken != null);
+ return Status.OK;
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR,
+ "OSS listFiles failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ public Status listDirectories(String remotePath, Set<String> result) {
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ String bucket = uri.getBucket();
+ String key = uri.getKey();
+ String prefix = key.endsWith("/") ? key : key + "/";
+ String continuationToken = null;
+ do {
+ ListObjectsV2Request req = new ListObjectsV2Request(bucket)
+ .withPrefix(prefix).withDelimiter("/");
+ if (continuationToken != null) {
+ req.setContinuationToken(continuationToken);
+ }
+ ListObjectsV2Result res = getClient().listObjectsV2(req);
+ result.addAll(res.getCommonPrefixes());
+ continuationToken = res.isTruncated() ? res.getNextContinuationToken() : null;
+ } while (continuationToken != null);
+ return Status.OK;
+ } catch (Exception e) {
+ return new Status(Status.ErrCode.COMMON_ERROR,
+ "OSS listDirectories failed: " + Util.getRootCauseMessage(e));
+ }
+ }
+
+ public Status globList(String remotePath, List<RemoteFile> result, boolean fileNameOnly) {
+ GlobListResult globListResult = globListInternal(remotePath, result, fileNameOnly, null, -1, -1);
+ return globListResult.getStatus();
+ }
+
+ public GlobListResult globListWithLimit(String remotePath, List<RemoteFile> result,
+ String startFile, long fileSizeLimit, long fileNumLimit) {
+ return globListInternal(remotePath, result, false, startFile, fileSizeLimit, fileNumLimit);
+ }
+
+ private GlobListResult globListInternal(String remotePath, List<RemoteFile> result,
+ boolean fileNameOnly, String startFile, long fileSizeLimit, long fileNumLimit) {
+ long roundCnt = 0;
+ long elementCnt = 0;
+ long matchCnt = 0;
+ long matchFileSize = 0L;
+ long startTime = System.nanoTime();
+ String currentMaxFile = "";
+ boolean hasLimits = fileSizeLimit > 0 || fileNumLimit > 0;
+ String bucket = "";
+ String finalPrefix = "";
+
+ try {
+ S3URI uri = S3URI.create(remotePath, isUsePathStyle, forceParsingByStandardUri);
+ bucket = uri.getBucket();
+ String keyPattern = uri.getKey();
+
+ String globPath = S3Util.extendGlobs(keyPattern);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("OSS globList globPath:{}, remotePath:{}", globPath, remotePath);
+ }
+ java.nio.file.Path pathPattern = Paths.get(globPath);
+ PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pathPattern);
+ HashSet<String> directorySet = new HashSet<>();
+
+ finalPrefix = S3Util.getLongestPrefix(globPath);
+
+ ListObjectsV2Request request = new ListObjectsV2Request(bucket)
+ .withPrefix(finalPrefix);
+ if (startFile != null) {
+ request.setStartAfter(startFile);
+ }
+
+ boolean isTruncated = false;
+ boolean reachLimit = false;
+ do {
+ roundCnt++;
+ ListObjectsV2Result response = getClient().listObjectsV2(request);
+
+ for (OSSObjectSummary obj : response.getObjectSummaries()) {
+ elementCnt++;
+
+ // Limit already reached: scan for the next matching key so
+ // the caller can detect hasMoreDataToConsume correctly.
+ if (reachLimit) {
+ java.nio.file.Path checkPath = Paths.get(obj.getKey());
+ if (matcher.matches(checkPath)) {
+ currentMaxFile = obj.getKey();
+ break;
+ }
+ continue;
+ }
+
+ java.nio.file.Path objPath = Paths.get(obj.getKey());
+ boolean isPrefix = false;
+ while (objPath != null && objPath.normalize().toString().startsWith(finalPrefix)) {
+ if (!matcher.matches(objPath)) {
+ isPrefix = true;
+ objPath = objPath.getParent();
+ continue;
+ }
+ if (directorySet.contains(objPath.normalize().toString())) {
+ break;
+ }
+ if (isPrefix) {
+ directorySet.add(objPath.normalize().toString());
+ }
+ matchCnt++;
+ matchFileSize += obj.getSize();
+ String displayPath = fileNameOnly
+ ? objPath.getFileName().toString()
+ : "s3://" + bucket + "/" + objPath.toString();
+ result.add(new RemoteFile(displayPath, !isPrefix,
+ isPrefix ? -1 : obj.getSize(),
+ isPrefix ? -1 : obj.getSize(),
+ isPrefix ? 0 : obj.getLastModified().getTime()));
+
+ currentMaxFile = obj.getKey();
+ if (hasLimits) {
+ boolean overSize = fileSizeLimit > 0 && matchFileSize > fileSizeLimit;
+ boolean overCount = fileNumLimit > 0 && matchCnt >= fileNumLimit;
+ if (overSize || overCount) {
+ reachLimit = true;
+ break;
+ }
+ }
+ break;
+ }
+ }
+
+ isTruncated = response.isTruncated();
+ if (isTruncated && !reachLimit) {
+ request = new ListObjectsV2Request(bucket)
+ .withPrefix(finalPrefix)
+ .withContinuationToken(response.getNextContinuationToken());
+ if (startFile != null) {
+ request.setStartAfter(startFile);
+ }
+ }
+ } while (isTruncated && !reachLimit);
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("OSS globList remotePath:{}, result:{}", remotePath, result);
+ }
+ return new GlobListResult(Status.OK, currentMaxFile, bucket, finalPrefix);
+ } catch (OSSException e) {
+ if ("NoSuchKey".equals(e.getErrorCode()) || "NoSuchBucket".equals(e.getErrorCode())) {
+ LOG.info("OSS NoSuchKey/Bucket when listing, treat as empty. bucket={} prefix={}",
+ bucket, finalPrefix);
+ return new GlobListResult(Status.OK, "", bucket, finalPrefix);
+ }
+ LOG.warn("OSS Errors while getting file status bucket={} prefix={}", bucket, finalPrefix, e);
+ return new GlobListResult(new Status(Status.ErrCode.COMMON_ERROR,
+ "Errors while getting file status " + e.getErrorMessage()));
+ } catch (Exception e) {
+ LOG.warn("OSS Errors while getting file status bucket={} prefix={}", bucket, finalPrefix, e);
+ return new GlobListResult(new Status(Status.ErrCode.COMMON_ERROR,
+ "Errors while getting file status " + Util.getRootCauseMessage(e)));
+ } finally {
+ if (LOG.isDebugEnabled()) {
+ long duration = System.nanoTime() - startTime;
+ LOG.debug("OSS globList: {} elements under prefix {} in {} rounds, "
+ + "{} matched, took {} ms",
+ elementCnt, finalPrefix, roundCnt, matchCnt, duration / 1_000_000);
+ }
+ }
+ }
+
+ protected static Path toPath(String schemaAndBucket, String key) {
+ String cleanedBase = (schemaAndBucket == null) ? "" : schemaAndBucket.replaceAll("/+$", "");
+ String cleanedKey = (key == null) ? "" : key.replaceAll("^/+", "");
+ return new Path(cleanedBase + "/" + cleanedKey);
+ }
+
+ @Override
+ public void close() throws Exception {
+ if (client != null) {
+ client.shutdown();
+ client = null;
+ }
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/fs/remote/OSSFileSystem.java b/fe/fe-core/src/main/java/org/apache/doris/fs/remote/OSSFileSystem.java
new file mode 100644
index 00000000000..3986854dd89
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/fs/remote/OSSFileSystem.java
@@ -0,0 +1,138 @@
+// 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.fs.remote;
+
+import org.apache.doris.analysis.StorageBackend.StorageType;
+import org.apache.doris.backup.Status;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.util.S3URI;
+import org.apache.doris.datasource.property.storage.OSSProperties;
+import org.apache.doris.datasource.property.storage.StorageProperties;
+import org.apache.doris.fs.GlobListResult;
+import org.apache.doris.fs.obj.OSSObjStorage;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * RemoteFileSystem backed by the Alibaba Cloud OSS Java SDK (aliyun-sdk-oss:3.15.0).
+ *
+ * Handles all credential types correctly using OSS-native signing:
+ * - Static ak/sk (permanent credentials)
+ * - Static ak/sk + session_token (STS temporary credentials) — fixes AWS SDK signing mismatch
+ * - role_arn via ECS RAM role (ECS metadata → STS AssumeRole)
+ * - ECS direct (via ALIBABA_CLOUD_ECS_METADATA env var)
+ *
+ * Follows the same pattern as AzureFileSystem: extends ObjFileSystem, wraps OSSObjStorage.
+ */
+public class OSSFileSystem extends ObjFileSystem {
+ private static final Logger LOG = LogManager.getLogger(OSSFileSystem.class);
+
+ private final OSSProperties ossProperties;
+
+ public OSSFileSystem(OSSProperties ossProperties) {
+ super(StorageType.S3.name(), StorageType.S3, new OSSObjStorage(ossProperties));
+ this.ossProperties = ossProperties;
+ // Populate properties map so callers using getProperties() see the OSS config.
+ // Mirrors S3FileSystem.initFsProperties() and AzureFileSystem constructor behaviour.
+ this.properties.putAll(ossProperties.getOrigProps());
+ }
+
+ @Override
+ public StorageProperties getStorageProperties() {
+ return ossProperties;
+ }
+
+ @Override
+ public Status listFiles(String remotePath, boolean recursive, List<RemoteFile> result) {
+ return getOssObjStorage().listFiles(remotePath, recursive, result);
+ }
+
+ @Override
+ public Status globList(String remotePath, List<RemoteFile> result, boolean fileNameOnly) {
+ return getOssObjStorage().globList(remotePath, result, fileNameOnly);
+ }
+
+ @Override
+ public GlobListResult globListWithLimit(String remotePath, List<RemoteFile> result,
+ String startFile, long fileSizeLimit, long fileNumLimit) {
+ return getOssObjStorage().globListWithLimit(remotePath, result, startFile, fileSizeLimit, fileNumLimit);
+ }
+
+ @Override
+ public Status listDirectories(String remotePath, Set<String> result) {
+ return getOssObjStorage().listDirectories(remotePath, result);
+ }
+
+ // Connectivity test using doesBucketExist() per bucket
+ @Override
+ public boolean connectivityTest(List<String> filePaths) throws UserException {
+ if (filePaths == null || filePaths.isEmpty()) {
+ throw new UserException("File paths cannot be null or empty for connectivity test.");
+ }
+ try {
+ OSSObjStorage ossObjStorage = getOssObjStorage();
+ // OSS only supports virtual-hosted style — always parse with usePathStyle=false
+ Set<String> bucketNames = new HashSet<>();
+ for (String filePath : filePaths) {
+ S3URI uri = S3URI.create(filePath, false,
+ Boolean.parseBoolean(ossProperties.getForceParsingByStandardUrl()));
+ bucketNames.add(uri.getBucket());
+ }
+ for (String bucketName : bucketNames) {
+ // doesBucketExist() confirmed in OSS SDK: boolean doesBucketExist(String bucketName)
+ boolean exists = ossObjStorage.getClient().doesBucketExist(bucketName);
+ if (!exists) {
+ LOG.warn("OSSFileSystem connectivityTest: bucket {} does not exist", bucketName);
+ return false;
+ }
+ }
+ return true;
+ } catch (Exception e) {
+ LOG.warn("OSSFileSystem connectivityTest error: {}", e.getMessage(), e);
+ return false;
+ }
+ }
+
+ @Override
+ public void completeMultipartUpload(String bucket, String key, String uploadId,
+ Map<Integer, String> parts) {
+ getOssObjStorage().completeMultipartUpload(bucket, key, uploadId, parts);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (closed.compareAndSet(false, true)) {
+ try {
+ objStorage.close();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ private OSSObjStorage getOssObjStorage() {
+ return (OSSObjStorage) this.objStorage;
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/httpv2/config/WebServerFactoryCustomizerConfig.java b/fe/fe-core/src/main/java/org/apache/doris/httpv2/config/WebServerFactoryCustomizerConfig.java
index c73c3b28749..ead380b260e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/httpv2/config/WebServerFactoryCustomizerConfig.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/httpv2/config/WebServerFactoryCustomizerConfig.java
@@ -19,6 +19,10 @@ package org.apache.doris.httpv2.config;
import org.apache.doris.common.Config;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.eclipse.jetty.ee10.webapp.WebAppContext;
+import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.ServerConnector;
@@ -31,6 +35,8 @@ import java.util.Collections;
@Configuration
public class WebServerFactoryCustomizerConfig implements WebServerFactoryCustomizer<ConfigurableJettyWebServerFactory> {
+ private static final Logger LOG = LogManager.getLogger(WebServerFactoryCustomizerConfig.class);
+
@Override
public void customize(ConfigurableJettyWebServerFactory factory) {
@@ -48,24 +54,36 @@ public class WebServerFactoryCustomizerConfig implements WebServerFactoryCustomi
}
}
});
+
+ ((JettyServletWebServerFactory) factory).addServerCustomizers(server -> {
+ WebAppContext context = server.getDescendant(WebAppContext.class);
+ if (context != null) {
+ try {
+ JettyWebSocketServletContainerInitializer.configure(context, null);
+ } catch (Exception e) {
+ LOG.error("Failed to initialize WebSocket support", e);
+ throw new RuntimeException("Failed to initialize WebSocket support", e);
+ }
+ }
+ });
+
if (Config.enable_https) {
((JettyServletWebServerFactory) factory).setConfigurations(
Collections.singletonList(new HttpToHttpsJettyConfig())
);
- factory.addServerCustomizers(
- server -> {
- HttpConfiguration httpConfiguration = new HttpConfiguration();
- httpConfiguration.setSecurePort(Config.https_port);
- httpConfiguration.setSecureScheme("https");
-
- ServerConnector connector = new ServerConnector(server);
- connector.addConnectionFactory(new HttpConnectionFactory(httpConfiguration));
- connector.setPort(Config.http_port);
-
- server.addConnector(connector);
+ factory.addServerCustomizers(server -> {
+ if (server.getConnectors() != null && server.getConnectors().length > 0) {
+ ServerConnector existingConnector = (ServerConnector) server.getConnectors()[0];
+ HttpConnectionFactory httpFactory =
+ existingConnector.getConnectionFactory(HttpConnectionFactory.class);
+ if (httpFactory != null) {
+ HttpConfiguration httpConfig = httpFactory.getHttpConfiguration();
+ httpConfig.setSecurePort(Config.https_port);
+ httpConfig.setSecureScheme("https");
}
- );
+ }
+ });
}
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/info/CreateResourceInfo.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/info/CreateResourceInfo.java
index 8365693ec69..5500883d785 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/info/CreateResourceInfo.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/info/CreateResourceInfo.java
@@ -26,6 +26,7 @@ import org.apache.doris.common.ErrorReport;
import org.apache.doris.common.FeNameFormat;
import org.apache.doris.common.UserException;
import org.apache.doris.datasource.property.storage.AzureProperties;
+import org.apache.doris.datasource.property.storage.OSSProperties;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.qe.ConnectContext;
@@ -96,6 +97,11 @@ public class CreateResourceInfo {
return;
}
+ if (OSSProperties.guessIsMe(properties)) {
+ resourceType = ResourceType.OSS;
+ return;
+ }
+
resourceType = ResourceType.fromString(type);
if (resourceType == ResourceType.UNKNOWN || resourceType == ResourceType.SPARK) {
throw new AnalysisException("Unsupported resource type: " + type);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/persist/gson/GsonUtils.java b/fe/fe-core/src/main/java/org/apache/doris/persist/gson/GsonUtils.java
index e315f967a73..e6cc2fefc48 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/persist/gson/GsonUtils.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/persist/gson/GsonUtils.java
@@ -91,6 +91,7 @@ import org.apache.doris.catalog.MTMV;
import org.apache.doris.catalog.MapType;
import org.apache.doris.catalog.MysqlDBTable;
import org.apache.doris.catalog.MysqlTable;
+import org.apache.doris.catalog.OSSResource;
import org.apache.doris.catalog.OdbcCatalogResource;
import org.apache.doris.catalog.OdbcTable;
import org.apache.doris.catalog.OlapTable;
@@ -360,6 +361,7 @@ public class GsonUtils {
.registerSubtype(SparkResource.class, SparkResource.class.getSimpleName())
.registerSubtype(OdbcCatalogResource.class, OdbcCatalogResource.class.getSimpleName())
.registerSubtype(S3Resource.class, S3Resource.class.getSimpleName())
+ .registerSubtype(OSSResource.class, OSSResource.class.getSimpleName())
.registerSubtype(JdbcResource.class, JdbcResource.class.getSimpleName())
.registerSubtype(HdfsResource.class, HdfsResource.class.getSimpleName())
.registerSubtype(HMSResource.class, HMSResource.class.getSimpleName())
diff --git a/fe/fe-core/src/main/java/org/apache/doris/task/PushStoragePolicyTask.java b/fe/fe-core/src/main/java/org/apache/doris/task/PushStoragePolicyTask.java
index 19f462169ea..d1d5b1387c9 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/task/PushStoragePolicyTask.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/task/PushStoragePolicyTask.java
@@ -21,6 +21,7 @@ import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.HdfsResource;
import org.apache.doris.catalog.Resource;
import org.apache.doris.catalog.Resource.ResourceType;
+import org.apache.doris.datasource.property.storage.OSSProperties;
import org.apache.doris.datasource.property.storage.S3Properties;
import org.apache.doris.policy.Policy;
import org.apache.doris.policy.StoragePolicy;
@@ -64,8 +65,9 @@ public class PushStoragePolicyTask extends AgentTask {
String resourceName = storagePolicy.getStorageResource();
Resource resource = Env.getCurrentEnv().getResourceMgr().getResource(resourceName);
if (resource == null || (resource.getType() != ResourceType.S3
+ && resource.getType() != ResourceType.OSS
&& resource.getType() != ResourceType.HDFS)) {
- LOG.warn("can't find s3 resource or hdfs resource by name {}", resourceName);
+ LOG.warn("can't find s3, oss, or hdfs resource by name {}", resourceName);
return;
}
item.setResourceId(resource.getId());
@@ -89,6 +91,8 @@ public class PushStoragePolicyTask extends AgentTask {
item.setVersion(r.getVersion());
if (r.getType() == ResourceType.S3) {
item.setS3StorageParam(S3Properties.getS3TStorageParam(r.getCopiedProperties()));
+ } else if (r.getType() == ResourceType.OSS) {
+ item.setS3StorageParam(OSSProperties.getS3TStorageParam(r.getCopiedProperties()));
} else if (r.getType() == ResourceType.HDFS) {
item.setHdfsStorageParam(HdfsResource.generateHdfsParam(r.getCopiedProperties()));
}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/storage/OSSPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/storage/OSSPropertiesTest.java
index 7c9ec53b177..0d4f5dd57bb 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/storage/OSSPropertiesTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/storage/OSSPropertiesTest.java
@@ -19,6 +19,9 @@ package org.apache.doris.datasource.property.storage;
import org.apache.doris.common.ExceptionChecker;
import org.apache.doris.common.UserException;
+import org.apache.doris.thrift.TCredProviderType;
+import org.apache.doris.thrift.TObjStorageType;
+import org.apache.doris.thrift.TS3StorageParam;
import com.google.common.collect.Maps;
import org.junit.jupiter.api.Assertions;
@@ -44,7 +47,8 @@ public class OSSPropertiesTest {
origProps.put(StorageProperties.FS_OSS_SUPPORT, "true");
Map<String, String> finalOrigProps = origProps;
ExceptionChecker.expectThrowsWithMsg(IllegalArgumentException.class,
- "Region is not set. If you are using a standard endpoint, the region will be detected automatically. Otherwise, please specify it explicitly.", () -> StorageProperties.createPrimary(finalOrigProps));
+ "Region is not set. Either set a standard endpoint or specify oss.region explicitly.",
+ () -> StorageProperties.createPrimary(finalOrigProps));
origProps.put("oss.endpoint", "oss-cn-shenzhen-finance-1-internal.aliyuncs.com");
Map<String, String> finalOrigProps1 = origProps;
OSSProperties ossProperties = (OSSProperties) StorageProperties.createPrimary(finalOrigProps1);
@@ -294,4 +298,129 @@ public class OSSPropertiesTest {
Assertions.assertEquals("s3://my-bucket/path/to/dir/file.txt", OSSProperties.rewriteOssBucketIfNecessary("s3://my-bucket.oss-cn-hangzhou.aliyuncs.com/path/to/dir/file.txt"));
Assertions.assertEquals("https://bucket-name.oss-cn-hangzhou.aliyuncs.com/path/to/dir/file.txt", OSSProperties.rewriteOssBucketIfNecessary("https://bucket-name.oss-cn-hangzhou.aliyuncs.com/path/to/dir/file.txt"));
}
+
+ @Test
+ public void testRoleArnBackendConfigProperties() {
+ Map<String, String> props = new HashMap<>();
+ props.put("oss.endpoint", "oss-cn-hangzhou.aliyuncs.com");
+ props.put("oss.access_key", "myAccessKey");
+ props.put("oss.secret_key", "mySecretKey");
+ props.put("oss.role_arn", "acs:ram::12345:role/my-role");
+ OSSProperties ossProperties = (OSSProperties) StorageProperties.createPrimary(props);
+ Map<String, String> backendProps = ossProperties.getBackendConfigProperties();
+ Assertions.assertEquals("acs:ram::12345:role/my-role", backendProps.get("AWS_ROLE_ARN"));
+ Assertions.assertEquals("INSTANCE_PROFILE", backendProps.get("AWS_CREDENTIALS_PROVIDER_TYPE"));
+ Assertions.assertNull(backendProps.get("AWS_EXTERNAL_ID"));
+ }
+
+ @Test
+ public void testRoleArnWithExternalIdBackendConfigProperties() {
+ Map<String, String> props = new HashMap<>();
+ props.put("oss.endpoint", "oss-cn-hangzhou.aliyuncs.com");
+ props.put("oss.access_key", "myAccessKey");
+ props.put("oss.secret_key", "mySecretKey");
+ props.put("oss.role_arn", "acs:ram::12345:role/my-role");
+ props.put("oss.external_id", "my-external-id");
+ OSSProperties ossProperties = (OSSProperties) StorageProperties.createPrimary(props);
+ Map<String, String> backendProps = ossProperties.getBackendConfigProperties();
+ Assertions.assertEquals("acs:ram::12345:role/my-role", backendProps.get("AWS_ROLE_ARN"));
+ Assertions.assertEquals("INSTANCE_PROFILE", backendProps.get("AWS_CREDENTIALS_PROVIDER_TYPE"));
+ Assertions.assertEquals("my-external-id", backendProps.get("AWS_EXTERNAL_ID"));
+ }
+
+ @Test
+ public void testExternalIdWithoutRoleArnThrows() {
+ Map<String, String> props = new HashMap<>();
+ props.put("oss.endpoint", "oss-cn-hangzhou.aliyuncs.com");
+ props.put("oss.access_key", "myAccessKey");
+ props.put("oss.secret_key", "mySecretKey");
+ props.put("oss.external_id", "my-external-id");
+ ExceptionChecker.expectThrowsWithMsg(IllegalArgumentException.class,
+ "oss.external_id must be used with oss.role_arn",
+ () -> StorageProperties.createPrimary(props));
+ }
+
+ @Test
+ public void testRoleArnReturnsNullCredentialsProvider() {
+ Map<String, String> props = new HashMap<>();
+ props.put("oss.endpoint", "oss-cn-hangzhou.aliyuncs.com");
+ props.put("oss.role_arn", "acs:ram::12345:role/my-role");
+ OSSProperties ossProperties = (OSSProperties) StorageProperties.createPrimary(props);
+ // FE cannot assume Alibaba Cloud RAM role via AWS SDK; BE handles this via OSSSTSCredentialProvider
+ Assertions.assertNull(ossProperties.getAwsCredentialsProvider());
+ }
+
+ @Test
+ public void testRoleArnWithStaticCredsCredentialsProviderIsNull() {
+ Map<String, String> props = new HashMap<>();
+ props.put("oss.endpoint", "oss-cn-hangzhou.aliyuncs.com");
+ props.put("oss.access_key", "myAccessKey");
+ props.put("oss.secret_key", "mySecretKey");
+ props.put("oss.role_arn", "acs:ram::12345:role/my-role");
+ OSSProperties ossProperties = (OSSProperties) StorageProperties.createPrimary(props);
+ // FE cannot assume Alibaba Cloud RAM role via AWS SDK regardless of static credentials
+ Assertions.assertNull(ossProperties.getAwsCredentialsProvider());
+ }
+
+ // -----------------------------------------------------------------
+ // OSSProperties.getS3TStorageParam() — Thrift serialisation for the
+ // storage-policy path (PushStoragePolicyTask → BE).
+ // Properties must be pre-normalised to s3.* keys, as OSSResource does
+ // via normalizeOssToS3Keys() before calling getCopiedProperties().
+ // -----------------------------------------------------------------
+
+ @Test
+ public void testGetS3TStorageParamSetsProviderOss() {
+ // Simulate what OSSResource.getCopiedProperties() returns after
+ // normalizeOssToS3Keys(): both oss.* originals and s3.* copies present.
+ Map<String, String> props = new HashMap<>();
+ props.put("s3.endpoint", "oss-cn-hangzhou.aliyuncs.com");
+ props.put("s3.region", "cn-hangzhou");
+ props.put("s3.access_key", "myAccessKey");
+ props.put("s3.secret_key", "mySecretKey");
+ props.put("s3.bucket", "my-bucket");
+ props.put("s3.root.path", "/data/root");
+ props.put("s3.connection.maximum", "80");
+ props.put("s3.connection.request.timeout", "5000");
+ props.put("s3.connection.timeout", "2000");
+ props.put("use_path_style", "true");
+
+ TS3StorageParam param = OSSProperties.getS3TStorageParam(props);
+
+ // Provider must always be OSS — this is the key correctness guarantee.
+ Assertions.assertEquals(TObjStorageType.OSS, param.getProvider());
+
+ Assertions.assertEquals("oss-cn-hangzhou.aliyuncs.com", param.getEndpoint());
+ Assertions.assertEquals("cn-hangzhou", param.getRegion());
+ Assertions.assertEquals("myAccessKey", param.getAk());
+ Assertions.assertEquals("mySecretKey", param.getSk());
+ Assertions.assertEquals("my-bucket", param.getBucket());
+ Assertions.assertEquals("/data/root", param.getRootPath());
+ Assertions.assertEquals(80, param.getMaxConn());
+ Assertions.assertEquals(5000, param.getRequestTimeoutMs());
+ Assertions.assertEquals(2000, param.getConnTimeoutMs());
+ Assertions.assertTrue(param.isUsePathStyle());
+ }
+
+ @Test
+ public void testGetS3TStorageParamWithRoleArn() {
+ Map<String, String> props = new HashMap<>();
+ props.put("s3.endpoint", "oss-cn-beijing.aliyuncs.com");
+ props.put("s3.region", "cn-beijing");
+ props.put("s3.bucket", "my-bucket");
+ props.put("s3.root.path", "/data/root");
+ props.put("s3.role_arn", "acs:ram::12345:role/my-role");
+ props.put("s3.external_id", "my-external-id");
+
+ TS3StorageParam param = OSSProperties.getS3TStorageParam(props);
+
+ Assertions.assertEquals(TObjStorageType.OSS, param.getProvider());
+ Assertions.assertEquals("acs:ram::12345:role/my-role", param.getRoleArn());
+ Assertions.assertEquals("my-external-id", param.getExternalId());
+ // role_arn without ak/sk → INSTANCE_PROFILE so BE uses Alibaba STS v2
+ Assertions.assertEquals(TCredProviderType.INSTANCE_PROFILE, param.getCredProviderType());
+ // No ak/sk in the map → fields should be null/empty
+ Assertions.assertNull(param.getAk());
+ Assertions.assertNull(param.getSk());
+ }
}
diff --git a/regression-test/suites/oss_vault_p0/test_oss_vault_with_assumerole.groovy b/regression-test/suites/oss_vault_p0/test_oss_vault_with_assumerole.groovy
new file mode 100644
index 00000000000..46a02782f95
--- /dev/null
+++ b/regression-test/suites/oss_vault_p0/test_oss_vault_with_assumerole.groovy
@@ -0,0 +1,158 @@
+// 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.
+
+import com.google.common.base.Strings;
+
+suite("test_oss_vault_with_assumerole") {
+ if (!isCloudMode()) {
+ logger.info("skip ${name} case, because not cloud mode")
+ return
+ }
+
+ if (!enableStoragevault()) {
+ logger.info("skip ${name} case, because storage vault not enabled")
+ return
+ }
+
+ def endpoint = context.config.otherConfigs.get("ossEndpoint")
+ if (!endpoint) {
+ logger.info("skip ${name} case, OSS config not set (ossEndpoint not configured)")
+ return
+ }
+
+ def randomStr = UUID.randomUUID().toString().replace("-", "")
+ def ossVaultName = "oss_" + randomStr
+
+ def region = context.config.otherConfigs.get("ossRegion")
+ def bucket = context.config.otherConfigs.get("ossBucket")
+ def roleArn = context.config.otherConfigs.get("ossRoleArn")
+ def externalId = context.config.otherConfigs.get("ossExternalId")
+ def prefix = context.config.otherConfigs.get("ossPrefix")
+
+ // Test 1: Create OSS storage vault with AssumeRole (no external_id)
+ // Note: When role_arn is provided, INSTANCE_PROFILE is automatically used as base credential provider
+ sql """
+ CREATE STORAGE VAULT IF NOT EXISTS ${ossVaultName}
+ PROPERTIES (
+ "type"="S3",
+ "provider"="OSS",
+ "s3.endpoint"="${endpoint}",
+ "s3.region" = "${region}",
+ "s3.role_arn" = "${roleArn}",
+ "s3.root.path" = "${prefix}/oss_vault_p0/${ossVaultName}",
+ "s3.bucket" = "${bucket}",
+ "s3_validity_check" = "false"
+ );
+ """
+
+ // Verify vault was created
+ def vaults = sql """ SHOW STORAGE VAULTS """
+ boolean vaultFound = false
+ for (int i = 0; i < vaults.size(); i++) {
+ if (vaults[i][0] == ossVaultName) {
+ vaultFound = true
+ logger.info("Found OSS vault: ${ossVaultName}")
+ break
+ }
+ }
+ assertTrue(vaultFound, "OSS vault should be created")
+
+ // Test 2: Create table using the vault
+ sql """ DROP TABLE IF EXISTS ${ossVaultName}_table """
+ sql """
+ CREATE TABLE ${ossVaultName}_table (
+ C_CUSTKEY INTEGER NOT NULL,
+ C_NAME VARCHAR(100) NOT NULL,
+ C_CREATED DATETIME NOT NULL
+ )
+ DUPLICATE KEY(C_CUSTKEY, C_NAME)
+ DISTRIBUTED BY HASH(C_CUSTKEY) BUCKETS 1
+ PROPERTIES (
+ "replication_num" = "1",
+ "storage_vault_name" = "${ossVaultName}"
+ )
+ """
+
+ // Test 3: Insert and query data
+ sql """ insert into ${ossVaultName}_table values(1, 'Alice', '2024-01-01 00:00:00'); """
+ sql """ insert into ${ossVaultName}_table values(2, 'Bob', '2024-01-02 00:00:00'); """
+ sql """ sync;"""
+
+ def result = sql """ select * from ${ossVaultName}_table order by C_CUSTKEY; """
+ assertEquals(result.size(), 2)
+ assertEquals(result[0][0], 1)
+ assertEquals(result[0][1], "Alice")
+ assertEquals(result[1][0], 2)
+ assertEquals(result[1][1], "Bob")
+
+ // Test 4: Verify data persisted in OSS by reading again
+ result = sql """ select count(*) from ${ossVaultName}_table; """
+ assertEquals(result[0][0], 2)
+
+ // Test 5: Create another vault with external_id (if configured)
+ if (!Strings.isNullOrEmpty(externalId)) {
+ def ossVaultNameExtId = "oss_extid_" + randomStr
+
+ sql """
+ CREATE STORAGE VAULT IF NOT EXISTS ${ossVaultNameExtId}
+ PROPERTIES (
+ "type"="S3",
+ "provider"="OSS",
+ "s3.endpoint"="${endpoint}",
+ "s3.region" = "${region}",
+ "s3.role_arn" = "${roleArn}",
+ "s3.external_id" = "${externalId}",
+ "s3.root.path" = "${prefix}/oss_vault_p0/${ossVaultNameExtId}",
+ "s3.bucket" = "${bucket}",
+ "s3_validity_check" = "false"
+ );
+ """
+
+ // Create table with external_id vault
+ sql """ DROP TABLE IF EXISTS ${ossVaultNameExtId}_table """
+ sql """
+ CREATE TABLE ${ossVaultNameExtId}_table (
+ ID INTEGER NOT NULL,
+ VALUE VARCHAR(100)
+ )
+ DUPLICATE KEY(ID)
+ DISTRIBUTED BY HASH(ID) BUCKETS 1
+ PROPERTIES (
+ "replication_num" = "1",
+ "storage_vault_name" = "${ossVaultNameExtId}"
+ )
+ """
+
+ sql """ insert into ${ossVaultNameExtId}_table values(100, 'test_external_id'); """
+ sql """ sync;"""
+
+ result = sql """ select * from ${ossVaultNameExtId}_table; """
+ assertEquals(result.size(), 1)
+ assertEquals(result[0][1], "test_external_id")
+
+ logger.info("Successfully tested OSS vault with external_id")
+ }
+
+ logger.info("Successfully completed OSS AssumeRole vault tests")
+
+ // Cleanup
+ sql """ DROP TABLE IF EXISTS ${ossVaultName}_table """
+ if (!Strings.isNullOrEmpty(externalId)) {
+ def ossVaultNameExtId = "oss_extid_" + randomStr
+ sql """ DROP TABLE IF EXISTS ${ossVaultNameExtId}_table """
+ }
+}
diff --git a/thirdparty/build-thirdparty.sh b/thirdparty/build-thirdparty.sh
index 88a3cdbcfb8..996877cdf5e 100755
--- a/thirdparty/build-thirdparty.sh
+++ b/thirdparty/build-thirdparty.sh
@@ -1852,22 +1852,246 @@ build_libuuid() {
make install
}
-# ali_sdk
+# Apache Portable Runtime (APR) - Required by OSS SDK
+build_apr() {
+ # Check if already built
+ if [[ -f "${TP_INSTALL_DIR}/lib/libapr.a" ]]; then
+ echo "APR already built, skipping"
+ return
+ fi
+
+ # Download if needed
+ if [[ ! -d "${TP_SOURCE_DIR}/${APR_SOURCE}" ]]; then
+ echo "Downloading APR..."
+ cd "${TP_SOURCE_DIR}"
+ if [[ ! -f "${APR_NAME}" ]]; then
+ wget --no-check-certificate "${APR_DOWNLOAD}" -O "${APR_NAME}"
+ fi
+ tar xzf "${APR_NAME}"
+ fi
+
+ check_if_source_exist "${APR_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${APR_SOURCE}"
+
+ # Clean previous build
+ make clean || true
+
+ CC=gcc ./configure --enable-layout=classic --prefix="${TP_INSTALL_DIR}" --enable-static --disable-shared
+ make -j "${PARALLEL}"
+ make install
+}
+
+# APR-Util - Required by OSS SDK
+build_apr_util() {
+ # Check if already built
+ if [[ -f "${TP_INSTALL_DIR}/lib/libaprutil.a" ]]; then
+ echo "APR-Util already built, skipping"
+ return
+ fi
+
+ # Download if needed
+ if [[ ! -d "${TP_SOURCE_DIR}/${APR_UTIL_SOURCE}" ]]; then
+ echo "Downloading APR-Util..."
+ cd "${TP_SOURCE_DIR}"
+ if [[ ! -f "${APR_UTIL_NAME}" ]]; then
+ wget --no-check-certificate "${APR_UTIL_DOWNLOAD}" -O "${APR_UTIL_NAME}"
+ fi
+ tar xzf "${APR_UTIL_NAME}"
+ fi
+
+ check_if_source_exist "${APR_UTIL_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${APR_UTIL_SOURCE}"
+
+ # Clean previous build
+ make clean || true
+
+ CC=gcc ./configure --enable-layout=classic --prefix="${TP_INSTALL_DIR}" \
+ --with-apr="${TP_INSTALL_DIR}" \
+ --enable-static --disable-shared
+ make -j "${PARALLEL}"
+ make install
+}
+
+# Alibaba Cloud SDK (old/existing - kept for compatibility)
build_ali_sdk() {
- build_jsoncpp
- build_libuuid
+ if [[ "${BUILD_OSS}" == "OFF" ]]; then
+ echo "Skip build Alibaba Cloud SDK (old version)"
+ return
+ fi
+
check_if_source_exist "${ALI_SDK_SOURCE}"
cd "${TP_SOURCE_DIR}/${ALI_SDK_SOURCE}"
+
rm -rf "${BUILD_DIR}"
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"
- CPPFLAGS="-I${TP_INCLUDE_DIR}" \
- CXXFLAGS="-I${TP_INCLUDE_DIR}" \
- LDFLAGS="-L${TP_LIB_DIR}" \
- "${CMAKE_CMD}" -G "${GENERATOR}" -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \
- -DBUILD_PRODUCT=core -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
- -DTP_INSTALL_DIR="${TP_INSTALL_DIR}" ..
+ "${CMAKE_CMD}" -G "${GENERATOR}" \
+ -DCMAKE_C_COMPILER="${CC:-clang}" \
+ -DCMAKE_CXX_COMPILER="${CXX:-clang++}" \
+ -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
+ -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DBUILD_SAMPLE=OFF \
+ -DBUILD_TESTS=OFF \
+ -DCMAKE_PREFIX_PATH="${TP_INSTALL_DIR}" \
+ -DCMAKE_CXX_FLAGS="-fvisibility=hidden -D_GLIBCXX_USE_CXX11_ABI=1" \
+ ..
+
+ "${BUILD_SYSTEM}" -j "${PARALLEL}"
+ "${BUILD_SYSTEM}" install
+}
+
+# AliCloud OSS C++ SDK 1.10.1 (V1 only - no V2 exists)
+build_oss() {
+ if [[ "${BUILD_OSS}" == "OFF" ]]; then
+ echo "Skip build OSS SDK"
+ else
+ # APR is required for OSS SDK
+ echo "Building APR dependencies for OSS SDK..."
+ build_apr
+ build_apr_util
+
+ check_if_source_exist "${OSS_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${OSS_SOURCE}"
+
+ rm -rf "${BUILD_DIR}"
+ mkdir -p "${BUILD_DIR}"
+ cd "${BUILD_DIR}"
+
+ "${CMAKE_CMD}" -G "${GENERATOR}" \
+ -DCMAKE_C_COMPILER="${CC:-clang}" \
+ -DCMAKE_CXX_COMPILER="${CXX:-clang++}" \
+ -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
+ -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DBUILD_SAMPLE=OFF \
+ -DBUILD_TESTS=OFF \
+ -DCMAKE_PREFIX_PATH="${TP_INSTALL_DIR}" \
+ -DCMAKE_CXX_FLAGS="-fvisibility=hidden -D_GLIBCXX_USE_CXX11_ABI=1" \
+ ..
+
+ "${BUILD_SYSTEM}" -j "${PARALLEL}"
+ "${BUILD_SYSTEM}" install
+ fi
+}
+
+# tea-cpp (darabonba_core) - Part of STS SDK V2 for OSS
+build_tea_cpp() {
+ if [[ "${BUILD_OSS}" == "OFF" ]]; then
+ echo "Skip build tea-cpp (STS SDK V2 disabled)"
+ return
+ fi
+
+ check_if_source_exist "${TEA_CPP_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${TEA_CPP_SOURCE}"
+
+ rm -rf "${BUILD_DIR}"
+ mkdir -p "${BUILD_DIR}"
+ cd "${BUILD_DIR}"
+
+ "${CMAKE_CMD}" -G "${GENERATOR}" \
+ -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" \
+ -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
+ -DCMAKE_PREFIX_PATH="${TP_INSTALL_DIR}" \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DOPENSSL_ROOT_DIR="${TP_INSTALL_DIR}" \
+ -DCURL_LIBRARY="${TP_LIB_DIR}/libcurl.a" \
+ -DCURL_INCLUDE_DIR="${TP_INCLUDE_DIR}" \
+ -DCMAKE_CXX_STANDARD=20 \
+ -DCMAKE_CXX_STANDARD_REQUIRED=ON \
+ ..
+
+ "${BUILD_SYSTEM}" -j "${PARALLEL}"
+ "${BUILD_SYSTEM}" install
+}
+
+# credentials-cpp - Part of STS SDK V2 for OSS
+build_credentials_cpp() {
+ if [[ "${BUILD_OSS}" == "OFF" ]]; then
+ echo "Skip build credentials-cpp (STS SDK V2 disabled)"
+ return
+ fi
+
+ check_if_source_exist "${CREDENTIALS_CPP_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${CREDENTIALS_CPP_SOURCE}"
+
+ rm -rf "${BUILD_DIR}"
+ mkdir -p "${BUILD_DIR}"
+ cd "${BUILD_DIR}"
+
+ "${CMAKE_CMD}" -G "${GENERATOR}" \
+ -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" \
+ -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
+ -DCMAKE_PREFIX_PATH="${TP_INSTALL_DIR}" \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DOPENSSL_ROOT_DIR="${TP_INSTALL_DIR}" \
+ -DCURL_LIBRARY="${TP_LIB_DIR}/libcurl.a" \
+ -DCURL_INCLUDE_DIR="${TP_INCLUDE_DIR}" \
+ -DCMAKE_CXX_STANDARD=20 \
+ -DCMAKE_CXX_STANDARD_REQUIRED=ON \
+ ..
+
+ "${BUILD_SYSTEM}" -j "${PARALLEL}"
+ "${BUILD_SYSTEM}" install
+}
+
+# alibabacloud-open-api-v2 - Part of STS SDK V2 for OSS
+build_openapi_v2() {
+ if [[ "${BUILD_OSS}" == "OFF" ]]; then
+ echo "Skip build alibabacloud-open-api-v2 (STS SDK V2 disabled)"
+ return
+ fi
+
+ check_if_source_exist "${OPENAPI_V2_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${OPENAPI_V2_SOURCE}"
+
+ rm -rf "${BUILD_DIR}"
+ mkdir -p "${BUILD_DIR}"
+ cd "${BUILD_DIR}"
+
+ "${CMAKE_CMD}" -G "${GENERATOR}" \
+ -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" \
+ -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
+ -DCMAKE_PREFIX_PATH="${TP_INSTALL_DIR}" \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DOPENSSL_ROOT_DIR="${TP_INSTALL_DIR}" \
+ -DCURL_LIBRARY="${TP_LIB_DIR}/libcurl.a" \
+ -DCURL_INCLUDE_DIR="${TP_INCLUDE_DIR}" \
+ -DCMAKE_CXX_STANDARD=20 \
+ -DCMAKE_CXX_STANDARD_REQUIRED=ON \
+ ..
+
+ "${BUILD_SYSTEM}" -j "${PARALLEL}"
+ "${BUILD_SYSTEM}" install
+}
+
+# sts-20150401 - Part of STS SDK V2 for OSS
+build_sts_20150401() {
+ if [[ "${BUILD_OSS}" == "OFF" ]]; then
+ echo "Skip build sts-20150401 (STS SDK V2 disabled)"
+ return
+ fi
+
+ check_if_source_exist "${STS_20150401_SOURCE}"
+ cd "${TP_SOURCE_DIR}/${STS_20150401_SOURCE}"
+
+ rm -rf "${BUILD_DIR}"
+ mkdir -p "${BUILD_DIR}"
+ cd "${BUILD_DIR}"
+
+ "${CMAKE_CMD}" -G "${GENERATOR}" \
+ -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" \
+ -DCMAKE_INSTALL_PREFIX="${TP_INSTALL_DIR}" \
+ -DCMAKE_PREFIX_PATH="${TP_INSTALL_DIR}" \
+ -DBUILD_SHARED_LIBS=OFF \
+ -DOPENSSL_ROOT_DIR="${TP_INSTALL_DIR}" \
+ -DCURL_LIBRARY="${TP_LIB_DIR}/libcurl.a" \
+ -DCURL_INCLUDE_DIR="${TP_INCLUDE_DIR}" \
+ -DCMAKE_CXX_STANDARD=20 \
+ -DCMAKE_CXX_STANDARD_REQUIRED=ON \
+ ..
+
"${BUILD_SYSTEM}" -j "${PARALLEL}"
"${BUILD_SYSTEM}" install
}
@@ -2145,6 +2369,11 @@ if [[ "${#packages[@]}" -eq 0 ]]; then
libdeflate
streamvbyte
ali_sdk
+ tea_cpp
+ credentials_cpp
+ openapi_v2
+ sts_20150401
+ oss
base64
azure
brotli
diff --git a/thirdparty/download-thirdparty.sh b/thirdparty/download-thirdparty.sh
index 52481b24fca..4e7837c6dde 100755
--- a/thirdparty/download-thirdparty.sh
+++ b/thirdparty/download-thirdparty.sh
@@ -727,4 +727,55 @@ if [[ " ${TP_ARCHIVES[*]} " =~ " CCTZ " ]] ; then
echo "Finished patching ${CCTZ_SOURCE}"
fi
+# patch tea-cpp for OpenSSL 1.1.1 compatibility
+if [[ " ${TP_ARCHIVES[*]} " =~ " TEA_CPP " ]]; then
+ cd "${TP_SOURCE_DIR}/${TEA_CPP_SOURCE}"
+ if [[ ! -f "${PATCHED_MARK}" ]]; then
+ echo "Applying OpenSSL 1.1.1 compatibility fix to tea-cpp..."
+ sed -i.bak 's/EVP_MD_CTX_get0_md/EVP_MD_CTX_md/g' include/darabonba/signature/RSASigner.hpp
+ touch "${PATCHED_MARK}"
+ fi
+ cd -
+ echo "Finished patching ${TEA_CPP_SOURCE}"
+fi
+
+# patch tea-cpp: CURLOPT_CAINFO support + CURL error propagation (required for OSS STS SSL)
+if [[ " ${TP_ARCHIVES[*]} " =~ " TEA_CPP " ]]; then
+ cd "${TP_SOURCE_DIR}/${TEA_CPP_SOURCE}"
+ if [[ ! -f "patched_mark_doris_oss_fix" ]]; then
+ echo "Applying OSS SSL/error fix to tea-cpp..."
+ patch -p1 < "${TP_PATCH_DIR}/tea-cpp-doris-oss-fix.patch"
+ touch "patched_mark_doris_oss_fix"
+ fi
+ cd -
+ echo "Finished patching ${TEA_CPP_SOURCE} (doris-oss-fix)"
+fi
+
+# patch credentials-cpp for OpenSSL 1.1.1 compatibility
+if [[ " ${TP_ARCHIVES[*]} " =~ " CREDENTIALS_CPP " ]]; then
+ cd "${TP_SOURCE_DIR}/${CREDENTIALS_CPP_SOURCE}"
+ if [[ ! -f "${PATCHED_MARK}" ]]; then
+ echo "Applying OpenSSL 1.1.1 compatibility fix to credentials-cpp..."
+ if [[ -f "src/credentials/providers/RsaKeyPairCredentialsProvider.cpp" ]]; then
+ sed -i.bak 's/EVP_MD_CTX_get0_md/EVP_MD_CTX_md/g' src/credentials/providers/RsaKeyPairCredentialsProvider.cpp
+ fi
+ touch "${PATCHED_MARK}"
+ fi
+ cd -
+ echo "Finished patching ${CREDENTIALS_CPP_SOURCE}"
+fi
+
+# boost patch to fix sigtimedwait not available on macOS
+if [[ " ${TP_ARCHIVES[*]} " =~ " BOOST " ]]; then
+ cd "${TP_SOURCE_DIR}/${BOOST_SOURCE}"
+ if [[ ! -f "${PATCHED_MARK}" ]]; then
+ if [[ "$(uname -s)" == "Darwin" ]]; then
+ patch -p1 <"${TP_PATCH_DIR}/boost-1.81.0-mac-sigtimedwait.patch"
+ fi
+ touch "${PATCHED_MARK}"
+ fi
+ cd -
+ echo "Finished patching ${BOOST_SOURCE}"
+fi
+
# vim: ts=4 sw=4 ts=4 tw=100:
diff --git a/thirdparty/patches/tea-cpp-doris-oss-fix.patch b/thirdparty/patches/tea-cpp-doris-oss-fix.patch
new file mode 100644
index 00000000000..29e4ee37c55
--- /dev/null
+++ b/thirdparty/patches/tea-cpp-doris-oss-fix.patch
@@ -0,0 +1,63 @@
+--- a/include/darabonba/Core.hpp
++++ b/include/darabonba/Core.hpp
+@@ -57,4 +57,5 @@
+ std::string https_proxy; // Per-request HTTPS proxy
+ std::string no_proxy; // Per-request no-proxy list
+ std::string credential; // Per-request credentials
++ std::string ca_cert; // Per-request CA cert file path
+ };
+--- a/src/darabonba/Core.cpp
++++ b/src/darabonba/Core.cpp
+@@ -126,6 +126,9 @@
+ if (runtime.contains("credential")) {
+ config.credential = runtime["credential"].get<std::string>();
+ }
++ if (runtime.contains("ca")) {
++ config.ca_cert = runtime["ca"].get<std::string>();
++ }
+ }
+
+ return config;
+@@ -221,6 +224,7 @@
+ request_runtime["httpProxy"] = request_config.http_proxy;
+ request_runtime["httpsProxy"] = request_config.https_proxy;
+ request_runtime["noProxy"] = request_config.no_proxy;
++ request_runtime["ca"] = request_config.ca_cert;
+
+ return it->second->makeRequest(request, request_runtime);
+ }
+--- a/src/darabonba/http/MCurlHttpClient.cpp
++++ b/src/darabonba/http/MCurlHttpClient.cpp
+@@ -30,6 +30,10 @@
+ } else {
+ curl_easy_setopt(easyHandle, CURLOPT_SSL_VERIFYPEER, 1L);
+ curl_easy_setopt(easyHandle, CURLOPT_SSL_VERIFYHOST,
+ 2L); // 2L for full verification
++ std::string caFile = options.value("ca", std::string {});
++ if (!caFile.empty()) {
++ curl_easy_setopt(easyHandle, CURLOPT_CAINFO, caFile.c_str());
++ }
+ }
+ // timeout
+@@ -154,7 +158,21 @@
+ while ((msg = curl_multi_info_read(mCurl_, &msgs_in_queue)) != nullptr) {
+ if (msg->msg == CURLMSG_DONE) {
+ auto easyHandle = msg->easy_handle;
++ auto curlResult = msg->data.result;
+ auto curlStorage = std::move(runningCurl_[easyHandle]);
+ runningCurl_.erase(easyHandle);
+
++ if (curlResult != CURLE_OK) {
++ const char* errorStr = curl_easy_strerror(curlResult);
++ std::string errorMsg = std::string("CURL error: ") + errorStr;
++
++ curl_slist_free_all(curlStorage->reqHeader);
++ curl_multi_remove_handle(mCurl_, easyHandle);
++ curl_easy_cleanup(easyHandle);
++
++ curlStorage->promise->set_exception(
++ std::make_exception_ptr(std::runtime_error(errorMsg)));
++ continue;
++ }
++
+ auto body = dynamic_cast<MCurlResponseBody *>(
diff --git a/thirdparty/vars.sh b/thirdparty/vars.sh
index 87f4132b0ff..2282a236e9c 100644
--- a/thirdparty/vars.sh
+++ b/thirdparty/vars.sh
@@ -434,10 +434,10 @@ SIMDJSON_SOURCE=simdjson-3.11.6
SIMDJSON_MD5SUM="e7d9c814a4fdd6e47119ce5cf4240f4e"
# nlohmann_json
-NLOHMANN_JSON_DOWNLOAD="https://github.com/nlohmann/json/archive/refs/tags/v3.10.1.tar.gz"
-NLOHMANN_JSON_NAME=json-3.10.1.tar.gz
-NLOHMANN_JSON_SOURCE=json-3.10.1
-NLOHMANN_JSON_MD5SUM="7b369d567afc0dffdcf5800fd9abb836"
+NLOHMANN_JSON_DOWNLOAD="https://github.com/nlohmann/json/archive/refs/tags/v3.11.3.tar.gz"
+NLOHMANN_JSON_NAME=json-3.11.3.tar.gz
+NLOHMANN_JSON_SOURCE=json-3.11.3
+NLOHMANN_JSON_MD5SUM="d603041cbc6051edbaa02ebb82cf0aa9"
# libbacktrace
LIBBACKTRACE_DOWNLOAD="https://codeload.github.com/ianlancetaylor/libbacktrace/zip/2446c66076480ce07a6bd868badcbceb3eeecc2e"
@@ -511,12 +511,54 @@ LIBUUID_NAME="libuuid-1.0.3.tar.gz"
LIBUUID_SOURCE="libuuid-1.0.3"
LIBUUID_MD5SUM="d44d866d06286c08ba0846aba1086d68"
-# ali
+# Alibaba Cloud SDK (old/existing)
ALI_SDK_DOWNLOAD="https://github.com/aliyun/aliyun-openapi-cpp-sdk/archive/refs/tags/1.36.1586.tar.gz"
ALI_SDK_NAME="1.36.1586.tar.gz"
ALI_SDK_SOURCE="aliyun-openapi-cpp-sdk-1.36.1586"
ALI_SDK_MD5SUM="14623ee8e87c89615477d9bf8cb30bea"
+# Alibaba Cloud STS SDK V2 - Component 1: tea-cpp (darabonba_core)
+TEA_CPP_DOWNLOAD="https://github.com/aliyun/tea-cpp/archive/b063160af903fe8385f98a95b77a4a8804e09816.tar.gz"
+TEA_CPP_NAME="tea-cpp-b063160.tar.gz"
+TEA_CPP_SOURCE="tea-cpp-b063160af903fe8385f98a95b77a4a8804e09816"
+TEA_CPP_MD5SUM="aeccc8ef5766f0001f81c6cee659776c"
+
+# Alibaba Cloud STS SDK V2 - Component 2: credentials-cpp
+CREDENTIALS_CPP_DOWNLOAD="https://github.com/aliyun/credentials-cpp/archive/f7584e1827b4672d237448f6c8fe348602edf1ae.tar.gz"
+CREDENTIALS_CPP_NAME="credentials-cpp-f7584e1.tar.gz"
+CREDENTIALS_CPP_SOURCE="credentials-cpp-f7584e1827b4672d237448f6c8fe348602edf1ae"
+CREDENTIALS_CPP_MD5SUM="9ece163713695d54aebabc73f388aef4"
+
+# Alibaba Cloud STS SDK V2 - Component 3: alibabacloud-open-api-v2
+OPENAPI_V2_DOWNLOAD="https://github.com/alibabacloud-sdk-cpp/alibabacloud-open-api-v2/archive/b915b2f8673e4c20aa88c3099f28c654128ee20d.tar.gz"
+OPENAPI_V2_NAME="alibabacloud-open-api-v2-b915b2f.tar.gz"
+OPENAPI_V2_SOURCE="alibabacloud-open-api-v2-b915b2f8673e4c20aa88c3099f28c654128ee20d"
+OPENAPI_V2_MD5SUM="7a1e3307f4b33c6e61810f2c06f74d11"
+
+# Alibaba Cloud STS SDK V2 - Component 4: sts-20150401 (v1.0.9)
+STS_20150401_DOWNLOAD="https://github.com/alibabacloud-sdk-cpp/sts-20150401/archive/refs/tags/1.0.9.tar.gz"
+STS_20150401_NAME="sts-20150401-1.0.9.tar.gz"
+STS_20150401_SOURCE="sts-20150401-1.0.9"
+STS_20150401_MD5SUM="ff8a75c6a8f83b8dd694cfa29171ffc7"
+
+# Apache Portable Runtime (APR) - Required by OSS SDK
+APR_DOWNLOAD="https://dlcdn.apache.org//apr/apr-1.7.6.tar.gz"
+APR_NAME="apr-1.7.6.tar.gz"
+APR_SOURCE="apr-1.7.6"
+APR_MD5SUM="44f27088e423da7cefc1a9717b910d85"
+
+# APR-Util - Required by OSS SDK
+APR_UTIL_DOWNLOAD="https://dlcdn.apache.org//apr/apr-util-1.6.3.tar.gz"
+APR_UTIL_NAME="apr-util-1.6.3.tar.gz"
+APR_UTIL_SOURCE="apr-util-1.6.3"
+APR_UTIL_MD5SUM="b2b6fb440548869dc228535e339f619b"
+
+# AliCloud OSS C++ SDK 1.10.1 (V1 only - no V2 exists)
+OSS_DOWNLOAD="https://github.com/aliyun/aliyun-oss-cpp-sdk/archive/refs/tags/1.10.1.tar.gz"
+OSS_NAME="aliyun-oss-cpp-sdk-1.10.1.tar.gz"
+OSS_SOURCE="aliyun-oss-cpp-sdk-1.10.1"
+OSS_MD5SUM="7b1628a678a47148e6c25c88ecf2b5f6"
+
# base64
BASE64_DOWNLOAD="https://github.com/aklomp/base64/archive/refs/tags/v0.5.2.tar.gz"
BASE64_NAME="v0.5.2.tar.gz"
@@ -641,6 +683,11 @@ export TP_ARCHIVES=(
'JSONCPP'
'LIBUUID'
'ALI_SDK'
+ 'TEA_CPP'
+ 'CREDENTIALS_CPP'
+ 'OPENAPI_V2'
+ 'STS_20150401'
+ 'OSS'
'BASE64'
'AZURE'
'DRAGONBOX'
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org