-
Notifications
You must be signed in to change notification settings - Fork 179
/
s3.cc
1754 lines (1458 loc) · 58.3 KB
/
s3.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
/**
* @file s3.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* This file implements the S3 class.
*/
#ifdef HAVE_S3
#include "tiledb/common/common.h"
#include "tiledb/common/filesystem/directory_entry.h"
#include <aws/core/utils/logging/AWSLogging.h>
#include <aws/core/utils/logging/DefaultLogSystem.h>
#include <aws/core/utils/logging/LogLevel.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/s3/model/AbortMultipartUploadRequest.h>
#include <aws/s3/model/CreateMultipartUploadRequest.h>
#include <boost/interprocess/streams/bufferstream.hpp>
#include <fstream>
#include <iostream>
#include "tiledb/common/logger.h"
#include "tiledb/common/unique_rwlock.h"
#include "tiledb/sm/global_state/global_state.h"
#include "tiledb/sm/global_state/unit_test_config.h"
#include "tiledb/sm/misc/tdb_math.h"
#include "tiledb/sm/misc/utils.h"
#ifdef _WIN32
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#include <Windows.h>
#undef GetMessage // workaround for
// https://github.com/aws/aws-sdk-cpp/issues/402
#endif
#include "tiledb/sm/filesystem/s3.h"
#include "tiledb/sm/misc/parallel_functions.h"
using tiledb::common::filesystem::directory_entry;
namespace {
Aws::Utils::Logging::LogLevel aws_log_name_to_level(std::string loglevel) {
std::transform(loglevel.begin(), loglevel.end(), loglevel.begin(), ::tolower);
if (loglevel == "fatal")
return Aws::Utils::Logging::LogLevel::Fatal;
else if (loglevel == "error")
return Aws::Utils::Logging::LogLevel::Error;
else if (loglevel == "warn")
return Aws::Utils::Logging::LogLevel::Warn;
else if (loglevel == "info")
return Aws::Utils::Logging::LogLevel::Info;
else if (loglevel == "debug")
return Aws::Utils::Logging::LogLevel::Debug;
else if (loglevel == "trace")
return Aws::Utils::Logging::LogLevel::Trace;
else
return Aws::Utils::Logging::LogLevel::Off;
}
/**
* Return a S3 enum value for any recognized string or NOT_SET if
* B) the string is not recognized to match any of the enum values
*
* @param canned_acl_str A textual string naming one of the
* Aws::S3::Model::ObjectCannedACL enum members.
*/
Aws::S3::Model::ObjectCannedACL S3_ObjectCannedACL_from_str(
const std::string& canned_acl_str) {
if (canned_acl_str.empty())
return Aws::S3::Model::ObjectCannedACL::NOT_SET;
if (canned_acl_str == "NOT_SET")
return Aws::S3::Model::ObjectCannedACL::NOT_SET;
else if (canned_acl_str == "private_")
return Aws::S3::Model::ObjectCannedACL::private_;
else if (canned_acl_str == "public_read")
return Aws::S3::Model::ObjectCannedACL::public_read;
else if (canned_acl_str == "public_read_write")
return Aws::S3::Model::ObjectCannedACL::public_read_write;
else if (canned_acl_str == "authenticated_read")
return Aws::S3::Model::ObjectCannedACL::authenticated_read;
else if (canned_acl_str == "aws_exec_read")
return Aws::S3::Model::ObjectCannedACL::aws_exec_read;
else if (canned_acl_str == "bucket_owner_read")
return Aws::S3::Model::ObjectCannedACL::bucket_owner_read;
else if (canned_acl_str == "bucket_owner_full_control")
return Aws::S3::Model::ObjectCannedACL::bucket_owner_full_control;
else
return Aws::S3::Model::ObjectCannedACL::NOT_SET;
}
/**
* Return a S3 enum value for any recognized string or NOT_SET if
* B) the string is not recognized to match any of the enum values
*
* @param canned_acl_str A textual string naming one of the
* Aws::S3::Model::BucketCannedACL enum members.
*/
Aws::S3::Model::BucketCannedACL S3_BucketCannedACL_from_str(
const std::string& canned_acl_str) {
if (canned_acl_str.empty())
return Aws::S3::Model::BucketCannedACL::NOT_SET;
if (canned_acl_str == "NOT_SET")
return Aws::S3::Model::BucketCannedACL::NOT_SET;
else if (canned_acl_str == "private_")
return Aws::S3::Model::BucketCannedACL::private_;
else if (canned_acl_str == "public_read")
return Aws::S3::Model::BucketCannedACL::public_read;
else if (canned_acl_str == "public_read_write")
return Aws::S3::Model::BucketCannedACL::public_read_write;
else if (canned_acl_str == "authenticated_read")
return Aws::S3::Model::BucketCannedACL::authenticated_read;
else
return Aws::S3::Model::BucketCannedACL::NOT_SET;
}
} // namespace
using namespace tiledb::common;
namespace tiledb {
namespace sm {
namespace {
/**
* Return the exception name and error message from the given outcome object.
*
* @tparam R AWS result type
* @tparam E AWS error type
* @param outcome Outcome to retrieve error message from
* @return Error message string
*/
template <typename R, typename E>
std::string outcome_error_message(const Aws::Utils::Outcome<R, E>& outcome) {
return std::string("\nException: ") +
outcome.GetError().GetExceptionName().c_str() +
std::string("\nError message: ") +
outcome.GetError().GetMessage().c_str();
}
} // namespace
/* ********************************* */
/* GLOBAL VARIABLES */
/* ********************************* */
/** Ensures that the AWS library is only initialized once per process. */
static std::once_flag aws_lib_initialized;
/* ********************************* */
/* CONSTRUCTORS & DESTRUCTORS */
/* ********************************* */
S3::S3()
: stats_(nullptr)
, state_(State::UNINITIALIZED)
, credentials_provider_(nullptr)
, file_buffer_size_(0)
, max_parallel_ops_(1)
, multipart_part_size_(0)
, vfs_thread_pool_(nullptr)
, use_virtual_addressing_(false)
, use_multipart_upload_(true)
, request_payer_(Aws::S3::Model::RequestPayer::NOT_SET)
, sse_(Aws::S3::Model::ServerSideEncryption::NOT_SET)
, object_canned_acl_(Aws::S3::Model::ObjectCannedACL::NOT_SET)
, bucket_canned_acl_(Aws::S3::Model::BucketCannedACL::NOT_SET) {
}
S3::~S3() {
assert(state_ == State::DISCONNECTED);
for (auto& buff : file_buffers_)
tdb_delete(buff.second);
}
/* ********************************* */
/* API */
/* ********************************* */
Status S3::init(
stats::Stats* const parent_stats,
const Config& config,
ThreadPool* const thread_pool) {
// already initialized
if (state_ == State::DISCONNECTED)
return Status::Ok();
assert(state_ == State::UNINITIALIZED);
stats_ = parent_stats->create_child("S3");
if (thread_pool == nullptr) {
return LOG_STATUS(
Status_S3Error("Can't initialize with null thread pool."));
}
bool found = false;
auto logging_level = config.get("vfs.s3.logging_level", &found);
assert(found);
options_.loggingOptions.logLevel = aws_log_name_to_level(logging_level);
// By default, curl sets the signal handler for SIGPIPE to SIG_IGN while
// executing. When curl is done executing, it restores the previous signal
// handler. This is not thread safe, so the AWS SDK disables this behavior
// in curl using the `CURLOPT_NOSIGNAL` option.
// Here, we set the `installSigPipeHandler` AWS SDK option to `true` to allow
// the AWS SDK to set its own signal handler to ignore SIGPIPE signals. A
// SIGPIPE may be raised from the socket library when the peer disconnects
// unexpectedly.
options_.httpOptions.installSigPipeHandler = true;
bool skip_init;
RETURN_NOT_OK(config.get<bool>("vfs.s3.skip_init", &skip_init, &found));
assert(found);
// Initialize the library once per process.
if (!skip_init)
std::call_once(aws_lib_initialized, [this]() { Aws::InitAPI(options_); });
if (options_.loggingOptions.logLevel != Aws::Utils::Logging::LogLevel::Off) {
Aws::Utils::Logging::InitializeAWSLogging(
Aws::MakeShared<Aws::Utils::Logging::DefaultLogSystem>(
"TileDB", Aws::Utils::Logging::LogLevel::Trace, "tiledb_s3_"));
}
vfs_thread_pool_ = thread_pool;
RETURN_NOT_OK(config.get<uint64_t>(
"vfs.s3.max_parallel_ops", &max_parallel_ops_, &found));
assert(found);
RETURN_NOT_OK(config.get<uint64_t>(
"vfs.s3.multipart_part_size", &multipart_part_size_, &found));
assert(found);
file_buffer_size_ = multipart_part_size_ * max_parallel_ops_;
region_ = config.get("vfs.s3.region", &found);
assert(found);
RETURN_NOT_OK(config.get<bool>(
"vfs.s3.use_virtual_addressing", &use_virtual_addressing_, &found));
assert(found);
RETURN_NOT_OK(config.get<bool>(
"vfs.s3.use_multipart_upload", &use_multipart_upload_, &found));
assert(found);
bool request_payer;
RETURN_NOT_OK(
config.get<bool>("vfs.s3.requester_pays", &request_payer, &found));
assert(found);
if (request_payer)
request_payer_ = Aws::S3::Model::RequestPayer::requester;
auto object_acl_str = config.get("vfs.s3.object_canned_acl", &found);
assert(found);
if (found) {
object_canned_acl_ = S3_ObjectCannedACL_from_str(object_acl_str);
}
auto bucket_acl_str = config.get("vfs.s3.bucket_canned_acl", &found);
assert(found);
if (found) {
bucket_canned_acl_ = S3_BucketCannedACL_from_str(bucket_acl_str);
}
auto sse = config.get("vfs.s3.sse", &found);
assert(found);
auto sse_kms_key_id = config.get("vfs.s3.sse_kms_key_id", &found);
assert(found);
if (!sse.empty()) {
if (sse == "aes256") {
sse_ = Aws::S3::Model::ServerSideEncryption::AES256;
} else if (sse == "kms") {
sse_ = Aws::S3::Model::ServerSideEncryption::aws_kms;
sse_kms_key_id_ = sse_kms_key_id;
if (sse_kms_key_id_.empty()) {
return Status_S3Error(
"Config parameter 'vfs.s3.sse_kms_key_id' must be set "
"for kms server-side encryption.");
}
} else {
return Status_S3Error(
"Unknown 'vfs.s3.sse' config value " + sse +
"; supported values are 'aes256' and 'kms'.");
}
}
// Ensure `sse_kms_key_id` was only set for kms encryption.
if (!sse_kms_key_id.empty() &&
sse_ != Aws::S3::Model::ServerSideEncryption::aws_kms) {
return Status_S3Error(
"Config parameter 'vfs.s3.sse_kms_key_id' may only be "
"set for 'vfs.s3.sse' == 'kms'.");
}
config_ = config;
state_ = State::INITIALIZED;
return Status::Ok();
}
Status S3::create_bucket(const URI& bucket) const {
RETURN_NOT_OK(init_client());
if (!bucket.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + bucket.to_string())));
}
Aws::Http::URI aws_uri = bucket.c_str();
Aws::S3::Model::CreateBucketRequest create_bucket_request;
create_bucket_request.SetBucket(aws_uri.GetAuthority());
// Set the bucket location constraint equal to the S3 region.
// Note: empty string and 'us-east-1' are parsing errors in the SDK.
if (!region_.empty() && region_ != "us-east-1") {
Aws::S3::Model::CreateBucketConfiguration cfg;
Aws::String region_str(region_.c_str());
auto location_constraint = Aws::S3::Model::BucketLocationConstraintMapper::
GetBucketLocationConstraintForName(region_str);
cfg.SetLocationConstraint(location_constraint);
create_bucket_request.SetCreateBucketConfiguration(cfg);
}
if (bucket_canned_acl_ != Aws::S3::Model::BucketCannedACL::NOT_SET) {
create_bucket_request.SetACL(bucket_canned_acl_);
}
auto create_bucket_outcome = client_->CreateBucket(create_bucket_request);
if (!create_bucket_outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to create S3 bucket ") + bucket.to_string() +
outcome_error_message(create_bucket_outcome)));
}
RETURN_NOT_OK(wait_for_bucket_to_be_created(bucket));
return Status::Ok();
}
Status S3::remove_bucket(const URI& bucket) const {
RETURN_NOT_OK(init_client());
// Empty bucket
RETURN_NOT_OK(empty_bucket(bucket));
// Delete bucket
Aws::Http::URI aws_uri = bucket.c_str();
Aws::S3::Model::DeleteBucketRequest delete_bucket_request;
delete_bucket_request.SetBucket(aws_uri.GetAuthority());
auto delete_bucket_outcome = client_->DeleteBucket(delete_bucket_request);
if (!delete_bucket_outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to remove S3 bucket ") + bucket.to_string() +
outcome_error_message(delete_bucket_outcome)));
}
return Status::Ok();
}
Status S3::disconnect() {
Status ret_st = Status::Ok();
if (state_ == State::UNINITIALIZED) {
return ret_st;
}
// Read-lock 'multipart_upload_states_'.
UniqueReadLock unique_rl(&multipart_upload_rwlock_);
if (multipart_upload_states_.size() > 0) {
RETURN_NOT_OK(init_client());
std::vector<const MultiPartUploadState*> states;
states.reserve(multipart_upload_states_.size());
for (auto& kv : multipart_upload_states_)
states.emplace_back(&kv.second);
auto status =
parallel_for(vfs_thread_pool_, 0, states.size(), [&](uint64_t i) {
const MultiPartUploadState* state = states[i];
// Lock multipart state
std::unique_lock<std::mutex> state_lck(state->mtx);
if (state->st.ok()) {
Aws::S3::Model::CompleteMultipartUploadRequest complete_request =
make_multipart_complete_request(*state);
auto outcome = client_->CompleteMultipartUpload(complete_request);
if (!outcome.IsSuccess()) {
const Status st = LOG_STATUS(Status_S3Error(
std::string("Failed to disconnect and flush S3 objects. ") +
outcome_error_message(outcome)));
if (!st.ok()) {
ret_st = st;
}
}
} else {
Aws::S3::Model::AbortMultipartUploadRequest abort_request =
make_multipart_abort_request(*state);
auto outcome = client_->AbortMultipartUpload(abort_request);
if (!outcome.IsSuccess()) {
const Status st = LOG_STATUS(Status_S3Error(
std::string("Failed to disconnect and flush S3 objects. ") +
outcome_error_message(outcome)));
if (!st.ok()) {
ret_st = st;
}
}
}
return Status::Ok();
});
RETURN_NOT_OK(status);
}
unique_rl.unlock();
if (options_.loggingOptions.logLevel != Aws::Utils::Logging::LogLevel::Off) {
Aws::Utils::Logging::ShutdownAWSLogging();
}
if (s3_tp_executor_) {
const Status st = s3_tp_executor_->Stop();
if (!st.ok()) {
ret_st = st;
}
}
state_ = State::DISCONNECTED;
return ret_st;
}
Status S3::empty_bucket(const URI& bucket) const {
RETURN_NOT_OK(init_client());
auto uri_dir = bucket.add_trailing_slash();
return remove_dir(uri_dir);
}
Status S3::flush_object(const URI& uri) {
RETURN_NOT_OK(init_client());
if (!use_multipart_upload_) {
return flush_direct(uri);
}
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + uri.to_string())));
}
// Flush and delete file buffer. For multipart requests, we must
// continue even if 'flush_file_buffer' fails. In that scenario,
// we will send an abort request.
auto buff = (Buffer*)nullptr;
RETURN_NOT_OK(get_file_buffer(uri, &buff));
const Status flush_st = flush_file_buffer(uri, buff, true);
Aws::Http::URI aws_uri = uri.c_str();
std::string path_c_str = aws_uri.GetPath().c_str();
// Take a lock protecting 'multipart_upload_states_'.
UniqueReadLock unique_rl(&multipart_upload_rwlock_);
// Do nothing - empty object
auto state_iter = multipart_upload_states_.find(path_c_str);
if (state_iter == multipart_upload_states_.end()) {
RETURN_NOT_OK(flush_st);
return Status::Ok();
}
const MultiPartUploadState* state = &multipart_upload_states_.at(path_c_str);
// Lock multipart state
std::unique_lock<std::mutex> state_lck(state->mtx);
unique_rl.unlock();
if (state->st.ok()) {
Aws::S3::Model::CompleteMultipartUploadRequest complete_request =
make_multipart_complete_request(*state);
auto outcome = client_->CompleteMultipartUpload(complete_request);
if (!outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to flush S3 object ") + uri.c_str() +
outcome_error_message(outcome)));
}
auto bucket = state->bucket;
auto key = state->key;
// It is safe to unlock the state here
state_lck.unlock();
wait_for_object_to_propagate(move(bucket), move(key));
return finish_flush_object(std::move(outcome), uri, buff);
} else {
Aws::S3::Model::AbortMultipartUploadRequest abort_request =
make_multipart_abort_request(*state);
auto outcome = client_->AbortMultipartUpload(abort_request);
state_lck.unlock();
return finish_flush_object(std::move(outcome), uri, buff);
}
}
Aws::S3::Model::CompleteMultipartUploadRequest
S3::make_multipart_complete_request(const MultiPartUploadState& state) {
// Add all the completed parts (sorted by part number) to the upload object.
Aws::S3::Model::CompletedMultipartUpload completed_upload;
for (auto& tup : state.completed_parts) {
const Aws::S3::Model::CompletedPart& part = std::get<1>(tup);
completed_upload.AddParts(part);
}
Aws::S3::Model::CompleteMultipartUploadRequest complete_request;
complete_request.SetBucket(state.bucket);
complete_request.SetKey(state.key);
complete_request.SetUploadId(state.upload_id);
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
complete_request.SetRequestPayer(request_payer_);
return complete_request.WithMultipartUpload(std::move(completed_upload));
}
Aws::S3::Model::AbortMultipartUploadRequest S3::make_multipart_abort_request(
const MultiPartUploadState& state) {
Aws::S3::Model::AbortMultipartUploadRequest abort_request;
abort_request.SetBucket(state.bucket);
abort_request.SetKey(state.key);
abort_request.SetUploadId(state.upload_id);
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
abort_request.SetRequestPayer(request_payer_);
return abort_request;
}
template <typename R, typename E>
Status S3::finish_flush_object(
const Aws::Utils::Outcome<R, E>& outcome,
const URI& uri,
Buffer* const buff) {
Aws::Http::URI aws_uri = uri.c_str();
UniqueWriteLock unique_wl(&multipart_upload_rwlock_);
multipart_upload_states_.erase(aws_uri.GetPath().c_str());
unique_wl.unlock();
std::unique_lock<std::mutex> file_buffers_lck(file_buffers_mtx_);
file_buffers_.erase(uri.to_string());
file_buffers_lck.unlock();
tdb_delete(buff);
if (!outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to flush S3 object ") + uri.c_str() +
outcome_error_message(outcome)));
}
return Status::Ok();
}
Status S3::is_empty_bucket(const URI& bucket, bool* is_empty) const {
RETURN_NOT_OK(init_client());
bool exists;
RETURN_NOT_OK(is_bucket(bucket, &exists));
if (!exists)
return LOG_STATUS(Status_S3Error(
"Cannot check if bucket is empty; Bucket does not exist"));
Aws::Http::URI aws_uri = bucket.c_str();
Aws::S3::Model::ListObjectsRequest list_objects_request;
list_objects_request.SetBucket(aws_uri.GetAuthority());
list_objects_request.SetPrefix("");
list_objects_request.SetDelimiter("/");
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
list_objects_request.SetRequestPayer(request_payer_);
auto list_objects_outcome = client_->ListObjects(list_objects_request);
if (!list_objects_outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to list s3 objects in bucket ") + bucket.c_str() +
outcome_error_message(list_objects_outcome)));
}
*is_empty = list_objects_outcome.GetResult().GetContents().empty() &&
list_objects_outcome.GetResult().GetCommonPrefixes().empty();
return Status::Ok();
}
Status S3::is_bucket(const URI& uri, bool* const exists) const {
init_client();
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + uri.to_string())));
}
Aws::Http::URI aws_uri = uri.c_str();
Aws::S3::Model::HeadBucketRequest head_bucket_request;
head_bucket_request.SetBucket(aws_uri.GetAuthority());
auto head_bucket_outcome = client_->HeadBucket(head_bucket_request);
*exists = head_bucket_outcome.IsSuccess();
return Status::Ok();
}
Status S3::is_object(const URI& uri, bool* const exists) const {
init_client();
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + uri.to_string())));
}
Aws::Http::URI aws_uri = uri.c_str();
return is_object(aws_uri.GetAuthority(), aws_uri.GetPath(), exists);
}
Status S3::is_object(
const Aws::String& bucket_name,
const Aws::String& object_key,
bool* const exists) const {
init_client();
Aws::S3::Model::HeadObjectRequest head_object_request;
head_object_request.SetBucket(bucket_name);
head_object_request.SetKey(object_key);
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
head_object_request.SetRequestPayer(request_payer_);
auto head_object_outcome = client_->HeadObject(head_object_request);
*exists = head_object_outcome.IsSuccess();
return Status::Ok();
}
Status S3::is_dir(const URI& uri, bool* exists) const {
RETURN_NOT_OK(init_client());
// Potentially add `/` to the end of `uri`
auto uri_dir = uri.add_trailing_slash();
std::vector<std::string> paths;
RETURN_NOT_OK(ls(uri_dir, &paths, "/", 1));
*exists = (bool)paths.size();
return Status::Ok();
}
Status S3::ls(
const URI& prefix,
std::vector<std::string>* paths,
const std::string& delimiter,
int max_paths) const {
auto&& [st, entries] = ls_with_sizes(prefix, delimiter, max_paths);
RETURN_NOT_OK(st);
for (auto& fs : *entries) {
paths->emplace_back(fs.path().native());
}
return Status::Ok();
}
tuple<Status, optional<std::vector<directory_entry>>> S3::ls_with_sizes(
const URI& prefix, const std::string& delimiter, int max_paths) const {
RETURN_NOT_OK_TUPLE(init_client(), nullopt);
const auto prefix_dir = prefix.add_trailing_slash();
auto prefix_str = prefix_dir.to_string();
if (!prefix_dir.is_s3()) {
auto st = LOG_STATUS(
Status_S3Error(std::string("URI is not an S3 URI: " + prefix_str)));
return {st, nullopt};
}
Aws::Http::URI aws_uri = prefix_str.c_str();
auto aws_prefix = remove_front_slash(aws_uri.GetPath().c_str());
std::string aws_auth = aws_uri.GetAuthority().c_str();
Aws::S3::Model::ListObjectsRequest list_objects_request;
list_objects_request.SetBucket(aws_uri.GetAuthority());
list_objects_request.SetPrefix(aws_prefix.c_str());
list_objects_request.SetDelimiter(delimiter.c_str());
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
list_objects_request.SetRequestPayer(request_payer_);
std::vector<directory_entry> entries;
bool is_done = false;
while (!is_done) {
// Not requesting more items than needed
if (max_paths != -1)
list_objects_request.SetMaxKeys(
max_paths - static_cast<int>(entries.size()));
auto list_objects_outcome = client_->ListObjects(list_objects_request);
if (!list_objects_outcome.IsSuccess()) {
auto st = LOG_STATUS(Status_S3Error(
std::string("Error while listing with prefix '") + prefix_str +
"' and delimiter '" + delimiter + "'" +
outcome_error_message(list_objects_outcome)));
return {st, nullopt};
}
for (const auto& object : list_objects_outcome.GetResult().GetContents()) {
std::string file(object.GetKey().c_str());
uint64_t size = object.GetSize();
entries.emplace_back("s3://" + aws_auth + add_front_slash(file), size);
}
for (const auto& object :
list_objects_outcome.GetResult().GetCommonPrefixes()) {
std::string file(object.GetPrefix().c_str());
// For "directories" it doesn't seem possible to get a shallow size in
// S3, so the size of such an entry will be 0 in S3.
entries.emplace_back(
"s3://" + aws_auth + add_front_slash(remove_trailing_slash(file)), 0);
}
is_done =
!list_objects_outcome.GetResult().GetIsTruncated() ||
(max_paths != -1 && entries.size() >= static_cast<size_t>(max_paths));
if (!is_done) {
// The documentation states that "GetNextMarker" will be non-empty only
// when the delimiter in the request is non-empty. When the delimiter is
// non-empty, we must used the last returned key as the next marker.
assert(
!delimiter.empty() ||
!list_objects_outcome.GetResult().GetContents().empty());
Aws::String next_marker =
!delimiter.empty() ?
list_objects_outcome.GetResult().GetNextMarker() :
list_objects_outcome.GetResult().GetContents().back().GetKey();
assert(!next_marker.empty());
list_objects_request.SetMarker(std::move(next_marker));
}
}
return {Status::Ok(), entries};
}
Status S3::move_object(const URI& old_uri, const URI& new_uri) {
RETURN_NOT_OK(init_client());
RETURN_NOT_OK(copy_object(old_uri, new_uri));
RETURN_NOT_OK(remove_object(old_uri));
return Status::Ok();
}
Status S3::move_dir(const URI& old_uri, const URI& new_uri) {
RETURN_NOT_OK(init_client());
std::vector<std::string> paths;
RETURN_NOT_OK(ls(old_uri, &paths, ""));
for (const auto& path : paths) {
auto suffix = path.substr(old_uri.to_string().size());
auto new_path = new_uri.join_path(suffix);
RETURN_NOT_OK(move_object(URI(path), URI(new_path)));
}
return Status::Ok();
}
Status S3::copy_file(const URI& old_uri, const URI& new_uri) {
RETURN_NOT_OK(init_client());
RETURN_NOT_OK(copy_object(old_uri, new_uri));
return Status::Ok();
}
Status S3::copy_dir(const URI& old_uri, const URI& new_uri) {
RETURN_NOT_OK(init_client());
std::string old_uri_string = old_uri.to_string();
std::vector<std::string> paths;
RETURN_NOT_OK(ls(old_uri, &paths));
while (!paths.empty()) {
std::string file_name_abs = paths.front();
URI file_name_uri = URI(file_name_abs);
std::string file_name = file_name_abs.substr(old_uri_string.length());
paths.erase(paths.begin());
bool dir_exists;
RETURN_NOT_OK(is_dir(file_name_uri, &dir_exists));
if (dir_exists) {
std::vector<std::string> child_paths;
RETURN_NOT_OK(ls(file_name_uri, &child_paths));
paths.insert(paths.end(), child_paths.begin(), child_paths.end());
} else {
std::string new_path_string = new_uri.to_string() + file_name;
URI new_path_uri = URI(new_path_string);
RETURN_NOT_OK(copy_object(file_name_uri, new_path_uri));
}
}
return Status::Ok();
}
Status S3::object_size(const URI& uri, uint64_t* nbytes) const {
RETURN_NOT_OK(init_client());
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + uri.to_string())));
}
Aws::Http::URI aws_uri = uri.to_string().c_str();
auto aws_path = remove_front_slash(aws_uri.GetPath().c_str());
Aws::S3::Model::HeadObjectRequest head_object_request;
head_object_request.SetBucket(aws_uri.GetAuthority());
head_object_request.SetKey(aws_path.c_str());
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
head_object_request.SetRequestPayer(request_payer_);
auto head_object_outcome = client_->HeadObject(head_object_request);
if (!head_object_outcome.IsSuccess())
return LOG_STATUS(Status_S3Error(
"Cannot retrieve S3 object size; Error while listing file " +
uri.to_string() + outcome_error_message(head_object_outcome)));
*nbytes =
static_cast<uint64_t>(head_object_outcome.GetResult().GetContentLength());
return Status::Ok();
}
Status S3::read(
const URI& uri,
const off_t offset,
void* const buffer,
const uint64_t length,
const uint64_t read_ahead_length,
uint64_t* const length_returned) const {
RETURN_NOT_OK(init_client());
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + uri.to_string())));
}
Aws::Http::URI aws_uri = uri.c_str();
Aws::S3::Model::GetObjectRequest get_object_request;
get_object_request.WithBucket(aws_uri.GetAuthority())
.WithKey(aws_uri.GetPath());
get_object_request.SetRange(
("bytes=" + std::to_string(offset) + "-" +
std::to_string(offset + length + read_ahead_length - 1))
.c_str());
get_object_request.SetResponseStreamFactory(
[buffer, length, read_ahead_length]() {
return Aws::New<PreallocatedIOStream>(
constants::s3_allocation_tag.c_str(),
buffer,
length + read_ahead_length);
});
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
get_object_request.SetRequestPayer(request_payer_);
auto get_object_outcome = client_->GetObject(get_object_request);
if (!get_object_outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to read S3 object ") + uri.c_str() +
outcome_error_message(get_object_outcome)));
}
*length_returned =
static_cast<uint64_t>(get_object_outcome.GetResult().GetContentLength());
if (*length_returned < length) {
return LOG_STATUS(Status_S3Error(
std::string("Read operation returned different size of bytes ") +
std::to_string(*length_returned) + " vs " + std::to_string(length)));
}
return Status::Ok();
}
Status S3::remove_object(const URI& uri) const {
RETURN_NOT_OK(init_client());
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(
std::string("URI is not an S3 URI: " + uri.to_string())));
}
Aws::Http::URI aws_uri = uri.to_string().c_str();
Aws::S3::Model::DeleteObjectRequest delete_object_request;
delete_object_request.SetBucket(aws_uri.GetAuthority());
delete_object_request.SetKey(aws_uri.GetPath());
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
delete_object_request.SetRequestPayer(request_payer_);
auto delete_object_outcome = client_->DeleteObject(delete_object_request);
if (!delete_object_outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Failed to delete S3 object '") + uri.c_str() +
outcome_error_message(delete_object_outcome)));
}
wait_for_object_to_be_deleted(
delete_object_request.GetBucket(), delete_object_request.GetKey());
return Status::Ok();
}
Status S3::remove_dir(const URI& uri) const {
RETURN_NOT_OK(init_client());
std::vector<std::string> paths;
RETURN_NOT_OK(ls(uri, &paths, ""));
auto status = parallel_for(vfs_thread_pool_, 0, paths.size(), [&](size_t i) {
RETURN_NOT_OK(remove_object(URI(paths[i])));
return Status::Ok();
});
RETURN_NOT_OK(status);
return Status::Ok();
}
Status S3::touch(const URI& uri) const {
RETURN_NOT_OK(init_client());
if (!uri.is_s3()) {
return LOG_STATUS(Status_S3Error(std::string(
"Cannot create file; URI is not an S3 URI: " + uri.to_string())));
}
if (uri.to_string().back() == '/') {
return LOG_STATUS(Status_S3Error(std::string(
"Cannot create file; URI is a directory: " + uri.to_string())));
}
bool exists;
RETURN_NOT_OK(is_object(uri, &exists));
if (exists) {
return Status::Ok();
}
Aws::Http::URI aws_uri = uri.c_str();
Aws::S3::Model::PutObjectRequest put_object_request;
put_object_request.WithKey(aws_uri.GetPath())
.WithBucket(aws_uri.GetAuthority());
auto request_stream =
Aws::MakeShared<Aws::StringStream>(constants::s3_allocation_tag.c_str());
put_object_request.SetBody(request_stream);
if (request_payer_ != Aws::S3::Model::RequestPayer::NOT_SET)
put_object_request.SetRequestPayer(request_payer_);
if (sse_ != Aws::S3::Model::ServerSideEncryption::NOT_SET)
put_object_request.SetServerSideEncryption(sse_);
if (!sse_kms_key_id_.empty())
put_object_request.SetSSEKMSKeyId(Aws::String(sse_kms_key_id_.c_str()));
if (object_canned_acl_ != Aws::S3::Model::ObjectCannedACL::NOT_SET) {
put_object_request.SetACL(object_canned_acl_);
}
auto put_object_outcome = client_->PutObject(put_object_request);
if (!put_object_outcome.IsSuccess()) {
return LOG_STATUS(Status_S3Error(
std::string("Cannot touch object '") + uri.c_str() +
outcome_error_message(put_object_outcome)));
}
wait_for_object_to_propagate(
put_object_request.GetBucket(), put_object_request.GetKey());
return Status::Ok();
}
Status S3::write(const URI& uri, const void* buffer, uint64_t length) {
RETURN_NOT_OK(init_client());