Coverage Report

Created: 2026-07-17 16:56

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