Coverage Report

Created: 2026-01-22 21:38

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