Coverage Report

Created: 2026-08-16 02:07

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/client/DefaultRetryStrategy.h>
24
#include <aws/core/utils/logging/LogLevel.h>
25
#include <aws/core/utils/logging/LogSystemInterface.h>
26
#include <aws/core/utils/memory/stl/AWSStringStream.h>
27
#include <aws/s3/S3Client.h>
28
29
#include "util/string_util.h"
30
31
#ifdef USE_AZURE
32
#include <azure/core/diagnostics/logger.hpp>
33
#include <azure/core/http/curl_transport.hpp>
34
#include <azure/storage/blobs/blob_container_client.hpp>
35
#endif
36
#include <cstdlib>
37
#include <filesystem>
38
#include <fstream>
39
#include <functional>
40
#include <memory>
41
#include <ostream>
42
#include <utility>
43
44
#include "common/config.h"
45
#include "common/logging.h"
46
#include "common/status.h"
47
#include "cpp/obj-client/auth/aws_credential_factory.h"
48
#ifdef USE_AZURE
49
#include "cpp/obj-client/auth/azure_auth_factory.h"
50
#include "cpp/obj-client/azure_obj_storage_client.h"
51
#endif
52
#include "cloud/config.h"
53
#include "cpp/aws_logger.h"
54
#include "cpp/obj-client/rate_limited_obj_storage_client.h"
55
#include "cpp/obj-client/s3_obj_storage_client.h"
56
#include "cpp/obj_retry_strategy.h"
57
#include "cpp/sync_point.h"
58
#include "cpp/util.h"
59
#include "exec/scan/scanner_scheduler.h"
60
#include "runtime/exec_env.h"
61
#include "util/s3_rate_limiter_manager.h"
62
#include "util/s3_uri.h"
63
64
namespace doris {
65
namespace {
66
67
37
doris::Status is_s3_conf_valid(const S3ClientConf& conf) {
68
37
    if (conf.endpoint.empty()) {
69
0
        return Status::InvalidArgument<false>("Invalid s3 conf, empty endpoint");
70
0
    }
71
37
    if (conf.region.empty()) {
72
0
        return Status::InvalidArgument<false>("Invalid s3 conf, empty region");
73
0
    }
74
75
37
    if (conf.role_arn.empty()) {
76
        // Allow anonymous access when both ak and sk are empty
77
31
        bool hasAk = !conf.ak.empty();
78
31
        bool hasSk = !conf.sk.empty();
79
80
        // Either both credentials are provided or both are empty (anonymous access)
81
31
        if (hasAk && conf.sk.empty()) {
82
1
            return Status::InvalidArgument<false>("Invalid s3 conf, empty sk");
83
1
        }
84
30
        if (hasSk && conf.ak.empty()) {
85
1
            return Status::InvalidArgument<false>("Invalid s3 conf, empty ak");
86
1
        }
87
30
    }
88
35
    return Status::OK();
89
37
}
90
91
ObjStorageResponse make_be_rate_limit_response(S3RateLimitType type,
92
3
                                               S3RateLimitRejectReason reason) {
93
3
    const auto* limit_type = reason == S3RateLimitRejectReason::QPS ? "QPS" : "bytes";
94
    // A local admission rejection is not an S3 HTTP 429. Keep the merged #65420 behavior so S3
95
    // readers do not retry it as provider throttling.
96
3
    return ObjStorageResponse::rate_limit(
97
3
            ErrorCode::EXCEEDED_LIMIT, 0,
98
3
            fmt::format("s3 {} request exceeds {} limit, rejected by BE rate limiter",
99
3
                        to_string(type), limit_type));
100
3
}
101
102
class BeObjStorageRateLimitPolicy final : public ObjStorageRateLimitPolicy {
103
public:
104
36
    ObjStorageAdmission acquire(S3RateLimitType type, size_t estimated_bytes) const override {
105
36
        auto guard = std::make_shared<S3RateLimitGuard>(type, estimated_bytes);
106
36
        if (!guard->ok()) {
107
3
            return ObjStorageAdmission {
108
3
                    .resp = make_be_rate_limit_response(type, guard->reject_reason()),
109
3
            };
110
3
        }
111
33
        return ObjStorageAdmission {
112
33
                .settle = [guard = std::move(guard)](
113
33
                                  size_t actual_bytes) { guard->settle(actual_bytes); },
114
33
        };
115
36
    }
116
};
117
118
// Return true is convert `str` to int successfully
119
0
bool to_int(std::string_view str, int& res) {
120
0
    auto [_, ec] = std::from_chars(str.data(), str.data() + str.size(), res);
121
0
    return ec == std::errc {};
122
0
}
123
124
#ifdef USE_AZURE
125
0
std::string env_or_empty(const char* env_name) {
126
0
    if (const char* value = std::getenv(env_name); value != nullptr) {
127
0
        return value;
128
0
    }
129
0
    return "";
130
0
}
131
132
0
std::string build_azure_tls_debug_context(const std::string& selected_ca_file) {
133
0
    bool selected_ca_exists = false;
134
0
    bool selected_ca_readable = false;
135
0
    if (!selected_ca_file.empty()) {
136
0
        std::error_code ec;
137
0
        selected_ca_exists = std::filesystem::exists(selected_ca_file, ec) && !ec;
138
0
        std::ifstream input(selected_ca_file);
139
0
        selected_ca_readable = input.good();
140
0
    }
141
142
0
    return fmt::format(
143
0
            "tls_debug(ca_cert_file_paths='{}', selected_ca_file='{}', selected_ca_exists={}, "
144
0
            "selected_ca_readable={}, SSL_CERT_FILE='{}', CURL_CA_BUNDLE='{}', SSL_CERT_DIR='{}')",
145
0
            config::ca_cert_file_paths, selected_ca_file, selected_ca_exists, selected_ca_readable,
146
0
            env_or_empty("SSL_CERT_FILE"), env_or_empty("CURL_CA_BUNDLE"),
147
0
            env_or_empty("SSL_CERT_DIR"));
148
0
}
149
#endif
150
151
constexpr char USE_PATH_STYLE[] = "use_path_style";
152
153
constexpr char AZURE_PROVIDER_STRING[] = "AZURE";
154
constexpr char S3_PROVIDER[] = "provider";
155
constexpr char S3_AK[] = "AWS_ACCESS_KEY";
156
constexpr char S3_SK[] = "AWS_SECRET_KEY";
157
constexpr char S3_ENDPOINT[] = "AWS_ENDPOINT";
158
constexpr char S3_REGION[] = "AWS_REGION";
159
constexpr char S3_TOKEN[] = "AWS_TOKEN";
160
constexpr char S3_MAX_CONN_SIZE[] = "AWS_MAX_CONNECTIONS";
161
constexpr char S3_REQUEST_TIMEOUT_MS[] = "AWS_REQUEST_TIMEOUT_MS";
162
constexpr char S3_CONN_TIMEOUT_MS[] = "AWS_CONNECTION_TIMEOUT_MS";
163
constexpr char S3_NEED_OVERRIDE_ENDPOINT[] = "AWS_NEED_OVERRIDE_ENDPOINT";
164
165
constexpr char S3_ROLE_ARN[] = "AWS_ROLE_ARN";
166
constexpr char S3_EXTERNAL_ID[] = "AWS_EXTERNAL_ID";
167
constexpr char S3_CREDENTIALS_PROVIDER_TYPE[] = "AWS_CREDENTIALS_PROVIDER_TYPE";
168
} // namespace
169
170
1
S3ClientFactory::S3ClientFactory() {
171
1
    _aws_options = Aws::SDKOptions {};
172
1
    auto logLevel = static_cast<Aws::Utils::Logging::LogLevel>(config::aws_log_level);
173
1
    _aws_options.loggingOptions.logLevel = logLevel;
174
1
    _aws_options.loggingOptions.logger_create_fn = [logLevel] {
175
1
        return std::make_shared<DorisAWSLogger>(logLevel);
176
1
    };
177
1
    Aws::InitAPI(_aws_options);
178
1
    _get_ca_cert_file_path();
179
180
1
#ifdef USE_AZURE
181
1
    auto azureLogLevel =
182
1
            static_cast<Azure::Core::Diagnostics::Logger::Level>(config::azure_log_level);
183
1
    Azure::Core::Diagnostics::Logger::SetLevel(azureLogLevel);
184
1
    Azure::Core::Diagnostics::Logger::SetListener(
185
1
            [&](Azure::Core::Diagnostics::Logger::Level level, const std::string& message) {
186
0
                switch (level) {
187
0
                case Azure::Core::Diagnostics::Logger::Level::Verbose:
188
0
                    LOG(INFO) << message;
189
0
                    break;
190
0
                case Azure::Core::Diagnostics::Logger::Level::Informational:
191
0
                    LOG(INFO) << message;
192
0
                    break;
193
0
                case Azure::Core::Diagnostics::Logger::Level::Warning:
194
0
                    LOG(WARNING) << message;
195
0
                    break;
196
0
                case Azure::Core::Diagnostics::Logger::Level::Error:
197
0
                    LOG(ERROR) << message;
198
0
                    break;
199
0
                default:
200
0
                    LOG(WARNING) << "Unknown level: " << static_cast<int>(level)
201
0
                                 << ", message: " << message;
202
0
                    break;
203
0
                }
204
0
            });
205
1
#endif
206
1
}
207
208
1
S3ClientFactory::~S3ClientFactory() {
209
1
    Aws::ShutdownAPI(_aws_options);
210
1
}
211
212
50
S3ClientFactory& S3ClientFactory::instance() {
213
50
    static S3ClientFactory ret;
214
50
    return ret;
215
50
}
216
217
22
Result<std::shared_ptr<io::ObjStorageClient>> S3ClientFactory::create(const S3ClientConf& s3_conf) {
218
22
    RETURN_IF_ERROR_RESULT(is_s3_conf_valid(s3_conf));
219
220
22
#ifdef BE_TEST
221
22
    {
222
22
        std::lock_guard l(_lock);
223
22
        if (_test_client_creator) {
224
4
            return _test_client_creator(s3_conf);
225
4
        }
226
22
    }
227
18
#endif
228
229
18
    {
230
18
        std::lock_guard l(_lock);
231
18
        auto it = _cache.find(s3_conf);
232
18
        if (it != _cache.end()) {
233
9
            return it->second;
234
9
        }
235
18
    }
236
237
9
    auto client_result = (s3_conf.provider == io::ObjStorageProvider::AZURE)
238
9
                                 ? _create_azure_client(s3_conf)
239
9
                                 : _create_s3_client(s3_conf);
240
9
    if (!client_result.has_value()) {
241
0
        return ResultError(std::move(client_result).error());
242
0
    }
243
9
    auto obj_client = std::move(client_result).value();
244
9
    if (!config::is_cloud_mode() || s3_conf.is_internal_bucket) {
245
8
        obj_client = std::make_shared<io::RateLimitedObjStorageClient>(
246
8
                std::move(obj_client), std::make_shared<BeObjStorageRateLimitPolicy>());
247
8
    }
248
249
9
    {
250
9
        std::lock_guard l(_lock);
251
9
        auto [it, _] = _cache.emplace(s3_conf, std::move(obj_client));
252
9
        return it->second;
253
9
    }
254
9
}
255
256
#ifdef BE_TEST
257
void S3ClientFactory::set_client_creator_for_test(
258
3
        std::function<std::shared_ptr<io::ObjStorageClient>(const S3ClientConf&)> creator) {
259
3
    std::lock_guard l(_lock);
260
3
    _test_client_creator = std::move(creator);
261
3
}
262
263
18
void S3ClientFactory::clear_client_creator_for_test() {
264
18
    std::lock_guard l(_lock);
265
18
    _test_client_creator = nullptr;
266
18
}
267
#endif
268
269
Result<std::shared_ptr<io::ObjStorageClient>> S3ClientFactory::_create_azure_client(
270
0
        const S3ClientConf& s3_conf) {
271
0
#ifdef USE_AZURE
272
0
    const std::string container_name = s3_conf.bucket;
273
0
    std::string uri = fmt::format("{}/{}", s3_conf.endpoint, container_name);
274
0
    if (s3_conf.endpoint.find("://") == std::string::npos) {
275
0
        uri = "https://" + uri;
276
0
    }
277
278
0
    Azure::Storage::Blobs::BlobClientOptions options;
279
0
    options.Retry.StatusCodes.insert(Azure::Core::Http::HttpStatusCode::TooManyRequests);
280
0
    options.Retry.MaxRetries = config::max_s3_client_retry;
281
0
    options.PerRetryPolicies.emplace_back(std::make_unique<AzureRetryRecordPolicy>());
282
0
    auto ca_cert_file_path = _get_ca_cert_file_path();
283
0
    if (!ca_cert_file_path.empty()) {
284
0
        Azure::Core::Http::CurlTransportOptions curl_options;
285
0
        curl_options.CAInfo = ca_cert_file_path;
286
0
        options.Transport.Transport =
287
0
                std::make_shared<Azure::Core::Http::CurlTransport>(std::move(curl_options));
288
0
    }
289
290
0
    std::string normalized_uri = normalize_http_uri(uri);
291
0
    VLOG_DEBUG << "uri:" << uri << ", normalized_uri:" << normalized_uri;
292
0
    std::string tls_debug_context = build_azure_tls_debug_context(ca_cert_file_path);
293
294
0
    auto built = AzureAuthFactory::create(uri,
295
0
                                          {
296
0
                                                  .type = AzureCredentialType::SHARED_KEY,
297
0
                                                  .account_name = s3_conf.ak,
298
0
                                                  .account_key = s3_conf.sk,
299
0
                                          },
300
0
                                          std::move(options));
301
0
    if (!built) {
302
0
        return ResultError(
303
0
                Status::InvalidArgument("failed to create Azure client: {}", built.error));
304
0
    }
305
0
    LOG_INFO("create one azure client with {}", s3_conf.to_string());
306
0
    return std::make_shared<io::AzureObjStorageClient>(
307
0
            std::move(built.container_client),
308
0
            ObjStorageEndpointInfo {
309
0
                    .endpoint = s3_conf.endpoint,
310
0
                    .ak = s3_conf.ak,
311
0
                    .sk = s3_conf.sk,
312
0
                    .tls_debug_context = std::move(tls_debug_context),
313
0
            },
314
0
            std::move(built.shared_key_credential));
315
#else
316
    return ResultError(Status::NotSupported(
317
            "BE is not compiled with azure support, export BUILD_AZURE=ON before building"));
318
#endif
319
0
}
320
321
41
std::string S3ClientFactory::_get_ca_cert_file_path() {
322
41
    std::lock_guard lock(_ca_cert_lock);
323
41
    if (_ca_cert_file_path.empty()) {
324
3
        _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
325
3
    }
326
41
    return _ca_cert_file_path;
327
41
}
328
329
36
AwsCredentialResult S3ClientFactory::create_aws_credentials_provider(const S3ClientConf& s3_conf) {
330
36
    auto sts_config = S3ClientFactory::getClientConfiguration();
331
36
    auto ca_cert_file_path = _get_ca_cert_file_path();
332
36
    if (!ca_cert_file_path.empty()) {
333
35
        sts_config.caFile = ca_cert_file_path;
334
35
    }
335
36
    return AwsCredentialFactory::create({
336
36
            .version = config::aws_credentials_provider_version == "v2"
337
36
                               ? AwsCredentialProviderVersion::V2
338
36
                               : AwsCredentialProviderVersion::V1,
339
36
            .access_key = s3_conf.ak,
340
36
            .secret_key = s3_conf.sk,
341
36
            .session_token = s3_conf.token,
342
36
            .provider_type = s3_conf.cred_provider_type,
343
36
            .role_arn = s3_conf.role_arn,
344
36
            .external_id = s3_conf.external_id,
345
36
            .empty_credentials = EmptyCredentialsBehavior::ANONYMOUS,
346
36
            .sts_client_config = std::move(sts_config),
347
36
    });
348
36
}
349
350
Result<std::shared_ptr<io::ObjStorageClient>> S3ClientFactory::_create_s3_client(
351
9
        const S3ClientConf& s3_conf) {
352
9
    TEST_SYNC_POINT_RETURN_WITH_VALUE(
353
4
            "s3_client_factory::create",
354
4
            std::make_shared<io::S3ObjStorageClient>(std::make_shared<Aws::S3::S3Client>(),
355
4
                                                     ObjStorageEndpointInfo {}));
356
4
    Aws::Client::ClientConfiguration aws_config = S3ClientFactory::getClientConfiguration();
357
4
    if (s3_conf.need_override_endpoint) {
358
4
        aws_config.endpointOverride = s3_conf.endpoint;
359
4
    }
360
4
    aws_config.region = s3_conf.region;
361
362
4
    auto ca_cert_file_path = _get_ca_cert_file_path();
363
4
    if (!ca_cert_file_path.empty()) {
364
4
        aws_config.caFile = ca_cert_file_path;
365
4
    }
366
367
4
    if (s3_conf.max_connections > 0) {
368
0
        aws_config.maxConnections = s3_conf.max_connections;
369
4
    } else {
370
4
        aws_config.maxConnections = 102400;
371
4
    }
372
373
4
    aws_config.requestTimeoutMs = 30000;
374
4
    if (s3_conf.request_timeout_ms > 0) {
375
0
        aws_config.requestTimeoutMs = s3_conf.request_timeout_ms;
376
0
    }
377
378
4
    if (s3_conf.connect_timeout_ms > 0) {
379
0
        aws_config.connectTimeoutMs = s3_conf.connect_timeout_ms;
380
0
    }
381
382
4
    set_s3_client_default_http_scheme(aws_config, config::s3_client_http_scheme);
383
384
4
    aws_config.retryStrategy = std::make_shared<S3CustomRetryStrategy>(
385
4
            config::max_s3_client_retry /*scaleFactor = 25*/, /*retry_slow_down=*/true);
386
387
4
    auto credentials = create_aws_credentials_provider(s3_conf);
388
4
    if (!credentials) {
389
0
        return ResultError(Status::InvalidArgument("failed to create AWS credential provider: {}",
390
0
                                                   credentials.error));
391
0
    }
392
4
    std::shared_ptr<Aws::S3::S3Client> new_client = std::make_shared<Aws::S3::S3Client>(
393
4
            std::move(credentials.provider), std::move(aws_config),
394
4
            Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never,
395
4
            s3_conf.use_virtual_addressing);
396
397
4
    auto provider_client = std::make_shared<io::S3ObjStorageClient>(
398
4
            std::move(new_client), ObjStorageEndpointInfo {
399
4
                                           .endpoint = s3_conf.endpoint,
400
4
                                           .ak = s3_conf.ak,
401
4
                                           .sk = s3_conf.sk,
402
4
                                   });
403
4
    LOG_INFO("create one s3 client with {}", s3_conf.to_string());
404
4
    return provider_client;
405
4
}
406
407
Status S3ClientFactory::convert_properties_to_s3_conf(
408
15
        const std::map<std::string, std::string>& prop, const S3URI& s3_uri, S3Conf* s3_conf) {
409
15
    StringCaseMap<std::string> properties(prop.begin(), prop.end());
410
15
    if (auto it = properties.find(S3_AK); it != properties.end()) {
411
2
        s3_conf->client_conf.ak = it->second;
412
2
    }
413
15
    if (auto it = properties.find(S3_SK); it != properties.end()) {
414
2
        s3_conf->client_conf.sk = it->second;
415
2
    }
416
15
    if (auto it = properties.find(S3_TOKEN); it != properties.end()) {
417
0
        s3_conf->client_conf.token = it->second;
418
0
    }
419
15
    if (auto it = properties.find(S3_ENDPOINT); it != properties.end()) {
420
15
        s3_conf->client_conf.endpoint = it->second;
421
15
    }
422
15
    if (auto it = properties.find(S3_NEED_OVERRIDE_ENDPOINT); it != properties.end()) {
423
0
        s3_conf->client_conf.need_override_endpoint = (it->second == "true");
424
0
    }
425
15
    if (auto it = properties.find(S3_REGION); it != properties.end()) {
426
15
        s3_conf->client_conf.region = it->second;
427
15
    }
428
15
    if (auto it = properties.find(S3_MAX_CONN_SIZE); it != properties.end()) {
429
0
        if (!to_int(it->second, s3_conf->client_conf.max_connections)) {
430
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_MAX_CONN_SIZE, it->second);
431
0
        }
432
0
    }
433
15
    if (auto it = properties.find(S3_REQUEST_TIMEOUT_MS); it != properties.end()) {
434
0
        if (!to_int(it->second, s3_conf->client_conf.request_timeout_ms)) {
435
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_REQUEST_TIMEOUT_MS,
436
0
                                           it->second);
437
0
        }
438
0
    }
439
15
    if (auto it = properties.find(S3_CONN_TIMEOUT_MS); it != properties.end()) {
440
0
        if (!to_int(it->second, s3_conf->client_conf.connect_timeout_ms)) {
441
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_CONN_TIMEOUT_MS,
442
0
                                           it->second);
443
0
        }
444
0
    }
445
15
    if (auto it = properties.find(S3_PROVIDER); it != properties.end()) {
446
        // S3 Provider properties should be case insensitive.
447
0
        if (0 == strcasecmp(it->second.c_str(), AZURE_PROVIDER_STRING)) {
448
0
            s3_conf->client_conf.provider = io::ObjStorageProvider::AZURE;
449
0
        }
450
0
    }
451
452
15
    if (s3_uri.get_bucket().empty()) {
453
0
        return Status::InvalidArgument("Invalid S3 URI {}, bucket is not specified",
454
0
                                       s3_uri.to_string());
455
0
    }
456
15
    s3_conf->bucket = s3_uri.get_bucket();
457
    // For azure's compatibility
458
15
    s3_conf->client_conf.bucket = s3_uri.get_bucket();
459
15
    s3_conf->prefix = "";
460
461
    // See https://sdk.amazonaws.com/cpp/api/LATEST/class_aws_1_1_s3_1_1_s3_client.html
462
15
    s3_conf->client_conf.use_virtual_addressing = true;
463
15
    if (auto it = properties.find(USE_PATH_STYLE); it != properties.end()) {
464
0
        s3_conf->client_conf.use_virtual_addressing = it->second != "true";
465
0
    }
466
467
15
    if (auto it = properties.find(S3_ROLE_ARN); it != properties.end()) {
468
        // Keep provider type as Default unless explicitly configured by
469
        // AWS_CREDENTIALS_PROVIDER_TYPE, consistent with FE behavior.
470
5
        s3_conf->client_conf.role_arn = it->second;
471
5
    }
472
473
15
    if (auto it = properties.find(S3_EXTERNAL_ID); it != properties.end()) {
474
0
        s3_conf->client_conf.external_id = it->second;
475
0
    }
476
477
15
    if (auto it = properties.find(S3_CREDENTIALS_PROVIDER_TYPE); it != properties.end()) {
478
8
        s3_conf->client_conf.cred_provider_type = cred_provider_type_from_string(it->second);
479
8
    }
480
481
15
    if (auto st = is_s3_conf_valid(s3_conf->client_conf); !st.ok()) {
482
2
        return st;
483
2
    }
484
13
    return Status::OK();
485
15
}
486
487
0
static CredProviderType cred_provider_type_from_thrift(TCredProviderType::type cred_provider_type) {
488
0
    switch (cred_provider_type) {
489
0
    case TCredProviderType::DEFAULT:
490
0
        return CredProviderType::Default;
491
0
    case TCredProviderType::SIMPLE:
492
0
        return CredProviderType::Simple;
493
0
    case TCredProviderType::INSTANCE_PROFILE:
494
0
        return CredProviderType::InstanceProfile;
495
0
    case TCredProviderType::ENV:
496
0
        return CredProviderType::Env;
497
0
    case TCredProviderType::SYSTEM_PROPERTIES:
498
0
        return CredProviderType::SystemProperties;
499
0
    case TCredProviderType::WEB_IDENTITY:
500
0
        return CredProviderType::WebIdentity;
501
0
    case TCredProviderType::CONTAINER:
502
0
        return CredProviderType::Container;
503
0
    case TCredProviderType::ANONYMOUS:
504
0
        return CredProviderType::Anonymous;
505
0
    default:
506
0
        __builtin_unreachable();
507
0
        LOG(WARNING) << "Invalid TCredProviderType value: " << cred_provider_type
508
0
                     << ", use default instead.";
509
0
        return CredProviderType::Default;
510
0
    }
511
0
}
512
513
0
S3Conf S3Conf::get_s3_conf(const cloud::ObjectStoreInfoPB& info) {
514
0
    S3Conf ret {
515
0
            .bucket = info.bucket(),
516
0
            .prefix = info.prefix(),
517
0
            .client_conf {
518
0
                    .endpoint = info.endpoint(),
519
0
                    .region = info.region(),
520
0
                    .ak = info.ak(),
521
0
                    .sk = info.sk(),
522
0
                    .token = {},
523
0
                    .bucket = info.bucket(),
524
0
                    .provider = io::ObjStorageProvider::AWS,
525
0
                    .use_virtual_addressing =
526
0
                            info.has_use_path_style() ? !info.use_path_style() : true,
527
528
0
                    .role_arn = info.role_arn(),
529
0
                    .external_id = info.external_id(),
530
                    // ObjectStoreInfoPB always describes a storage vault, i.e. a Doris
531
                    // internal bucket in cloud mode.
532
0
                    .is_internal_bucket = true,
533
0
            },
534
0
            .sse_enabled = info.sse_enabled(),
535
0
    };
536
537
0
    if (info.has_cred_provider_type()) {
538
0
        ret.client_conf.cred_provider_type = cred_provider_type_from_pb(info.cred_provider_type());
539
0
    }
540
541
0
    io::ObjStorageProvider type = io::ObjStorageProvider::AWS;
542
0
    switch (info.provider()) {
543
0
    case cloud::ObjectStoreInfoPB_Provider_OSS:
544
0
        type = io::ObjStorageProvider::OSS;
545
0
        break;
546
0
    case cloud::ObjectStoreInfoPB_Provider_S3:
547
0
        type = io::ObjStorageProvider::AWS;
548
0
        break;
549
0
    case cloud::ObjectStoreInfoPB_Provider_COS:
550
0
        type = io::ObjStorageProvider::COS;
551
0
        break;
552
0
    case cloud::ObjectStoreInfoPB_Provider_OBS:
553
0
        type = io::ObjStorageProvider::OBS;
554
0
        break;
555
0
    case cloud::ObjectStoreInfoPB_Provider_BOS:
556
0
        type = io::ObjStorageProvider::BOS;
557
0
        break;
558
0
    case cloud::ObjectStoreInfoPB_Provider_GCP:
559
0
        type = io::ObjStorageProvider::GCP;
560
0
        break;
561
0
    case cloud::ObjectStoreInfoPB_Provider_AZURE:
562
0
        type = io::ObjStorageProvider::AZURE;
563
0
        break;
564
0
    case cloud::ObjectStoreInfoPB_Provider_TOS:
565
0
        type = io::ObjStorageProvider::TOS;
566
0
        break;
567
0
    default:
568
0
        __builtin_unreachable();
569
0
        LOG_FATAL("unknown provider type {}, info {}", info.provider(), ret.to_string());
570
0
    }
571
0
    ret.client_conf.provider = type;
572
0
    return ret;
573
0
}
574
575
0
S3Conf S3Conf::get_s3_conf(const TS3StorageParam& param) {
576
0
    S3Conf ret {
577
0
            .bucket = param.bucket,
578
0
            .prefix = param.root_path,
579
0
            .client_conf = {
580
0
                    .endpoint = param.endpoint,
581
0
                    .region = param.region,
582
0
                    .ak = param.ak,
583
0
                    .sk = param.sk,
584
0
                    .token = param.token,
585
0
                    .bucket = param.bucket,
586
0
                    .provider = io::ObjStorageProvider::AWS,
587
0
                    .max_connections = param.max_conn,
588
0
                    .request_timeout_ms = param.request_timeout_ms,
589
0
                    .connect_timeout_ms = param.conn_timeout_ms,
590
                    // When using cold heat separation in minio, user might use ip address directly,
591
                    // which needs enable use_virtual_addressing to true
592
0
                    .use_virtual_addressing = !param.use_path_style,
593
0
                    .role_arn = param.role_arn,
594
0
                    .external_id = param.external_id,
595
0
            }};
596
597
0
    if (param.__isset.cred_provider_type) {
598
0
        ret.client_conf.cred_provider_type =
599
0
                cred_provider_type_from_thrift(param.cred_provider_type);
600
0
    }
601
602
0
    io::ObjStorageProvider type = io::ObjStorageProvider::AWS;
603
0
    switch (param.provider) {
604
0
    case TObjStorageType::UNKNOWN:
605
0
        LOG_INFO("Receive one legal storage resource, set provider type to aws, param detail {}",
606
0
                 ret.to_string());
607
0
        type = io::ObjStorageProvider::AWS;
608
0
        break;
609
0
    case TObjStorageType::AWS:
610
0
        type = io::ObjStorageProvider::AWS;
611
0
        break;
612
0
    case TObjStorageType::AZURE:
613
0
        type = io::ObjStorageProvider::AZURE;
614
0
        break;
615
0
    case TObjStorageType::BOS:
616
0
        type = io::ObjStorageProvider::BOS;
617
0
        break;
618
0
    case TObjStorageType::COS:
619
0
        type = io::ObjStorageProvider::COS;
620
0
        break;
621
0
    case TObjStorageType::OBS:
622
0
        type = io::ObjStorageProvider::OBS;
623
0
        break;
624
0
    case TObjStorageType::OSS:
625
0
        type = io::ObjStorageProvider::OSS;
626
0
        break;
627
0
    case TObjStorageType::GCP:
628
0
        type = io::ObjStorageProvider::GCP;
629
0
        break;
630
0
    case TObjStorageType::TOS:
631
0
        type = io::ObjStorageProvider::TOS;
632
0
        break;
633
0
    default:
634
0
        LOG_FATAL("unknown provider type {}, info {}", param.provider, ret.to_string());
635
0
        __builtin_unreachable();
636
0
    }
637
0
    ret.client_conf.provider = type;
638
0
    return ret;
639
0
}
640
641
16
std::string hide_access_key(const std::string& ak) {
642
16
    std::string key = ak;
643
16
    size_t key_len = key.length();
644
16
    size_t reserved_count;
645
16
    if (key_len > 7) {
646
3
        reserved_count = 6;
647
13
    } else if (key_len > 2) {
648
6
        reserved_count = key_len - 2;
649
7
    } else {
650
7
        reserved_count = 0;
651
7
    }
652
653
16
    size_t x_count = key_len - reserved_count;
654
16
    size_t left_x_count = (x_count + 1) / 2;
655
656
16
    if (left_x_count > 0) {
657
12
        key.replace(0, left_x_count, left_x_count, 'x');
658
12
    }
659
660
16
    if (x_count - left_x_count > 0) {
661
11
        key.replace(key_len - (x_count - left_x_count), x_count - left_x_count,
662
11
                    x_count - left_x_count, 'x');
663
11
    }
664
16
    return key;
665
16
}
666
667
} // end namespace doris