-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
s3fs.cc
3311 lines (2889 loc) · 120 KB
/
s3fs.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/filesystem/s3fs.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <sstream>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#ifdef _WIN32
// Undefine preprocessor macros that interfere with AWS function / method names
#ifdef GetMessage
#undef GetMessage
#endif
#ifdef GetObject
#undef GetObject
#endif
#endif
#include <aws/core/Aws.h>
#include <aws/core/Region.h>
#include <aws/core/VersionConfig.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/auth/STSCredentialsProvider.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/utils/logging/ConsoleLogSystem.h>
#include <aws/core/utils/stream/PreallocatedStreamBuf.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/identity-management/auth/STSAssumeRoleCredentialsProvider.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/S3Errors.h>
#include <aws/s3/model/AbortMultipartUploadRequest.h>
#include <aws/s3/model/CompleteMultipartUploadRequest.h>
#include <aws/s3/model/CompletedMultipartUpload.h>
#include <aws/s3/model/CompletedPart.h>
#include <aws/s3/model/CopyObjectRequest.h>
#include <aws/s3/model/CreateBucketRequest.h>
#include <aws/s3/model/CreateMultipartUploadRequest.h>
#include <aws/s3/model/DeleteBucketRequest.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/DeleteObjectsRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/HeadBucketRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/s3/model/ListBucketsResult.h>
#include <aws/s3/model/ListObjectsV2Request.h>
#include <aws/s3/model/ObjectCannedACL.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/UploadPartRequest.h>
// AWS_SDK_VERSION_{MAJOR,MINOR,PATCH} are available since 1.9.7.
#if defined(AWS_SDK_VERSION_MAJOR) && defined(AWS_SDK_VERSION_MINOR) && \
defined(AWS_SDK_VERSION_PATCH)
// Redundant "(...)" are for suppressing "Weird number of spaces at
// line-start. Are you using a 2-space indent? [whitespace/indent]
// [3]" errors...
#define ARROW_AWS_SDK_VERSION_CHECK(major, minor, patch) \
((AWS_SDK_VERSION_MAJOR > (major) || \
(AWS_SDK_VERSION_MAJOR == (major) && AWS_SDK_VERSION_MINOR > (minor)) || \
((AWS_SDK_VERSION_MAJOR == (major) && AWS_SDK_VERSION_MINOR == (minor) && \
AWS_SDK_VERSION_PATCH >= (patch)))))
#else
#define ARROW_AWS_SDK_VERSION_CHECK(major, minor, patch) 0
#endif
// This feature is available since 1.9.0 but
// AWS_SDK_VERSION_{MAJOR,MINOR,PATCH} are available since 1.9.7. So
// we can't use this feature for [1.9.0,1.9.6]. If it's a problem,
// please report it to our issue tracker.
#if ARROW_AWS_SDK_VERSION_CHECK(1, 9, 0)
#define ARROW_S3_HAS_CRT
#endif
#if ARROW_AWS_SDK_VERSION_CHECK(1, 10, 0)
#define ARROW_S3_HAS_S3CLIENT_CONFIGURATION
#endif
#ifdef ARROW_S3_HAS_CRT
#include <aws/crt/io/Bootstrap.h>
#include <aws/crt/io/EventLoopGroup.h>
#include <aws/crt/io/HostResolver.h>
#endif
#ifdef ARROW_S3_HAS_S3CLIENT_CONFIGURATION
#include <aws/s3/S3ClientConfiguration.h>
#include <aws/s3/S3EndpointProvider.h>
#endif
#include "arrow/util/windows_fixup.h"
#include "arrow/buffer.h"
#include "arrow/filesystem/filesystem.h"
#include "arrow/filesystem/path_util.h"
#include "arrow/filesystem/s3_internal.h"
#include "arrow/filesystem/util_internal.h"
#include "arrow/io/interfaces.h"
#include "arrow/io/memory.h"
#include "arrow/io/util_internal.h"
#include "arrow/result.h"
#include "arrow/status.h"
#include "arrow/util/async_generator.h"
#include "arrow/util/async_util.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/future.h"
#include "arrow/util/io_util.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/string.h"
#include "arrow/util/task_group.h"
#include "arrow/util/thread_pool.h"
namespace arrow::fs {
using ::Aws::Client::AWSError;
using ::Aws::S3::S3Errors;
namespace S3Model = Aws::S3::Model;
using ::arrow::internal::TaskGroup;
using ::arrow::internal::ToChars;
using ::arrow::io::internal::SubmitIO;
using ::arrow::util::Uri;
using internal::ConnectRetryStrategy;
using internal::DetectS3Backend;
using internal::ErrorToStatus;
using internal::FromAwsDatetime;
using internal::FromAwsString;
using internal::IsAlreadyExists;
using internal::IsNotFound;
using internal::OutcomeToResult;
using internal::OutcomeToStatus;
using internal::S3Backend;
using internal::ToAwsString;
using internal::ToURLEncodedAwsString;
static constexpr const char kSep = '/';
static constexpr const char kAwsEndpointUrlEnvVar[] = "AWS_ENDPOINT_URL";
static constexpr const char kAwsEndpointUrlS3EnvVar[] = "AWS_ENDPOINT_URL_S3";
static constexpr const char kAwsDirectoryContentType[] = "application/x-directory";
// -----------------------------------------------------------------------
// S3ProxyOptions implementation
Result<S3ProxyOptions> S3ProxyOptions::FromUri(const Uri& uri) {
S3ProxyOptions options;
options.scheme = uri.scheme();
options.host = uri.host();
options.port = uri.port();
options.username = uri.username();
options.password = uri.password();
return options;
}
Result<S3ProxyOptions> S3ProxyOptions::FromUri(const std::string& uri_string) {
Uri uri;
RETURN_NOT_OK(uri.Parse(uri_string));
return FromUri(uri);
}
bool S3ProxyOptions::Equals(const S3ProxyOptions& other) const {
return (scheme == other.scheme && host == other.host && port == other.port &&
username == other.username && password == other.password);
}
// -----------------------------------------------------------------------
// AwsRetryStrategy implementation
class AwsRetryStrategy : public S3RetryStrategy {
public:
explicit AwsRetryStrategy(std::shared_ptr<Aws::Client::RetryStrategy> retry_strategy)
: retry_strategy_(std::move(retry_strategy)) {}
bool ShouldRetry(const AWSErrorDetail& detail, int64_t attempted_retries) override {
Aws::Client::AWSError<Aws::Client::CoreErrors> error = DetailToError(detail);
return retry_strategy_->ShouldRetry(
error, static_cast<long>(attempted_retries)); // NOLINT: runtime/int
}
int64_t CalculateDelayBeforeNextRetry(const AWSErrorDetail& detail,
int64_t attempted_retries) override {
Aws::Client::AWSError<Aws::Client::CoreErrors> error = DetailToError(detail);
return retry_strategy_->CalculateDelayBeforeNextRetry(
error, static_cast<long>(attempted_retries)); // NOLINT: runtime/int
}
private:
std::shared_ptr<Aws::Client::RetryStrategy> retry_strategy_;
static Aws::Client::AWSError<Aws::Client::CoreErrors> DetailToError(
const S3RetryStrategy::AWSErrorDetail& detail) {
auto exception_name = ToAwsString(detail.exception_name);
auto message = ToAwsString(detail.message);
auto errors = Aws::Client::AWSError<Aws::Client::CoreErrors>(
static_cast<Aws::Client::CoreErrors>(detail.error_type), exception_name, message,
detail.should_retry);
return errors;
}
};
std::shared_ptr<S3RetryStrategy> S3RetryStrategy::GetAwsDefaultRetryStrategy(
int64_t max_attempts) {
return std::make_shared<AwsRetryStrategy>(
std::make_shared<Aws::Client::DefaultRetryStrategy>(
static_cast<long>(max_attempts))); // NOLINT: runtime/int
}
std::shared_ptr<S3RetryStrategy> S3RetryStrategy::GetAwsStandardRetryStrategy(
int64_t max_attempts) {
return std::make_shared<AwsRetryStrategy>(
std::make_shared<Aws::Client::StandardRetryStrategy>(
static_cast<long>(max_attempts))); // NOLINT: runtime/int
}
// -----------------------------------------------------------------------
// S3Options implementation
S3Options::S3Options() {
DCHECK(IsS3Initialized()) << "Must initialize S3 before using S3Options";
}
void S3Options::ConfigureDefaultCredentials() {
credentials_provider =
std::make_shared<Aws::Auth::DefaultAWSCredentialsProviderChain>();
credentials_kind = S3CredentialsKind::Default;
}
void S3Options::ConfigureAnonymousCredentials() {
credentials_provider = std::make_shared<Aws::Auth::AnonymousAWSCredentialsProvider>();
credentials_kind = S3CredentialsKind::Anonymous;
}
void S3Options::ConfigureAccessKey(const std::string& access_key,
const std::string& secret_key,
const std::string& session_token) {
credentials_provider = std::make_shared<Aws::Auth::SimpleAWSCredentialsProvider>(
ToAwsString(access_key), ToAwsString(secret_key), ToAwsString(session_token));
credentials_kind = S3CredentialsKind::Explicit;
}
void S3Options::ConfigureAssumeRoleCredentials(
const std::string& role_arn, const std::string& session_name,
const std::string& external_id, int load_frequency,
const std::shared_ptr<Aws::STS::STSClient>& stsClient) {
credentials_provider = std::make_shared<Aws::Auth::STSAssumeRoleCredentialsProvider>(
ToAwsString(role_arn), ToAwsString(session_name), ToAwsString(external_id),
load_frequency, stsClient);
credentials_kind = S3CredentialsKind::Role;
}
void S3Options::ConfigureAssumeRoleWithWebIdentityCredentials() {
// The AWS SDK uses environment variables AWS_DEFAULT_REGION,
// AWS_ROLE_ARN, AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_SESSION_NAME
// to configure the required credentials
credentials_provider =
std::make_shared<Aws::Auth::STSAssumeRoleWebIdentityCredentialsProvider>();
credentials_kind = S3CredentialsKind::WebIdentity;
}
std::string S3Options::GetAccessKey() const {
auto credentials = credentials_provider->GetAWSCredentials();
return std::string(FromAwsString(credentials.GetAWSAccessKeyId()));
}
std::string S3Options::GetSecretKey() const {
auto credentials = credentials_provider->GetAWSCredentials();
return std::string(FromAwsString(credentials.GetAWSSecretKey()));
}
std::string S3Options::GetSessionToken() const {
auto credentials = credentials_provider->GetAWSCredentials();
return std::string(FromAwsString(credentials.GetSessionToken()));
}
S3Options S3Options::Defaults() {
S3Options options;
options.ConfigureDefaultCredentials();
return options;
}
S3Options S3Options::Anonymous() {
S3Options options;
options.ConfigureAnonymousCredentials();
return options;
}
S3Options S3Options::FromAccessKey(const std::string& access_key,
const std::string& secret_key,
const std::string& session_token) {
S3Options options;
options.ConfigureAccessKey(access_key, secret_key, session_token);
return options;
}
S3Options S3Options::FromAssumeRole(
const std::string& role_arn, const std::string& session_name,
const std::string& external_id, int load_frequency,
const std::shared_ptr<Aws::STS::STSClient>& stsClient) {
S3Options options;
options.role_arn = role_arn;
options.session_name = session_name;
options.external_id = external_id;
options.load_frequency = load_frequency;
options.ConfigureAssumeRoleCredentials(role_arn, session_name, external_id,
load_frequency, stsClient);
return options;
}
S3Options S3Options::FromAssumeRoleWithWebIdentity() {
S3Options options;
options.ConfigureAssumeRoleWithWebIdentityCredentials();
return options;
}
Result<S3Options> S3Options::FromUri(const Uri& uri, std::string* out_path) {
S3Options options;
const auto bucket = uri.host();
auto path = uri.path();
if (bucket.empty()) {
if (!path.empty()) {
return Status::Invalid("Missing bucket name in S3 URI");
}
} else {
if (path.empty()) {
path = bucket;
} else {
if (path[0] != '/') {
return Status::Invalid("S3 URI should be absolute, not relative");
}
path = bucket + path;
}
}
if (out_path != nullptr) {
*out_path = std::string(internal::RemoveTrailingSlash(path));
}
std::unordered_map<std::string, std::string> options_map;
ARROW_ASSIGN_OR_RAISE(const auto options_items, uri.query_items());
for (const auto& kv : options_items) {
options_map.emplace(kv.first, kv.second);
}
const auto username = uri.username();
if (!username.empty()) {
options.ConfigureAccessKey(username, uri.password());
} else {
options.ConfigureDefaultCredentials();
}
// Prefer AWS service-specific endpoint url
auto s3_endpoint_env = arrow::internal::GetEnvVar(kAwsEndpointUrlS3EnvVar);
if (s3_endpoint_env.ok()) {
options.endpoint_override = *s3_endpoint_env;
} else {
auto endpoint_env = arrow::internal::GetEnvVar(kAwsEndpointUrlEnvVar);
if (endpoint_env.ok()) {
options.endpoint_override = *endpoint_env;
}
}
bool region_set = false;
for (const auto& kv : options_map) {
if (kv.first == "region") {
options.region = kv.second;
region_set = true;
} else if (kv.first == "scheme") {
options.scheme = kv.second;
} else if (kv.first == "endpoint_override") {
options.endpoint_override = kv.second;
} else if (kv.first == "allow_bucket_creation") {
ARROW_ASSIGN_OR_RAISE(options.allow_bucket_creation,
::arrow::internal::ParseBoolean(kv.second));
} else if (kv.first == "allow_bucket_deletion") {
ARROW_ASSIGN_OR_RAISE(options.allow_bucket_deletion,
::arrow::internal::ParseBoolean(kv.second));
} else {
return Status::Invalid("Unexpected query parameter in S3 URI: '", kv.first, "'");
}
}
if (!region_set && !bucket.empty() && options.endpoint_override.empty()) {
// XXX Should we use a dedicated resolver with the given credentials?
ARROW_ASSIGN_OR_RAISE(options.region, ResolveS3BucketRegion(bucket));
}
return options;
}
Result<S3Options> S3Options::FromUri(const std::string& uri_string,
std::string* out_path) {
Uri uri;
RETURN_NOT_OK(uri.Parse(uri_string));
return FromUri(uri, out_path);
}
bool S3Options::Equals(const S3Options& other) const {
const int64_t default_metadata_size = default_metadata ? default_metadata->size() : 0;
const bool default_metadata_equals =
default_metadata_size
? (other.default_metadata && other.default_metadata->Equals(*default_metadata))
: (!other.default_metadata || other.default_metadata->size() == 0);
return (region == other.region && connect_timeout == other.connect_timeout &&
request_timeout == other.request_timeout &&
endpoint_override == other.endpoint_override && scheme == other.scheme &&
role_arn == other.role_arn && session_name == other.session_name &&
external_id == other.external_id && load_frequency == other.load_frequency &&
proxy_options.Equals(other.proxy_options) &&
credentials_kind == other.credentials_kind &&
background_writes == other.background_writes &&
allow_bucket_creation == other.allow_bucket_creation &&
allow_bucket_deletion == other.allow_bucket_deletion &&
default_metadata_equals && GetAccessKey() == other.GetAccessKey() &&
GetSecretKey() == other.GetSecretKey() &&
GetSessionToken() == other.GetSessionToken());
}
namespace {
Status ErrorS3Finalized() { return Status::Invalid("S3 subsystem is finalized"); }
Status CheckS3Initialized() {
if (!IsS3Initialized()) {
if (IsS3Finalized()) {
return ErrorS3Finalized();
}
return Status::Invalid(
"S3 subsystem is not initialized; please call InitializeS3() "
"before carrying out any S3-related operation");
}
return Status::OK();
}
// XXX Sanitize paths by removing leading slash?
struct S3Path {
std::string full_path;
std::string bucket;
std::string key;
std::vector<std::string> key_parts;
static Result<S3Path> FromString(const std::string& s) {
if (internal::IsLikelyUri(s)) {
return Status::Invalid(
"Expected an S3 object path of the form 'bucket/key...', got a URI: '", s, "'");
}
const auto src = internal::RemoveTrailingSlash(s);
auto first_sep = src.find_first_of(kSep);
if (first_sep == 0) {
return Status::Invalid("Path cannot start with a separator ('", s, "')");
}
if (first_sep == std::string::npos) {
return S3Path{std::string(src), std::string(src), "", {}};
}
S3Path path;
path.full_path = std::string(src);
path.bucket = std::string(src.substr(0, first_sep));
path.key = std::string(src.substr(first_sep + 1));
path.key_parts = internal::SplitAbstractPath(path.key);
RETURN_NOT_OK(Validate(path));
return path;
}
static Status Validate(const S3Path& path) {
auto st = internal::ValidateAbstractPath(path.full_path);
if (!st.ok()) {
return Status::Invalid(st.message(), " in path ", path.full_path);
}
return Status::OK();
}
Aws::String ToAwsString() const {
Aws::String res(bucket.begin(), bucket.end());
res.reserve(bucket.size() + key.size() + 1);
res += kSep;
res.append(key.begin(), key.end());
return res;
}
Aws::String ToURLEncodedAwsString() const {
// URL-encode individual parts, not the '/' separator
Aws::String res;
res += internal::ToURLEncodedAwsString(bucket);
for (const auto& part : key_parts) {
res += kSep;
res += internal::ToURLEncodedAwsString(part);
}
return res;
}
S3Path parent() const {
DCHECK(!key_parts.empty());
auto parent = S3Path{"", bucket, "", key_parts};
parent.key_parts.pop_back();
parent.key = internal::JoinAbstractPath(parent.key_parts);
parent.full_path = parent.bucket + kSep + parent.key;
return parent;
}
bool has_parent() const { return !key.empty(); }
bool empty() const { return bucket.empty() && key.empty(); }
bool operator==(const S3Path& other) const {
return bucket == other.bucket && key == other.key;
}
};
// XXX return in OutcomeToStatus instead?
Status PathNotFound(const S3Path& path) {
return ::arrow::fs::internal::PathNotFound(path.full_path);
}
Status PathNotFound(const std::string& bucket, const std::string& key) {
return ::arrow::fs::internal::PathNotFound(bucket + kSep + key);
}
Status NotAFile(const S3Path& path) {
return ::arrow::fs::internal::NotAFile(path.full_path);
}
Status ValidateFilePath(const S3Path& path) {
if (path.bucket.empty() || path.key.empty()) {
return NotAFile(path);
}
return Status::OK();
}
std::string FormatRange(int64_t start, int64_t length) {
// Format a HTTP range header value
std::stringstream ss;
ss << "bytes=" << start << "-" << start + length - 1;
return ss.str();
}
// An AWS RetryStrategy that wraps a provided arrow::fs::S3RetryStrategy
class WrappedRetryStrategy : public Aws::Client::RetryStrategy {
public:
explicit WrappedRetryStrategy(const std::shared_ptr<S3RetryStrategy>& s3_retry_strategy)
: s3_retry_strategy_(s3_retry_strategy) {}
bool ShouldRetry(const Aws::Client::AWSError<Aws::Client::CoreErrors>& error,
long attempted_retries) const override { // NOLINT runtime/int
S3RetryStrategy::AWSErrorDetail detail = ErrorToDetail(error);
return s3_retry_strategy_->ShouldRetry(detail,
static_cast<int64_t>(attempted_retries));
}
long CalculateDelayBeforeNextRetry( // NOLINT runtime/int
const Aws::Client::AWSError<Aws::Client::CoreErrors>& error,
long attempted_retries) const override { // NOLINT runtime/int
S3RetryStrategy::AWSErrorDetail detail = ErrorToDetail(error);
return static_cast<long>( // NOLINT runtime/int
s3_retry_strategy_->CalculateDelayBeforeNextRetry(
detail, static_cast<int64_t>(attempted_retries)));
}
private:
template <typename ErrorType>
static S3RetryStrategy::AWSErrorDetail ErrorToDetail(
const Aws::Client::AWSError<ErrorType>& error) {
S3RetryStrategy::AWSErrorDetail detail;
detail.error_type = static_cast<int>(error.GetErrorType());
detail.message = std::string(FromAwsString(error.GetMessage()));
detail.exception_name = std::string(FromAwsString(error.GetExceptionName()));
detail.should_retry = error.ShouldRetry();
return detail;
}
std::shared_ptr<S3RetryStrategy> s3_retry_strategy_;
};
class S3Client : public Aws::S3::S3Client {
public:
using Aws::S3::S3Client::S3Client;
static inline constexpr auto kBucketRegionHeaderName = "x-amz-bucket-region";
std::string GetBucketRegionFromHeaders(
const Aws::Http::HeaderValueCollection& headers) {
const auto it = headers.find(ToAwsString(kBucketRegionHeaderName));
if (it != headers.end()) {
return std::string(FromAwsString(it->second));
}
return std::string();
}
template <typename ErrorType>
Result<std::string> GetBucketRegionFromError(
const std::string& bucket, const Aws::Client::AWSError<ErrorType>& error) {
std::string region = GetBucketRegionFromHeaders(error.GetResponseHeaders());
if (!region.empty()) {
return region;
} else if (error.GetResponseCode() == Aws::Http::HttpResponseCode::NOT_FOUND) {
return Status::IOError("Bucket '", bucket, "' not found");
} else {
return ErrorToStatus(
std::forward_as_tuple("When resolving region for bucket '", bucket, "': "),
"HeadBucket", error);
}
}
#if ARROW_AWS_SDK_VERSION_CHECK(1, 11, 212)
// HeadBucketResult::GetBucketRegion appeared in AWS SDK 1.11.212
Result<std::string> GetBucketRegion(const std::string& bucket,
const S3Model::HeadBucketRequest& request) {
auto outcome = this->HeadBucket(request);
if (!outcome.IsSuccess()) {
return GetBucketRegionFromError(bucket, outcome.GetError());
}
auto&& region = std::move(outcome).GetResult().GetBucketRegion();
if (region.empty()) {
return Status::IOError("When resolving region for bucket '", request.GetBucket(),
"': missing 'x-amz-bucket-region' header in response");
}
return region;
}
#else
// To get a bucket's region, we must extract the "x-amz-bucket-region" header
// from the response to a HEAD bucket request.
// Unfortunately, the S3Client APIs don't let us access the headers of successful
// responses. So we have to cook a AWS request and issue it ourselves.
Result<std::string> GetBucketRegion(const std::string& bucket,
const S3Model::HeadBucketRequest& request) {
auto uri = GeneratePresignedUrl(request.GetBucket(),
/*key=*/"", Aws::Http::HttpMethod::HTTP_HEAD);
// NOTE: The signer region argument isn't passed here, as there's no easy
// way of computing it (the relevant method is private).
auto outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_HEAD,
Aws::Auth::SIGV4_SIGNER);
if (!outcome.IsSuccess()) {
return GetBucketRegionFromError(bucket, outcome.GetError());
}
std::string region =
GetBucketRegionFromHeaders(outcome.GetResult().GetHeaderValueCollection());
if (!region.empty()) {
return region;
} else if (outcome.GetResult().GetResponseCode() ==
Aws::Http::HttpResponseCode::NOT_FOUND) {
return Status::IOError("Bucket '", request.GetBucket(), "' not found");
} else {
return Status::IOError("When resolving region for bucket '", request.GetBucket(),
"': missing 'x-amz-bucket-region' header in response");
}
}
#endif
Result<std::string> GetBucketRegion(const std::string& bucket) {
S3Model::HeadBucketRequest req;
req.SetBucket(ToAwsString(bucket));
return GetBucketRegion(bucket, req);
}
S3Model::CompleteMultipartUploadOutcome CompleteMultipartUploadWithErrorFixup(
S3Model::CompleteMultipartUploadRequest&& request) const {
// CompletedMultipartUpload can return a 200 OK response with an error
// encoded in the response body, in which case we should either retry
// or propagate the error to the user (see
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html).
//
// Unfortunately the AWS SDK doesn't detect such situations but lets them
// return successfully (see https://github.com/aws/aws-sdk-cpp/issues/658).
//
// We work around the issue by registering a DataReceivedEventHandler
// which parses the XML response for embedded errors.
std::optional<AWSError<Aws::Client::CoreErrors>> aws_error;
auto handler = [&](const Aws::Http::HttpRequest* http_req,
Aws::Http::HttpResponse* http_resp,
long long) { // NOLINT runtime/int
auto& stream = http_resp->GetResponseBody();
const auto pos = stream.tellg();
const auto doc = Aws::Utils::Xml::XmlDocument::CreateFromXmlStream(stream);
// Rewind stream for later
stream.clear();
stream.seekg(pos);
if (doc.WasParseSuccessful()) {
auto root = doc.GetRootElement();
if (!root.IsNull()) {
// Detect something that looks like an abnormal CompletedMultipartUpload
// response.
if (root.GetName() != "CompleteMultipartUploadResult" ||
!root.FirstChild("Error").IsNull() || !root.FirstChild("Errors").IsNull()) {
// Make sure the error marshaller doesn't see a 200 OK
http_resp->SetResponseCode(
Aws::Http::HttpResponseCode::INTERNAL_SERVER_ERROR);
aws_error = GetErrorMarshaller()->Marshall(*http_resp);
// Rewind stream for later
stream.clear();
stream.seekg(pos);
}
}
}
};
request.SetDataReceivedEventHandler(std::move(handler));
// We don't have access to the configured AWS retry strategy
// (m_retryStrategy is a private member of AwsClient), so don't use that.
std::unique_ptr<Aws::Client::RetryStrategy> retry_strategy;
if (s3_retry_strategy_) {
retry_strategy.reset(new WrappedRetryStrategy(s3_retry_strategy_));
} else {
// Note that DefaultRetryStrategy, unlike StandardRetryStrategy,
// has empty definitions for RequestBookkeeping() and GetSendToken(),
// which simplifies the code below.
retry_strategy.reset(new Aws::Client::DefaultRetryStrategy());
}
for (int32_t retries = 0;; retries++) {
aws_error.reset();
auto outcome = Aws::S3::S3Client::S3Client::CompleteMultipartUpload(request);
if (!outcome.IsSuccess()) {
// Error returned in HTTP headers (or client failure)
return outcome;
}
if (!aws_error.has_value()) {
// Genuinely successful outcome
return outcome;
}
const bool should_retry = retry_strategy->ShouldRetry(*aws_error, retries);
ARROW_LOG(WARNING)
<< "CompletedMultipartUpload got error embedded in a 200 OK response: "
<< aws_error->GetExceptionName() << " (\"" << aws_error->GetMessage()
<< "\"), retry = " << should_retry;
if (!should_retry) {
break;
}
const auto delay = std::chrono::milliseconds(
retry_strategy->CalculateDelayBeforeNextRetry(*aws_error, retries));
std::this_thread::sleep_for(delay);
}
DCHECK(aws_error.has_value());
auto s3_error = AWSError<S3Errors>(std::move(aws_error).value());
return S3Model::CompleteMultipartUploadOutcome(std::move(s3_error));
}
std::shared_ptr<S3RetryStrategy> s3_retry_strategy_;
};
// In AWS SDK < 1.8, Aws::Client::ClientConfiguration::followRedirects is a bool.
template <bool Never = false>
void DisableRedirectsImpl(bool* followRedirects) {
*followRedirects = false;
}
// In AWS SDK >= 1.8, it's a Aws::Client::FollowRedirectsPolicy scoped enum.
template <typename PolicyEnum, PolicyEnum Never = PolicyEnum::NEVER>
void DisableRedirectsImpl(PolicyEnum* followRedirects) {
*followRedirects = Never;
}
void DisableRedirects(Aws::Client::ClientConfiguration* c) {
DisableRedirectsImpl(&c->followRedirects);
}
// -----------------------------------------------------------------------
// S3 client protection against use after finalization
//
// Applications are advised to call FinalizeS3() before process end.
// However, once this is done, AWS APIs cannot reliably be called anymore
// (even destructors may crash or trigger UB).
// To prevent such issues, we wrap all S3Client instances in a special
// structure (S3ClientHolder) that prevents usage of S3Client after
// S3 was finalized.
// Please make sure you read the comments in S3ClientLock::Move below.
//
// See: GH-36346, GH-15054.
class S3ClientFinalizer;
class S3ClientLock {
public:
S3Client* get() { return client_.get(); }
S3Client* operator->() { return client_.get(); }
// Move this S3ClientLock into a temporary instance
//
// It is counter-intuitive, but lock ordering issues can happen even
// with a shared mutex locked in shared mode.
// The reason is that locking again in shared mode can block while
// there are threads waiting to take the lock in exclusive mode.
// Therefore, we should avoid obtaining the S3ClientLock when
// we already have it locked.
//
// This methods helps by moving the S3ClientLock into a temporary
// that is immediately destroyed so the lock will be released as
// soon as we are done making the call to the underlying client.
//
// (see GH-36523)
S3ClientLock Move() { return std::move(*this); }
protected:
friend class S3ClientHolder;
// Locks the finalizer until the S3ClientLock gets out of scope.
std::shared_lock<std::shared_mutex> lock_;
std::shared_ptr<S3Client> client_;
};
class S3ClientHolder {
public:
/// \brief Return a RAII guard guaranteeing a S3Client is safe for use
///
/// S3 finalization will be deferred until the returned S3ClientLock
/// goes out of scope.
/// An error is returned if S3 is already finalized.
Result<S3ClientLock> Lock();
S3ClientHolder(std::weak_ptr<S3ClientFinalizer> finalizer,
std::shared_ptr<S3Client> client)
: finalizer_(std::move(finalizer)), client_(std::move(client)) {}
void Finalize();
protected:
std::mutex mutex_;
std::weak_ptr<S3ClientFinalizer> finalizer_;
std::shared_ptr<S3Client> client_;
};
class S3ClientFinalizer : public std::enable_shared_from_this<S3ClientFinalizer> {
using ClientHolderList = std::vector<std::weak_ptr<S3ClientHolder>>;
public:
Result<std::shared_ptr<S3ClientHolder>> AddClient(std::shared_ptr<S3Client> client) {
std::unique_lock lock(mutex_);
if (finalized_) {
return ErrorS3Finalized();
}
auto holder = std::make_shared<S3ClientHolder>(shared_from_this(), std::move(client));
// Remove expired entries before adding new one
auto end = std::remove_if(
holders_.begin(), holders_.end(),
[](std::weak_ptr<S3ClientHolder> holder) { return holder.expired(); });
holders_.erase(end, holders_.end());
holders_.emplace_back(holder);
return holder;
}
void Finalize() {
std::unique_lock lock(mutex_);
finalized_ = true;
ClientHolderList finalizing = std::move(holders_);
lock.unlock(); // avoid lock ordering issue with S3ClientHolder::Finalize
// Finalize all client holders, such that no S3Client remains alive
// after this.
for (auto&& weak_holder : finalizing) {
auto holder = weak_holder.lock();
if (holder) {
holder->Finalize();
}
}
}
auto LockShared() { return std::shared_lock(mutex_); }
protected:
friend class S3ClientHolder;
std::shared_mutex mutex_;
ClientHolderList holders_;
bool finalized_ = false;
};
Result<S3ClientLock> S3ClientHolder::Lock() {
std::shared_ptr<S3ClientFinalizer> finalizer;
std::shared_ptr<S3Client> client;
{
std::unique_lock lock(mutex_);
finalizer = finalizer_.lock();
client = client_;
}
// Do not hold mutex while taking finalizer lock below.
//
// Acquiring a shared_mutex in shared mode may block even if not already
// acquired in exclusive mode, because of pending writers:
// https://github.com/google/sanitizers/issues/1668#issuecomment-1624985664
// """It is implementation-defined whether the calling thread acquires
// the lock when a writer does not hold the lock and there are writers
// blocked on the lock""".
//
// Therefore, we want to avoid potential lock ordering issues
// even when a shared lock is involved (GH-36523).
if (!finalizer) {
return ErrorS3Finalized();
}
S3ClientLock client_lock;
// Lock the finalizer before examining it
client_lock.lock_ = finalizer->LockShared();
if (finalizer->finalized_) {
return ErrorS3Finalized();
}
// (the client can be cleared only if finalizer->finalized_ is true)
DCHECK(client) << "inconsistent S3ClientHolder";
client_lock.client_ = std::move(client);
return client_lock;
}
void S3ClientHolder::Finalize() {
std::shared_ptr<S3Client> client;
{
std::unique_lock lock(mutex_);
client = std::move(client_);
}
// Do not hold mutex while ~S3Client potentially runs
}
std::shared_ptr<S3ClientFinalizer> GetClientFinalizer() {
static auto finalizer = std::make_shared<S3ClientFinalizer>();
return finalizer;
}
Result<std::shared_ptr<S3ClientHolder>> GetClientHolder(
std::shared_ptr<S3Client> client) {
return GetClientFinalizer()->AddClient(std::move(client));
}
// -----------------------------------------------------------------------
// S3 client factory: build S3Client from S3Options
#ifdef ARROW_S3_HAS_S3CLIENT_CONFIGURATION
// GH-40279: standard initialization of S3Client creates a new `S3EndpointProvider`
// every time. Its construction takes 1ms, which makes instantiating every S3Client
// very costly (see upstream bug report
// at https://github.com/aws/aws-sdk-cpp/issues/2880).
// To work around this, we build and cache `S3EndpointProvider` instances
// for each distinct endpoint configuration, and reuse them whenever possible.
// Since most applications tend to use a single endpoint configuration, this
// makes the 1ms setup cost a once-per-process overhead, making it much more
// bearable - if not ideal.
struct EndpointConfigKey {
explicit EndpointConfigKey(const Aws::S3::S3ClientConfiguration& config)
: region(config.region),
scheme(config.scheme),
endpoint_override(config.endpointOverride),
use_virtual_addressing(config.useVirtualAddressing) {}
Aws::String region;
Aws::Http::Scheme scheme;
Aws::String endpoint_override;
bool use_virtual_addressing;
bool operator==(const EndpointConfigKey& other) const noexcept {
return region == other.region && scheme == other.scheme &&
endpoint_override == other.endpoint_override &&
use_virtual_addressing == other.use_virtual_addressing;
}
};
} // namespace
} // namespace arrow::fs
template <>
struct std::hash<arrow::fs::EndpointConfigKey> {
std::size_t operator()(const arrow::fs::EndpointConfigKey& key) const noexcept {
// A crude hash is sufficient since we expect the cache to remain very small.
auto h = std::hash<Aws::String>{};
return h(key.region) ^ h(key.endpoint_override);
}