Coverage Report

Created: 2026-03-15 23:42

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