Coverage Report

Created: 2026-07-12 20:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/s3_util.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "util/s3_util.h"
19
20
#include <aws/core/auth/AWSAuthSigner.h>
21
#include <aws/core/auth/AWSCredentials.h>
22
#include <aws/core/auth/AWSCredentialsProviderChain.h>
23
#include <aws/core/auth/STSCredentialsProvider.h>
24
#include <aws/core/client/DefaultRetryStrategy.h>
25
#include <aws/core/platform/Environment.h>
26
#include <aws/core/utils/logging/LogLevel.h>
27
#include <aws/core/utils/logging/LogSystemInterface.h>
28
#include <aws/core/utils/memory/stl/AWSStringStream.h>
29
#include <aws/identity-management/auth/STSAssumeRoleCredentialsProvider.h>
30
#include <aws/s3/S3Client.h>
31
#include <aws/sts/STSClient.h>
32
#include <bvar/reducer.h>
33
#include <cpp/token_bucket_rate_limiter.h>
34
35
#include <atomic>
36
37
#include "util/string_util.h"
38
39
#ifdef USE_AZURE
40
#include <azure/core/diagnostics/logger.hpp>
41
#include <azure/core/http/curl_transport.hpp>
42
#include <azure/storage/blobs/blob_container_client.hpp>
43
#endif
44
#include <cstdlib>
45
#include <filesystem>
46
#include <fstream>
47
#include <functional>
48
#include <memory>
49
#include <ostream>
50
#include <utility>
51
52
#include "common/config.h"
53
#include "common/logging.h"
54
#include "common/status.h"
55
#include "cpp/aws_logger.h"
56
#include "cpp/custom_aws_credentials_provider_chain.h"
57
#include "cpp/gcp_workload_identity_token_provider.h"
58
#include "cpp/obj_retry_strategy.h"
59
#include "cpp/sync_point.h"
60
#include "cpp/util.h"
61
#ifdef USE_AZURE
62
#include "io/fs/azure_obj_storage_client.h"
63
#endif
64
#include "exec/scan/scanner_scheduler.h"
65
#include "io/fs/obj_storage_client.h"
66
#include "io/fs/s3_obj_storage_client.h"
67
#include "runtime/exec_env.h"
68
#include "util/s3_uri.h"
69
70
namespace doris {
71
namespace s3_bvar {
72
bvar::LatencyRecorder s3_get_latency("s3_get");
73
bvar::LatencyRecorder s3_put_latency("s3_put");
74
bvar::LatencyRecorder s3_delete_object_latency("s3_delete_object");
75
bvar::LatencyRecorder s3_delete_objects_latency("s3_delete_objects");
76
bvar::LatencyRecorder s3_head_latency("s3_head");
77
bvar::LatencyRecorder s3_multi_part_upload_latency("s3_multi_part_upload");
78
bvar::LatencyRecorder s3_list_latency("s3_list");
79
bvar::LatencyRecorder s3_list_object_versions_latency("s3_list_object_versions");
80
bvar::LatencyRecorder s3_get_bucket_version_latency("s3_get_bucket_version");
81
bvar::LatencyRecorder s3_copy_object_latency("s3_copy_object");
82
}; // namespace s3_bvar
83
84
namespace {
85
86
85.9k
doris::Status is_s3_conf_valid(const S3ClientConf& conf) {
87
85.9k
    if (conf.endpoint.empty()) {
88
0
        return Status::InvalidArgument<false>("Invalid s3 conf, empty endpoint");
89
0
    }
90
85.9k
    if (conf.region.empty()) {
91
0
        return Status::InvalidArgument<false>("Invalid s3 conf, empty region");
92
0
    }
93
85.9k
    if (conf.cred_provider_type == CredProviderType::GcpWorkloadIdentity) {
94
3
        if (conf.provider != io::ObjStorageType::GCP) {
95
0
            return Status::InvalidArgument<false>("GCP workload identity requires provider GCP");
96
0
        }
97
3
        if (!is_gcs_xml_endpoint(conf.endpoint)) {
98
2
            return Status::InvalidArgument<false>("GCP workload identity requires endpoint {}",
99
2
                                                  GCS_XML_ENDPOINT);
100
2
        }
101
1
        if (!conf.ak.empty() || !conf.sk.empty() || !conf.role_arn.empty()) {
102
0
            return Status::InvalidArgument<false>(
103
0
                    "GCP workload identity cannot be combined with other credentials");
104
0
        }
105
1
    }
106
107
85.9k
    if (conf.role_arn.empty()) {
108
        // Allow anonymous access when both ak and sk are empty
109
85.9k
        bool hasAk = !conf.ak.empty();
110
85.9k
        bool hasSk = !conf.sk.empty();
111
112
        // Either both credentials are provided or both are empty (anonymous access)
113
85.9k
        if (hasAk && conf.sk.empty()) {
114
1
            return Status::InvalidArgument<false>("Invalid s3 conf, empty sk");
115
1
        }
116
85.9k
        if (hasSk && conf.ak.empty()) {
117
9
            return Status::InvalidArgument<false>("Invalid s3 conf, empty ak");
118
9
        }
119
85.9k
    }
120
85.9k
    return Status::OK();
121
85.9k
}
122
123
// Return true is convert `str` to int successfully
124
128k
bool to_int(std::string_view str, int& res) {
125
128k
    auto [_, ec] = std::from_chars(str.data(), str.data() + str.size(), res);
126
128k
    return ec == std::errc {};
127
128k
}
128
129
#ifdef USE_AZURE
130
0
std::string env_or_empty(const char* env_name) {
131
0
    if (const char* value = std::getenv(env_name); value != nullptr) {
132
0
        return value;
133
0
    }
134
0
    return "";
135
0
}
136
137
0
std::string build_azure_tls_debug_context(const std::string& selected_ca_file) {
138
0
    bool selected_ca_exists = false;
139
0
    bool selected_ca_readable = false;
140
0
    if (!selected_ca_file.empty()) {
141
0
        std::error_code ec;
142
0
        selected_ca_exists = std::filesystem::exists(selected_ca_file, ec) && !ec;
143
0
        std::ifstream input(selected_ca_file);
144
0
        selected_ca_readable = input.good();
145
0
    }
146
147
0
    return fmt::format(
148
0
            "tls_debug(ca_cert_file_paths='{}', selected_ca_file='{}', selected_ca_exists={}, "
149
0
            "selected_ca_readable={}, SSL_CERT_FILE='{}', CURL_CA_BUNDLE='{}', SSL_CERT_DIR='{}')",
150
0
            config::ca_cert_file_paths, selected_ca_file, selected_ca_exists, selected_ca_readable,
151
0
            env_or_empty("SSL_CERT_FILE"), env_or_empty("CURL_CA_BUNDLE"),
152
0
            env_or_empty("SSL_CERT_DIR"));
153
0
}
154
#endif
155
156
constexpr char USE_PATH_STYLE[] = "use_path_style";
157
158
constexpr char AZURE_PROVIDER_STRING[] = "AZURE";
159
constexpr char S3_PROVIDER[] = "provider";
160
constexpr char S3_AK[] = "AWS_ACCESS_KEY";
161
constexpr char S3_SK[] = "AWS_SECRET_KEY";
162
constexpr char S3_ENDPOINT[] = "AWS_ENDPOINT";
163
constexpr char S3_REGION[] = "AWS_REGION";
164
constexpr char S3_TOKEN[] = "AWS_TOKEN";
165
constexpr char S3_MAX_CONN_SIZE[] = "AWS_MAX_CONNECTIONS";
166
constexpr char S3_REQUEST_TIMEOUT_MS[] = "AWS_REQUEST_TIMEOUT_MS";
167
constexpr char S3_CONN_TIMEOUT_MS[] = "AWS_CONNECTION_TIMEOUT_MS";
168
constexpr char S3_NEED_OVERRIDE_ENDPOINT[] = "AWS_NEED_OVERRIDE_ENDPOINT";
169
170
constexpr char S3_ROLE_ARN[] = "AWS_ROLE_ARN";
171
constexpr char S3_EXTERNAL_ID[] = "AWS_EXTERNAL_ID";
172
constexpr char S3_CREDENTIALS_PROVIDER_TYPE[] = "AWS_CREDENTIALS_PROVIDER_TYPE";
173
} // namespace
174
175
bvar::Adder<int64_t> get_rate_limit_ns("get_rate_limit_ns");
176
bvar::Adder<int64_t> get_rate_limit_exceed_req_num("get_rate_limit_exceed_req_num");
177
bvar::Adder<int64_t> put_rate_limit_ns("put_rate_limit_ns");
178
bvar::Adder<int64_t> put_rate_limit_exceed_req_num("put_rate_limit_exceed_req_num");
179
180
static std::atomic<int64_t> last_s3_get_token_bucket_tokens {0};
181
static std::atomic<int64_t> last_s3_get_token_limit {0};
182
static std::atomic<int64_t> last_s3_get_token_per_second {0};
183
static std::atomic<int64_t> last_s3_put_token_per_second {0};
184
static std::atomic<int64_t> last_s3_put_token_bucket_tokens {0};
185
static std::atomic<int64_t> last_s3_put_token_limit {0};
186
187
static std::atomic<bool> updating_get_limiter {false};
188
static std::atomic<bool> updating_put_limiter {false};
189
190
17
S3RateLimiterHolder* S3ClientFactory::rate_limiter(S3RateLimitType type) {
191
17
    CHECK(type == S3RateLimitType::GET || type == S3RateLimitType::PUT) << to_string(type);
192
17
    return _rate_limiters[static_cast<size_t>(type)].get();
193
17
}
194
195
template <S3RateLimitType LimiterType>
196
void update_rate_limiter_if_changed(int64_t current_tps, int64_t current_bucket,
197
                                    int64_t current_limit, std::atomic<int64_t>& last_tps,
198
                                    std::atomic<int64_t>& last_bucket,
199
                                    std::atomic<int64_t>& last_limit,
200
86.4k
                                    std::atomic<bool>& updating_flag, const char* limiter_name) {
201
86.4k
    if (last_tps.load(std::memory_order_relaxed) != current_tps ||
202
86.5k
        last_bucket.load(std::memory_order_relaxed) != current_bucket ||
203
86.5k
        last_limit.load(std::memory_order_relaxed) != current_limit) {
204
16
        bool expected = false;
205
16
        if (!updating_flag.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
206
0
            return;
207
0
        }
208
16
        if (last_tps.load(std::memory_order_acquire) != current_tps ||
209
16
            last_bucket.load(std::memory_order_acquire) != current_bucket ||
210
16
            last_limit.load(std::memory_order_acquire) != current_limit) {
211
16
            int ret =
212
16
                    reset_s3_rate_limiter(LimiterType, current_tps, current_bucket, current_limit);
213
214
16
            if (ret == 0) {
215
16
                last_tps.store(current_tps, std::memory_order_release);
216
16
                last_bucket.store(current_bucket, std::memory_order_release);
217
16
                last_limit.store(current_limit, std::memory_order_release);
218
16
            } else {
219
0
                LOG(WARNING) << "Failed to reset S3 " << limiter_name
220
0
                             << " rate limiter, error code: " << ret;
221
0
            }
222
16
        }
223
224
16
        updating_flag.store(false, std::memory_order_release);
225
16
    }
226
86.4k
}
_ZN5doris30update_rate_limiter_if_changedILNS_15S3RateLimitTypeE0EEEvlllRSt6atomicIlES4_S4_RS2_IbEPKc
Line
Count
Source
200
43.2k
                                    std::atomic<bool>& updating_flag, const char* limiter_name) {
201
43.2k
    if (last_tps.load(std::memory_order_relaxed) != current_tps ||
202
43.2k
        last_bucket.load(std::memory_order_relaxed) != current_bucket ||
203
43.2k
        last_limit.load(std::memory_order_relaxed) != current_limit) {
204
10
        bool expected = false;
205
10
        if (!updating_flag.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
206
0
            return;
207
0
        }
208
10
        if (last_tps.load(std::memory_order_acquire) != current_tps ||
209
10
            last_bucket.load(std::memory_order_acquire) != current_bucket ||
210
10
            last_limit.load(std::memory_order_acquire) != current_limit) {
211
10
            int ret =
212
10
                    reset_s3_rate_limiter(LimiterType, current_tps, current_bucket, current_limit);
213
214
10
            if (ret == 0) {
215
10
                last_tps.store(current_tps, std::memory_order_release);
216
10
                last_bucket.store(current_bucket, std::memory_order_release);
217
10
                last_limit.store(current_limit, std::memory_order_release);
218
10
            } else {
219
0
                LOG(WARNING) << "Failed to reset S3 " << limiter_name
220
0
                             << " rate limiter, error code: " << ret;
221
0
            }
222
10
        }
223
224
10
        updating_flag.store(false, std::memory_order_release);
225
10
    }
226
43.2k
}
_ZN5doris30update_rate_limiter_if_changedILNS_15S3RateLimitTypeE1EEEvlllRSt6atomicIlES4_S4_RS2_IbEPKc
Line
Count
Source
200
43.2k
                                    std::atomic<bool>& updating_flag, const char* limiter_name) {
201
43.2k
    if (last_tps.load(std::memory_order_relaxed) != current_tps ||
202
43.2k
        last_bucket.load(std::memory_order_relaxed) != current_bucket ||
203
43.2k
        last_limit.load(std::memory_order_relaxed) != current_limit) {
204
6
        bool expected = false;
205
6
        if (!updating_flag.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
206
0
            return;
207
0
        }
208
6
        if (last_tps.load(std::memory_order_acquire) != current_tps ||
209
6
            last_bucket.load(std::memory_order_acquire) != current_bucket ||
210
6
            last_limit.load(std::memory_order_acquire) != current_limit) {
211
6
            int ret =
212
6
                    reset_s3_rate_limiter(LimiterType, current_tps, current_bucket, current_limit);
213
214
6
            if (ret == 0) {
215
6
                last_tps.store(current_tps, std::memory_order_release);
216
6
                last_bucket.store(current_bucket, std::memory_order_release);
217
6
                last_limit.store(current_limit, std::memory_order_release);
218
6
            } else {
219
0
                LOG(WARNING) << "Failed to reset S3 " << limiter_name
220
0
                             << " rate limiter, error code: " << ret;
221
0
            }
222
6
        }
223
224
6
        updating_flag.store(false, std::memory_order_release);
225
6
    }
226
43.2k
}
227
228
43.2k
void check_s3_rate_limiter_config_changed() {
229
43.2k
    update_rate_limiter_if_changed<S3RateLimitType::GET>(
230
43.2k
            config::s3_get_token_per_second, config::s3_get_bucket_tokens,
231
43.2k
            config::s3_get_token_limit, last_s3_get_token_per_second,
232
43.2k
            last_s3_get_token_bucket_tokens, last_s3_get_token_limit, updating_get_limiter, "GET");
233
234
43.2k
    update_rate_limiter_if_changed<S3RateLimitType::PUT>(
235
43.2k
            config::s3_put_token_per_second, config::s3_put_bucket_tokens,
236
43.2k
            config::s3_put_token_limit, last_s3_put_token_per_second,
237
43.2k
            last_s3_put_token_bucket_tokens, last_s3_put_token_limit, updating_put_limiter, "PUT");
238
43.2k
}
239
240
16
int reset_s3_rate_limiter(S3RateLimitType type, size_t max_speed, size_t max_burst, size_t limit) {
241
16
    if (type == S3RateLimitType::UNKNOWN) {
242
0
        return -1;
243
0
    }
244
16
    return S3ClientFactory::instance().rate_limiter(type)->reset(max_speed, max_burst, limit);
245
16
}
246
247
8
S3ClientFactory::S3ClientFactory() {
248
8
    _aws_options = Aws::SDKOptions {};
249
8
    auto logLevel = static_cast<Aws::Utils::Logging::LogLevel>(config::aws_log_level);
250
8
    _aws_options.loggingOptions.logLevel = logLevel;
251
8
    _aws_options.loggingOptions.logger_create_fn = [logLevel] {
252
8
        return std::make_shared<DorisAWSLogger>(logLevel);
253
8
    };
254
8
    Aws::InitAPI(_aws_options);
255
8
    _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
256
8
    _rate_limiters = {
257
8
            std::make_unique<S3RateLimiterHolder>(
258
8
                    config::s3_get_token_per_second, config::s3_get_bucket_tokens,
259
8
                    config::s3_get_token_limit,
260
8
                    metric_func_factory(get_rate_limit_ns, get_rate_limit_exceed_req_num)),
261
8
            std::make_unique<S3RateLimiterHolder>(
262
8
                    config::s3_put_token_per_second, config::s3_put_bucket_tokens,
263
8
                    config::s3_put_token_limit,
264
8
                    metric_func_factory(put_rate_limit_ns, put_rate_limit_exceed_req_num))};
265
266
8
#ifdef USE_AZURE
267
8
    auto azureLogLevel =
268
8
            static_cast<Azure::Core::Diagnostics::Logger::Level>(config::azure_log_level);
269
8
    Azure::Core::Diagnostics::Logger::SetLevel(azureLogLevel);
270
8
    Azure::Core::Diagnostics::Logger::SetListener(
271
8
            [&](Azure::Core::Diagnostics::Logger::Level level, const std::string& message) {
272
0
                switch (level) {
273
0
                case Azure::Core::Diagnostics::Logger::Level::Verbose:
274
0
                    LOG(INFO) << message;
275
0
                    break;
276
0
                case Azure::Core::Diagnostics::Logger::Level::Informational:
277
0
                    LOG(INFO) << message;
278
0
                    break;
279
0
                case Azure::Core::Diagnostics::Logger::Level::Warning:
280
0
                    LOG(WARNING) << message;
281
0
                    break;
282
0
                case Azure::Core::Diagnostics::Logger::Level::Error:
283
0
                    LOG(ERROR) << message;
284
0
                    break;
285
0
                default:
286
0
                    LOG(WARNING) << "Unknown level: " << static_cast<int>(level)
287
0
                                 << ", message: " << message;
288
0
                    break;
289
0
                }
290
0
            });
291
8
#endif
292
8
}
293
294
4
S3ClientFactory::~S3ClientFactory() {
295
4
    Aws::ShutdownAPI(_aws_options);
296
4
}
297
298
43.2k
S3ClientFactory& S3ClientFactory::instance() {
299
43.2k
    static S3ClientFactory ret;
300
43.2k
    return ret;
301
43.2k
}
302
303
43.2k
std::shared_ptr<io::ObjStorageClient> S3ClientFactory::create(const S3ClientConf& s3_conf) {
304
43.2k
    if (!is_s3_conf_valid(s3_conf).ok()) {
305
8
        return nullptr;
306
8
    }
307
308
43.2k
    check_s3_rate_limiter_config_changed();
309
310
#ifdef BE_TEST
311
    {
312
        std::lock_guard l(_lock);
313
        if (_test_client_creator) {
314
            return _test_client_creator(s3_conf);
315
        }
316
    }
317
#endif
318
319
43.2k
    {
320
43.2k
        uint64_t hash = s3_conf.get_hash();
321
43.2k
        std::lock_guard l(_lock);
322
43.2k
        auto it = _cache.find(hash);
323
43.2k
        if (it != _cache.end()) {
324
43.2k
            return it->second;
325
43.2k
        }
326
43.2k
    }
327
328
18.4E
    auto obj_client = (s3_conf.provider == io::ObjStorageType::AZURE)
329
18.4E
                              ? _create_azure_client(s3_conf)
330
18.4E
                              : _create_s3_client(s3_conf);
331
332
18.4E
    {
333
18.4E
        uint64_t hash = s3_conf.get_hash();
334
18.4E
        std::lock_guard l(_lock);
335
18.4E
        _cache[hash] = obj_client;
336
18.4E
    }
337
18.4E
    return obj_client;
338
43.2k
}
339
340
#ifdef BE_TEST
341
void S3ClientFactory::set_client_creator_for_test(
342
        std::function<std::shared_ptr<io::ObjStorageClient>(const S3ClientConf&)> creator) {
343
    std::lock_guard l(_lock);
344
    _test_client_creator = std::move(creator);
345
}
346
347
void S3ClientFactory::clear_client_creator_for_test() {
348
    std::lock_guard l(_lock);
349
    _test_client_creator = nullptr;
350
}
351
#endif
352
353
std::shared_ptr<io::ObjStorageClient> S3ClientFactory::_create_azure_client(
354
0
        const S3ClientConf& s3_conf) {
355
0
#ifdef USE_AZURE
356
0
    auto cred =
357
0
            std::make_shared<Azure::Storage::StorageSharedKeyCredential>(s3_conf.ak, s3_conf.sk);
358
359
0
    const std::string container_name = s3_conf.bucket;
360
0
    std::string uri = fmt::format("{}/{}", s3_conf.endpoint, container_name);
361
0
    if (s3_conf.endpoint.find("://") == std::string::npos) {
362
0
        uri = "https://" + uri;
363
0
    }
364
365
0
    Azure::Storage::Blobs::BlobClientOptions options;
366
0
    options.Retry.MaxRetries = config::max_s3_client_retry;
367
0
    options.PerRetryPolicies.emplace_back(std::make_unique<AzureRetryRecordPolicy>());
368
0
    if (_ca_cert_file_path.empty()) {
369
0
        _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
370
0
    }
371
0
    if (!_ca_cert_file_path.empty()) {
372
0
        Azure::Core::Http::CurlTransportOptions curl_options;
373
0
        curl_options.CAInfo = _ca_cert_file_path;
374
0
        options.Transport.Transport =
375
0
                std::make_shared<Azure::Core::Http::CurlTransport>(std::move(curl_options));
376
0
    }
377
378
0
    std::string normalized_uri = normalize_http_uri(uri);
379
0
    VLOG_DEBUG << "uri:" << uri << ", normalized_uri:" << normalized_uri;
380
0
    std::string tls_debug_context = build_azure_tls_debug_context(_ca_cert_file_path);
381
382
0
    auto containerClient = std::make_shared<Azure::Storage::Blobs::BlobContainerClient>(
383
0
            uri, cred, std::move(options));
384
0
    LOG_INFO("create one azure client with {}", s3_conf.to_string());
385
0
    return std::make_shared<io::AzureObjStorageClient>(std::move(containerClient),
386
0
                                                       std::move(tls_debug_context));
387
#else
388
    LOG_FATAL("BE is not compiled with azure support, export BUILD_AZURE=ON before building");
389
    return nullptr;
390
#endif
391
0
}
392
393
std::shared_ptr<Aws::Auth::AWSCredentialsProvider>
394
6
S3ClientFactory::_get_aws_credentials_provider_v1(const S3ClientConf& s3_conf) {
395
6
    if (!s3_conf.ak.empty() && !s3_conf.sk.empty()) {
396
2
        Aws::Auth::AWSCredentials aws_cred(s3_conf.ak, s3_conf.sk);
397
2
        DCHECK(!aws_cred.IsExpiredOrEmpty());
398
2
        if (!s3_conf.token.empty()) {
399
0
            aws_cred.SetSessionToken(s3_conf.token);
400
0
        }
401
2
        return std::make_shared<Aws::Auth::SimpleAWSCredentialsProvider>(std::move(aws_cred));
402
2
    }
403
404
4
    if (s3_conf.cred_provider_type == CredProviderType::InstanceProfile) {
405
2
        if (s3_conf.role_arn.empty()) {
406
1
            return std::make_shared<Aws::Auth::InstanceProfileCredentialsProvider>();
407
1
        }
408
409
1
        Aws::Client::ClientConfiguration clientConfiguration =
410
1
                S3ClientFactory::getClientConfiguration();
411
412
1
        if (_ca_cert_file_path.empty()) {
413
0
            _ca_cert_file_path =
414
0
                    get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
415
0
        }
416
1
        if (!_ca_cert_file_path.empty()) {
417
1
            clientConfiguration.caFile = _ca_cert_file_path;
418
1
        }
419
420
1
        auto stsClient = std::make_shared<Aws::STS::STSClient>(
421
1
                std::make_shared<Aws::Auth::InstanceProfileCredentialsProvider>(),
422
1
                clientConfiguration);
423
424
1
        return std::make_shared<Aws::Auth::STSAssumeRoleCredentialsProvider>(
425
1
                s3_conf.role_arn, Aws::String(), s3_conf.external_id,
426
1
                Aws::Auth::DEFAULT_CREDS_LOAD_FREQ_SECONDS, stsClient);
427
2
    }
428
429
    // Support anonymous access for public datasets when no credentials are provided
430
2
    if (s3_conf.ak.empty() && s3_conf.sk.empty()) {
431
2
        return std::make_shared<Aws::Auth::AnonymousAWSCredentialsProvider>();
432
2
    }
433
434
0
    return std::make_shared<Aws::Auth::DefaultAWSCredentialsProviderChain>();
435
2
}
436
437
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> S3ClientFactory::_create_credentials_provider(
438
22
        CredProviderType type) {
439
22
    switch (type) {
440
2
    case CredProviderType::Env:
441
2
        return std::make_shared<Aws::Auth::EnvironmentAWSCredentialsProvider>();
442
2
    case CredProviderType::SystemProperties:
443
2
        return std::make_shared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>();
444
3
    case CredProviderType::WebIdentity:
445
3
        return std::make_shared<Aws::Auth::STSAssumeRoleWebIdentityCredentialsProvider>();
446
2
    case CredProviderType::Container:
447
2
        return std::make_shared<Aws::Auth::TaskRoleCredentialsProvider>(
448
2
                Aws::Environment::GetEnv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI").c_str());
449
4
    case CredProviderType::InstanceProfile:
450
4
        return std::make_shared<Aws::Auth::InstanceProfileCredentialsProvider>();
451
4
    case CredProviderType::Anonymous:
452
4
        return std::make_shared<Aws::Auth::AnonymousAWSCredentialsProvider>();
453
2
    case CredProviderType::GcpWorkloadIdentity:
454
        // Anonymous credentials make the SDK's SigV4 signer a no-op; the
455
        // request-level `Authorization: Bearer` header (see
456
        // S3ObjStorageClient) authenticates against the GCS XML API instead.
457
2
        return std::make_shared<Aws::Auth::AnonymousAWSCredentialsProvider>();
458
3
    case CredProviderType::Default:
459
3
    default:
460
3
        return std::make_shared<CustomAwsCredentialsProviderChain>();
461
22
    }
462
22
}
463
464
std::shared_ptr<Aws::Auth::AWSCredentialsProvider>
465
97
S3ClientFactory::_get_aws_credentials_provider_v2(const S3ClientConf& s3_conf) {
466
97
    if (!s3_conf.ak.empty() && !s3_conf.sk.empty()) {
467
75
        Aws::Auth::AWSCredentials aws_cred(s3_conf.ak, s3_conf.sk);
468
75
        DCHECK(!aws_cred.IsExpiredOrEmpty());
469
75
        if (!s3_conf.token.empty()) {
470
11
            aws_cred.SetSessionToken(s3_conf.token);
471
11
        }
472
75
        return std::make_shared<Aws::Auth::SimpleAWSCredentialsProvider>(std::move(aws_cred));
473
75
    }
474
475
    // Handle role_arn for assume role scenario
476
22
    if (!s3_conf.role_arn.empty()) {
477
8
        Aws::Client::ClientConfiguration clientConfiguration =
478
8
                S3ClientFactory::getClientConfiguration();
479
480
8
        if (_ca_cert_file_path.empty()) {
481
0
            _ca_cert_file_path =
482
0
                    get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
483
0
        }
484
8
        if (!_ca_cert_file_path.empty()) {
485
8
            clientConfiguration.caFile = _ca_cert_file_path;
486
8
        }
487
488
8
        auto baseProvider = _create_credentials_provider(s3_conf.cred_provider_type);
489
8
        auto stsClient = std::make_shared<Aws::STS::STSClient>(baseProvider, clientConfiguration);
490
491
8
        return std::make_shared<Aws::Auth::STSAssumeRoleCredentialsProvider>(
492
8
                s3_conf.role_arn, Aws::String(), s3_conf.external_id,
493
8
                Aws::Auth::DEFAULT_CREDS_LOAD_FREQ_SECONDS, stsClient);
494
8
    }
495
496
    // Return provider based on cred_provider_type
497
14
    return _create_credentials_provider(s3_conf.cred_provider_type);
498
22
}
499
500
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> S3ClientFactory::get_aws_credentials_provider(
501
103
        const S3ClientConf& s3_conf) {
502
103
    if (config::aws_credentials_provider_version == "v2") {
503
97
        return _get_aws_credentials_provider_v2(s3_conf);
504
97
    }
505
6
    return _get_aws_credentials_provider_v1(s3_conf);
506
103
}
507
508
std::shared_ptr<io::ObjStorageClient> S3ClientFactory::_create_s3_client(
509
73
        const S3ClientConf& s3_conf) {
510
73
    TEST_SYNC_POINT_RETURN_WITH_VALUE(
511
73
            "s3_client_factory::create",
512
73
            std::make_shared<io::S3ObjStorageClient>(std::make_shared<Aws::S3::S3Client>()));
513
73
    Aws::Client::ClientConfiguration aws_config = S3ClientFactory::getClientConfiguration();
514
73
    if (s3_conf.need_override_endpoint) {
515
73
        aws_config.endpointOverride = s3_conf.endpoint;
516
73
    }
517
73
    aws_config.region = s3_conf.region;
518
519
73
    if (_ca_cert_file_path.empty()) {
520
0
        _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
521
0
    }
522
523
73
    if (!_ca_cert_file_path.empty()) {
524
73
        aws_config.caFile = _ca_cert_file_path;
525
73
    }
526
527
73
    if (s3_conf.max_connections > 0) {
528
71
        aws_config.maxConnections = s3_conf.max_connections;
529
71
    } else {
530
2
        aws_config.maxConnections = 102400;
531
2
    }
532
533
73
    aws_config.requestTimeoutMs = 30000;
534
73
    if (s3_conf.request_timeout_ms > 0) {
535
71
        aws_config.requestTimeoutMs = s3_conf.request_timeout_ms;
536
71
    }
537
538
73
    if (s3_conf.connect_timeout_ms > 0) {
539
71
        aws_config.connectTimeoutMs = s3_conf.connect_timeout_ms;
540
71
    }
541
542
73
    if (config::s3_client_http_scheme == "http") {
543
73
        aws_config.scheme = Aws::Http::Scheme::HTTP;
544
73
    }
545
73
    if (s3_conf.cred_provider_type == CredProviderType::GcpWorkloadIdentity) {
546
0
        aws_config.scheme = Aws::Http::Scheme::HTTPS;
547
0
    }
548
549
73
    aws_config.retryStrategy = std::make_shared<S3CustomRetryStrategy>(
550
73
            config::max_s3_client_retry /*scaleFactor = 25*/, /*retry_slow_down=*/false);
551
552
73
    std::shared_ptr<Aws::S3::S3Client> new_client = std::make_shared<Aws::S3::S3Client>(
553
73
            get_aws_credentials_provider(s3_conf), std::move(aws_config),
554
73
            Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never,
555
73
            s3_conf.use_virtual_addressing);
556
557
73
    std::shared_ptr<GcpWorkloadIdentityTokenProvider> bearer_token_provider;
558
73
    if (s3_conf.cred_provider_type == CredProviderType::GcpWorkloadIdentity) {
559
0
        bearer_token_provider = global_gcp_workload_identity_token_provider();
560
0
    }
561
73
    auto obj_client = std::make_shared<io::S3ObjStorageClient>(std::move(new_client),
562
73
                                                               std::move(bearer_token_provider));
563
73
    LOG_INFO("create one s3 client with {}", s3_conf.to_string());
564
73
    return obj_client;
565
73
}
566
567
Status S3ClientFactory::convert_properties_to_s3_conf(
568
42.6k
        const std::map<std::string, std::string>& prop, const S3URI& s3_uri, S3Conf* s3_conf) {
569
42.6k
    StringCaseMap<std::string> properties(prop.begin(), prop.end());
570
42.7k
    if (auto it = properties.find(S3_AK); it != properties.end()) {
571
42.7k
        s3_conf->client_conf.ak = it->second;
572
42.7k
    }
573
42.7k
    if (auto it = properties.find(S3_SK); it != properties.end()) {
574
42.7k
        s3_conf->client_conf.sk = it->second;
575
42.7k
    }
576
42.6k
    if (auto it = properties.find(S3_TOKEN); it != properties.end()) {
577
90
        s3_conf->client_conf.token = it->second;
578
90
    }
579
42.7k
    if (auto it = properties.find(S3_ENDPOINT); it != properties.end()) {
580
42.7k
        s3_conf->client_conf.endpoint = it->second;
581
42.7k
    }
582
42.6k
    if (auto it = properties.find(S3_NEED_OVERRIDE_ENDPOINT); it != properties.end()) {
583
0
        s3_conf->client_conf.need_override_endpoint = (it->second == "true");
584
0
    }
585
42.7k
    if (auto it = properties.find(S3_REGION); it != properties.end()) {
586
42.7k
        s3_conf->client_conf.region = it->second;
587
42.7k
    }
588
42.7k
    if (auto it = properties.find(S3_MAX_CONN_SIZE); it != properties.end()) {
589
42.7k
        if (!to_int(it->second, s3_conf->client_conf.max_connections)) {
590
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_MAX_CONN_SIZE, it->second);
591
0
        }
592
42.7k
    }
593
42.7k
    if (auto it = properties.find(S3_REQUEST_TIMEOUT_MS); it != properties.end()) {
594
42.7k
        if (!to_int(it->second, s3_conf->client_conf.request_timeout_ms)) {
595
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_REQUEST_TIMEOUT_MS,
596
0
                                           it->second);
597
0
        }
598
42.7k
    }
599
42.6k
    if (auto it = properties.find(S3_CONN_TIMEOUT_MS); it != properties.end()) {
600
42.6k
        if (!to_int(it->second, s3_conf->client_conf.connect_timeout_ms)) {
601
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_CONN_TIMEOUT_MS,
602
0
                                           it->second);
603
0
        }
604
42.6k
    }
605
42.6k
    if (auto it = properties.find(S3_PROVIDER); it != properties.end()) {
606
        // S3 Provider properties should be case insensitive.
607
0
        if (0 == strcasecmp(it->second.c_str(), AZURE_PROVIDER_STRING)) {
608
0
            s3_conf->client_conf.provider = io::ObjStorageType::AZURE;
609
0
        }
610
0
    }
611
612
42.6k
    if (s3_uri.get_bucket().empty()) {
613
0
        return Status::InvalidArgument("Invalid S3 URI {}, bucket is not specified",
614
0
                                       s3_uri.to_string());
615
0
    }
616
42.6k
    s3_conf->bucket = s3_uri.get_bucket();
617
    // For azure's compatibility
618
42.6k
    s3_conf->client_conf.bucket = s3_uri.get_bucket();
619
42.6k
    s3_conf->prefix = "";
620
621
    // See https://sdk.amazonaws.com/cpp/api/LATEST/class_aws_1_1_s3_1_1_s3_client.html
622
42.6k
    s3_conf->client_conf.use_virtual_addressing = true;
623
42.7k
    if (auto it = properties.find(USE_PATH_STYLE); it != properties.end()) {
624
42.7k
        s3_conf->client_conf.use_virtual_addressing = it->second != "true";
625
42.7k
    }
626
627
42.6k
    if (auto it = properties.find(S3_ROLE_ARN); it != properties.end()) {
628
        // Keep provider type as Default unless explicitly configured by
629
        // AWS_CREDENTIALS_PROVIDER_TYPE, consistent with FE behavior.
630
5
        s3_conf->client_conf.role_arn = it->second;
631
5
    }
632
633
42.6k
    if (auto it = properties.find(S3_EXTERNAL_ID); it != properties.end()) {
634
0
        s3_conf->client_conf.external_id = it->second;
635
0
    }
636
637
42.6k
    if (auto it = properties.find(S3_CREDENTIALS_PROVIDER_TYPE); it != properties.end()) {
638
142
        s3_conf->client_conf.cred_provider_type = cred_provider_type_from_string(it->second);
639
142
    }
640
641
42.6k
    if (auto st = is_s3_conf_valid(s3_conf->client_conf); !st.ok()) {
642
2
        return st;
643
2
    }
644
42.6k
    return Status::OK();
645
42.6k
}
646
647
0
static CredProviderType cred_provider_type_from_thrift(TCredProviderType::type cred_provider_type) {
648
0
    switch (cred_provider_type) {
649
0
    case TCredProviderType::DEFAULT:
650
0
        return CredProviderType::Default;
651
0
    case TCredProviderType::SIMPLE:
652
0
        return CredProviderType::Simple;
653
0
    case TCredProviderType::INSTANCE_PROFILE:
654
0
        return CredProviderType::InstanceProfile;
655
0
    case TCredProviderType::ENV:
656
0
        return CredProviderType::Env;
657
0
    case TCredProviderType::SYSTEM_PROPERTIES:
658
0
        return CredProviderType::SystemProperties;
659
0
    case TCredProviderType::WEB_IDENTITY:
660
0
        return CredProviderType::WebIdentity;
661
0
    case TCredProviderType::CONTAINER:
662
0
        return CredProviderType::Container;
663
0
    case TCredProviderType::ANONYMOUS:
664
0
        return CredProviderType::Anonymous;
665
0
    default:
666
0
        __builtin_unreachable();
667
0
        LOG(WARNING) << "Invalid TCredProviderType value: " << cred_provider_type
668
0
                     << ", use default instead.";
669
0
        return CredProviderType::Default;
670
0
    }
671
0
}
672
673
128
S3Conf S3Conf::get_s3_conf(const cloud::ObjectStoreInfoPB& info) {
674
128
    S3Conf ret {
675
128
            .bucket = info.bucket(),
676
128
            .prefix = info.prefix(),
677
128
            .client_conf {
678
128
                    .endpoint = info.endpoint(),
679
128
                    .region = info.region(),
680
128
                    .ak = info.ak(),
681
128
                    .sk = info.sk(),
682
128
                    .token {},
683
128
                    .bucket = info.bucket(),
684
128
                    .provider = io::ObjStorageType::AWS,
685
128
                    .use_virtual_addressing =
686
128
                            info.has_use_path_style() ? !info.use_path_style() : true,
687
688
128
                    .role_arn = info.role_arn(),
689
128
                    .external_id = info.external_id(),
690
128
            },
691
128
            .sse_enabled = info.sse_enabled(),
692
128
    };
693
694
128
    if (info.has_cred_provider_type()) {
695
0
        ret.client_conf.cred_provider_type = cred_provider_type_from_pb(info.cred_provider_type());
696
0
    }
697
698
128
    io::ObjStorageType type = io::ObjStorageType::AWS;
699
128
    switch (info.provider()) {
700
128
    case cloud::ObjectStoreInfoPB_Provider_OSS:
701
128
        type = io::ObjStorageType::OSS;
702
128
        break;
703
0
    case cloud::ObjectStoreInfoPB_Provider_S3:
704
0
        type = io::ObjStorageType::AWS;
705
0
        break;
706
0
    case cloud::ObjectStoreInfoPB_Provider_COS:
707
0
        type = io::ObjStorageType::COS;
708
0
        break;
709
0
    case cloud::ObjectStoreInfoPB_Provider_OBS:
710
0
        type = io::ObjStorageType::OBS;
711
0
        break;
712
0
    case cloud::ObjectStoreInfoPB_Provider_BOS:
713
0
        type = io::ObjStorageType::BOS;
714
0
        break;
715
0
    case cloud::ObjectStoreInfoPB_Provider_GCP:
716
0
        type = io::ObjStorageType::GCP;
717
0
        break;
718
0
    case cloud::ObjectStoreInfoPB_Provider_AZURE:
719
0
        type = io::ObjStorageType::AZURE;
720
0
        break;
721
0
    case cloud::ObjectStoreInfoPB_Provider_TOS:
722
0
        type = io::ObjStorageType::TOS;
723
0
        break;
724
0
    default:
725
0
        __builtin_unreachable();
726
0
        LOG_FATAL("unknown provider type {}, info {}", info.provider(), ret.to_string());
727
128
    }
728
128
    ret.client_conf.provider = type;
729
128
    return ret;
730
128
}
731
732
34
S3Conf S3Conf::get_s3_conf(const TS3StorageParam& param) {
733
34
    S3Conf ret {
734
34
            .bucket = param.bucket,
735
34
            .prefix = param.root_path,
736
34
            .client_conf = {
737
34
                    .endpoint = param.endpoint,
738
34
                    .region = param.region,
739
34
                    .ak = param.ak,
740
34
                    .sk = param.sk,
741
34
                    .token = param.token,
742
34
                    .bucket = param.bucket,
743
34
                    .provider = io::ObjStorageType::AWS,
744
34
                    .max_connections = param.max_conn,
745
34
                    .request_timeout_ms = param.request_timeout_ms,
746
34
                    .connect_timeout_ms = param.conn_timeout_ms,
747
                    // When using cold heat separation in minio, user might use ip address directly,
748
                    // which needs enable use_virtual_addressing to true
749
34
                    .use_virtual_addressing = !param.use_path_style,
750
34
                    .role_arn = param.role_arn,
751
34
                    .external_id = param.external_id,
752
34
            }};
753
754
34
    if (param.__isset.cred_provider_type) {
755
0
        ret.client_conf.cred_provider_type =
756
0
                cred_provider_type_from_thrift(param.cred_provider_type);
757
0
    }
758
759
34
    io::ObjStorageType type = io::ObjStorageType::AWS;
760
34
    switch (param.provider) {
761
34
    case TObjStorageType::UNKNOWN:
762
34
        LOG_INFO("Receive one legal storage resource, set provider type to aws, param detail {}",
763
34
                 ret.to_string());
764
34
        type = io::ObjStorageType::AWS;
765
34
        break;
766
0
    case TObjStorageType::AWS:
767
0
        type = io::ObjStorageType::AWS;
768
0
        break;
769
0
    case TObjStorageType::AZURE:
770
0
        type = io::ObjStorageType::AZURE;
771
0
        break;
772
0
    case TObjStorageType::BOS:
773
0
        type = io::ObjStorageType::BOS;
774
0
        break;
775
0
    case TObjStorageType::COS:
776
0
        type = io::ObjStorageType::COS;
777
0
        break;
778
0
    case TObjStorageType::OBS:
779
0
        type = io::ObjStorageType::OBS;
780
0
        break;
781
0
    case TObjStorageType::OSS:
782
0
        type = io::ObjStorageType::OSS;
783
0
        break;
784
0
    case TObjStorageType::GCP:
785
0
        type = io::ObjStorageType::GCP;
786
0
        break;
787
0
    case TObjStorageType::TOS:
788
0
        type = io::ObjStorageType::TOS;
789
0
        break;
790
0
    default:
791
0
        LOG_FATAL("unknown provider type {}, info {}", param.provider, ret.to_string());
792
0
        __builtin_unreachable();
793
34
    }
794
34
    ret.client_conf.provider = type;
795
34
    return ret;
796
34
}
797
798
258
std::string hide_access_key(const std::string& ak) {
799
258
    std::string key = ak;
800
258
    size_t key_len = key.length();
801
258
    size_t reserved_count;
802
258
    if (key_len > 7) {
803
76
        reserved_count = 6;
804
182
    } else if (key_len > 2) {
805
158
        reserved_count = key_len - 2;
806
158
    } else {
807
24
        reserved_count = 0;
808
24
    }
809
810
258
    size_t x_count = key_len - reserved_count;
811
258
    size_t left_x_count = (x_count + 1) / 2;
812
813
258
    if (left_x_count > 0) {
814
238
        key.replace(0, left_x_count, left_x_count, 'x');
815
238
    }
816
817
258
    if (x_count - left_x_count > 0) {
818
237
        key.replace(key_len - (x_count - left_x_count), x_count - left_x_count,
819
237
                    x_count - left_x_count, 'x');
820
237
    }
821
258
    return key;
822
258
}
823
824
} // end namespace doris