Coverage Report

Created: 2026-07-23 11:19

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