-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
S3ObjectTask.java
1422 lines (1309 loc) · 64.1 KB
/
S3ObjectTask.java
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
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.proxy.s3;
import alluxio.AlluxioURI;
import alluxio.Constants;
import alluxio.client.WriteType;
import alluxio.client.file.FileInStream;
import alluxio.client.file.FileOutStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.conf.Configuration;
import alluxio.conf.PropertyKey;
import alluxio.exception.AlluxioException;
import alluxio.exception.DirectoryNotEmptyException;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.grpc.Bits;
import alluxio.grpc.CreateDirectoryPOptions;
import alluxio.grpc.CreateFilePOptions;
import alluxio.grpc.DeletePOptions;
import alluxio.grpc.PMode;
import alluxio.grpc.RenamePOptions;
import alluxio.grpc.S3SyntaxOptions;
import alluxio.grpc.SetAttributePOptions;
import alluxio.grpc.XAttrPropagationStrategy;
import alluxio.metrics.MetricKey;
import alluxio.metrics.MetricsSystem;
import alluxio.proto.journal.File;
import alluxio.util.ThreadUtils;
import alluxio.web.ProxyWebServer;
import com.codahale.metrics.Timer;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.common.base.Preconditions;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.RateLimiter;
import com.google.protobuf.ByteString;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* S3 Tasks to handle object level request.
* (bucket and object name provided in the request)
*/
public class S3ObjectTask extends S3BaseTask {
private static final Logger LOG = LoggerFactory.getLogger(S3ObjectTask.class);
protected S3ObjectTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(mHandler.getBucket(), () -> {
throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
});
}
/**
* Concatenate bucket and object to make a full path.
* @return full path
*/
public String getObjectTaskResource() {
return mHandler.getBucket() + AlluxioURI.SEPARATOR + mHandler.getObject();
}
/**
* Factory for getting a S3ObjectTask.
*/
public static final class Factory {
/**
* Marshall the request and create corresponding object level S3 task.
* @param handler
* @return S3ObjectTask
*/
public static S3ObjectTask create(S3Handler handler) {
switch (handler.getHTTPVerb()) {
case "GET":
if (handler.getQueryParameter("uploadId") != null) {
return new ListPartsTask(handler, OpType.ListParts);
} else if (handler.getQueryParameter("tagging") != null) {
return new GetObjectTaggingTask(handler, OpType.GetObjectTagging);
} else {
return new GetObjectTask(handler, OpType.GetObject);
}
case "PUT":
if (handler.getQueryParameter("tagging") != null) {
return new PutObjectTaggingTask(handler, OpType.PutObjectTagging);
} else if (handler.getQueryParameter("uploadId") != null) {
if (handler.getHeader(S3Constants.S3_COPY_SOURCE_HEADER) != null) {
return new UploadPartTask(handler, OpType.UploadPartCopy);
}
return new UploadPartTask(handler, OpType.UploadPart);
} else {
if (handler.getHeader(S3Constants.S3_COPY_SOURCE_HEADER) != null) {
return new CopyObjectTask(handler, OpType.CopyObject);
}
return new PutObjectTask(handler, OpType.PutObject);
}
case "POST":
if (handler.getQueryParameter("uploads") != null) {
return new CreateMultipartUploadTask(handler, OpType.CreateMultipartUpload);
} else if (handler.getQueryParameter("uploadId") != null) {
return new CompleteMultipartUploadTask(handler, OpType.CompleteMultipartUpload);
}
break;
case "HEAD":
return new HeadObjectTask(handler, OpType.HeadObject);
case "DELETE":
if (handler.getQueryParameter("uploadId") != null) {
return new AbortMultipartUploadTask(handler, OpType.AbortMultipartUpload);
} else if (handler.getQueryParameter("tagging") != null) {
return new DeleteObjectTaggingTask(handler, OpType.DeleteObjectTagging);
} else {
return new DeleteObjectTask(handler, OpType.DeleteObject);
}
default:
return new S3ObjectTask(handler, OpType.Unsupported);
}
return new S3ObjectTask(handler, OpType.Unsupported);
}
}
private static final class ListPartsTask extends S3ObjectTask {
public ListPartsTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
final String uploadId = mHandler.getQueryParameter("uploadId");
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + mHandler.getBucket());
try (S3AuditContext auditContext = mHandler.createAuditContext(
mOPType.name(), user, mHandler.getBucket(), mHandler.getObject())) {
S3RestUtils.checkPathIsAlluxioDirectory(userFs, bucketPath, auditContext);
AlluxioURI tmpDir = new AlluxioURI(S3RestUtils.getMultipartTemporaryDirForObject(
bucketPath, mHandler.getObject(), uploadId));
try {
S3RestUtils.checkStatusesForUploadId(mHandler.getMetaFS(), userFs, tmpDir, uploadId);
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception((e instanceof FileDoesNotExistException)
? new S3Exception(mHandler.getObject(), S3ErrorCode.NO_SUCH_UPLOAD) : e,
mHandler.getObject(), auditContext);
}
try {
List<URIStatus> statuses = userFs.listStatus(tmpDir);
statuses.sort(new S3RestUtils.URIStatusNameComparator());
List<ListPartsResult.Part> parts = new ArrayList<>();
for (URIStatus status : statuses) {
parts.add(ListPartsResult.Part.fromURIStatus(status));
}
ListPartsResult result = new ListPartsResult();
result.setBucket(bucketPath);
result.setKey(mHandler.getObject());
result.setUploadId(uploadId);
result.setParts(parts);
return result;
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, tmpDir.getPath(), auditContext);
}
}
});
}
} // end of ListPartsTask
private static final class GetObjectTaggingTask extends S3ObjectTask {
public GetObjectTaggingTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + mHandler.getBucket());
String objectPath = bucketPath + AlluxioURI.SEPARATOR + mHandler.getObject();
AlluxioURI uri = new AlluxioURI(objectPath);
try (S3AuditContext auditContext = mHandler.createAuditContext(
mOPType.name(), user, mHandler.getBucket(), mHandler.getObject())) {
S3RestUtils.checkPathIsAlluxioDirectory(userFs, bucketPath, auditContext);
try {
TaggingData tagData = S3RestUtils.deserializeTags(userFs.getStatus(uri).getXAttr());
LOG.debug("GetObjectTagging tagData={}", tagData);
return tagData != null ? tagData : new TaggingData();
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
});
}
} // end of GetObjectTaggingTask
private static final class PutObjectTaggingTask extends S3ObjectTask {
private PutObjectTaggingTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + mHandler.getBucket());
try (S3AuditContext auditContext = mHandler.createAuditContext(
mOPType.name(), user, mHandler.getBucket(), mHandler.getObject())) {
S3RestUtils.checkPathIsAlluxioDirectory(userFs, bucketPath, auditContext);
String objectPath = bucketPath + AlluxioURI.SEPARATOR + mHandler.getObject();
AlluxioURI objectUri = new AlluxioURI(objectPath);
TaggingData tagData = null;
try {
tagData = new XmlMapper().readerFor(TaggingData.class)
.readValue(mHandler.getInputStream());
} catch (IOException e) {
if (e.getCause() instanceof S3Exception) {
throw S3RestUtils.toObjectS3Exception((S3Exception) e.getCause(), objectPath,
auditContext);
}
auditContext.setSucceeded(false);
throw new S3Exception(e, objectPath, S3ErrorCode.MALFORMED_XML);
}
LOG.debug("PutObjectTagging tagData={}", tagData);
Map<String, ByteString> xattrMap = new HashMap<>();
if (tagData != null) {
try {
xattrMap.put(S3Constants.TAGGING_XATTR_KEY, TaggingData.serialize(tagData));
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
try {
SetAttributePOptions attrPOptions = SetAttributePOptions.newBuilder()
.putAllXattr(xattrMap)
.setXattrUpdateStrategy(File.XAttrUpdateStrategy.UNION_REPLACE)
.build();
userFs.setAttribute(objectUri, attrPOptions);
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
return Response.ok().build();
}
});
}
} // end of PutObjectTaggingTask
private static final class GetObjectTask extends S3ObjectTask {
public GetObjectTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
final String range = mHandler.getHeaderOrDefault("Range", null);
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + mHandler.getBucket());
String objectPath = bucketPath + AlluxioURI.SEPARATOR + mHandler.getObject();
AlluxioURI objectUri = new AlluxioURI(objectPath);
try (S3AuditContext auditContext = mHandler.createAuditContext(
mOPType.name(), user, mHandler.getBucket(), mHandler.getObject())) {
try {
URIStatus status = userFs.getStatus(objectUri);
FileInStream is = userFs.openFile(objectUri);
S3RangeSpec s3Range = S3RangeSpec.Factory.create(range);
RangeFileInStream ris = RangeFileInStream.Factory.create(
is, status.getLength(), s3Range);
InputStream inputStream;
RateLimiter globalRateLimiter = (RateLimiter) mHandler.getServletContext()
.getAttribute(ProxyWebServer.GLOBAL_RATE_LIMITER_SERVLET_RESOURCE_KEY);
long rate = (long) mHandler.getMetaFS().getConf()
.getInt(PropertyKey.PROXY_S3_SINGLE_CONNECTION_READ_RATE_LIMIT_MB) * Constants.MB;
RateLimiter currentRateLimiter = S3RestUtils.createRateLimiter(rate).orElse(null);
if (currentRateLimiter == null && globalRateLimiter == null) {
inputStream = ris;
} else {
inputStream = new RateLimitInputStream(ris, globalRateLimiter, currentRateLimiter);
}
Response.ResponseBuilder res = Response.ok(inputStream,
MediaType.APPLICATION_OCTET_STREAM_TYPE)
.lastModified(new Date(status.getLastModificationTimeMs()))
.header(S3Constants.S3_CONTENT_LENGTH_HEADER,
s3Range.getLength(status.getLength()));
// Check range
if (s3Range.isValid()) {
res.status(Response.Status.PARTIAL_CONTENT)
.header(S3Constants.S3_ACCEPT_RANGES_HEADER, S3Constants.S3_ACCEPT_RANGES_VALUE)
.header(S3Constants.S3_CONTENT_RANGE_HEADER,
s3Range.getRealRange(status.getLength()));
}
// Check for the object's ETag
String entityTag = S3RestUtils.getEntityTag(status);
if (entityTag != null) {
res.header(S3Constants.S3_ETAG_HEADER, entityTag);
} else {
LOG.debug("Failed to find ETag for object: " + objectPath);
}
// Check if the object had a specified "Content-Type"
res.type(S3RestUtils.deserializeContentType(status.getXAttr()));
// Check if object had tags, if so we need to return the count
// in the header "x-amz-tagging-count"
TaggingData tagData = S3RestUtils.deserializeTags(status.getXAttr());
if (tagData != null) {
int taggingCount = tagData.getTagMap().size();
if (taggingCount > 0) {
res.header(S3Constants.S3_TAGGING_COUNT_HEADER, taggingCount);
}
}
return res.build();
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
});
}
} // end of GetObjectTask
private static final class HeadObjectTask extends S3ObjectTask {
public HeadObjectTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
Preconditions.checkNotNull(mHandler.getBucket(), "required 'bucket' parameter is missing");
Preconditions.checkNotNull(mHandler.getObject(), "required 'object' parameter is missing");
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + mHandler.getBucket());
String objectPath = bucketPath + AlluxioURI.SEPARATOR + mHandler.getObject();
AlluxioURI objectUri = new AlluxioURI(objectPath);
try (S3AuditContext auditContext = mHandler.createAuditContext(
mOPType.name(), user, mHandler.getBucket(), mHandler.getObject())) {
try {
URIStatus status = userFs.getStatus(objectUri);
if (status.isFolder() && !mHandler.getObject().endsWith(AlluxioURI.SEPARATOR)) {
throw new FileDoesNotExistException(status.getPath() + " is a directory");
}
Response.ResponseBuilder res = Response.ok()
.lastModified(new Date(status.getLastModificationTimeMs()))
.header(S3Constants.S3_CONTENT_LENGTH_HEADER,
status.isFolder() ? 0 : status.getLength());
// Check for the object's ETag
String entityTag = S3RestUtils.getEntityTag(status);
if (entityTag != null) {
res.header(S3Constants.S3_ETAG_HEADER, entityTag);
} else {
LOG.debug("Failed to find ETag for object: " + objectPath);
}
// Check if the object had a specified "Content-Type"
res.type(S3RestUtils.deserializeContentType(status.getXAttr()));
return res.build();
} catch (FileDoesNotExistException e) {
// must be null entity (content length 0) for S3A Filesystem
return Response.status(404).entity(null).header("Content-Length", "0").build();
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
});
}
} // end of HeadObjectTask
private static final class CopyObjectTask extends PutObjectTask {
public CopyObjectTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
final String bucket = mHandler.getBucket();
final String object = mHandler.getObject();
Preconditions.checkNotNull(bucket, "required 'bucket' parameter is missing");
Preconditions.checkNotNull(object, "required 'object' parameter is missing");
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + bucket);
String objectPath = bucketPath + AlluxioURI.SEPARATOR + object;
final String copySourceParam = mHandler.getHeader(S3Constants.S3_COPY_SOURCE_HEADER);
String copySource = !copySourceParam.startsWith(AlluxioURI.SEPARATOR)
? AlluxioURI.SEPARATOR + copySourceParam : copySourceParam;
try (S3AuditContext auditContext = mHandler.createAuditContext(
mOPType.name(), user, mHandler.getBucket(), mHandler.getObject())) {
if (objectPath.endsWith(AlluxioURI.SEPARATOR)) {
createDirectory(objectPath, userFs, auditContext);
}
AlluxioURI objectUri = new AlluxioURI(objectPath);
// Populate the xattr Map with the metadata tags if provided
Map<String, ByteString> xattrMap = new HashMap<>();
final String taggingHeader = mHandler.getHeader(S3Constants.S3_TAGGING_HEADER);
S3RestUtils.populateTaggingInXAttr(xattrMap, taggingHeader, auditContext, objectPath);
// populate the xAttr map with the "Content-Type" header
final String contentTypeHeader = mHandler.getHeader(S3Constants.S3_CONTENT_TYPE_HEADER);
S3RestUtils.populateContentTypeInXAttr(xattrMap, contentTypeHeader);
CreateFilePOptions filePOptions =
CreateFilePOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setWriteType(S3RestUtils.getS3WriteType())
.putAllXattr(xattrMap)
.setXattrPropStrat(XAttrPropagationStrategy.LEAF_NODE)
.setOverwrite(true)
.build();
try {
copySource = URLDecoder.decode(copySource, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw S3RestUtils.toObjectS3Exception(ex, objectPath, auditContext);
}
URIStatus status = null;
CreateFilePOptions.Builder copyFilePOptionsBuilder = CreateFilePOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build());
// Handle metadata directive
final String metadataDirective = mHandler.getHeader(
S3Constants.S3_METADATA_DIRECTIVE_HEADER);
if (StringUtils.equals(metadataDirective, S3Constants.Directive.REPLACE.name())
&& filePOptions.getXattrMap().containsKey(S3Constants.CONTENT_TYPE_XATTR_KEY)) {
copyFilePOptionsBuilder.putXattr(S3Constants.CONTENT_TYPE_XATTR_KEY,
filePOptions.getXattrMap().get(S3Constants.CONTENT_TYPE_XATTR_KEY));
} else { // defaults to COPY
try {
status = userFs.getStatus(new AlluxioURI(copySource));
if (status.getFileInfo().getXAttr() != null) {
copyFilePOptionsBuilder.putXattr(S3Constants.CONTENT_TYPE_XATTR_KEY,
ByteString.copyFrom(status.getFileInfo().getXAttr().getOrDefault(
S3Constants.CONTENT_TYPE_XATTR_KEY,
MediaType.APPLICATION_OCTET_STREAM.getBytes(S3Constants.HEADER_CHARSET))));
}
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
// Handle tagging directive
final String taggingDirective = mHandler.getHeader(
S3Constants.S3_TAGGING_DIRECTIVE_HEADER);
if (StringUtils.equals(taggingDirective, S3Constants.Directive.REPLACE.name())
&& filePOptions.getXattrMap().containsKey(S3Constants.TAGGING_XATTR_KEY)) {
copyFilePOptionsBuilder.putXattr(S3Constants.TAGGING_XATTR_KEY,
filePOptions.getXattrMap().get(S3Constants.TAGGING_XATTR_KEY));
} else { // defaults to COPY
try {
if (status == null) {
status = userFs.getStatus(new AlluxioURI(copySource));
}
if (status.getFileInfo().getXAttr() != null
&& status.getFileInfo().getXAttr()
.containsKey(S3Constants.TAGGING_XATTR_KEY)) {
copyFilePOptionsBuilder.putXattr(S3Constants.TAGGING_XATTR_KEY,
TaggingData.serialize(S3RestUtils.deserializeTags(status.getXAttr())));
}
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
String entityTag = copyObject(userFs, auditContext,
objectPath, copySource, copyFilePOptionsBuilder.build());
return new CopyObjectResult(entityTag, System.currentTimeMillis());
}
});
}
} // end of CopyObjectTask
private static class PutObjectTask extends S3ObjectTask {
// For both PutObject and UploadPart
public PutObjectTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
/**
* Common function for create object.
* TODO(lucy) needs to change the central logic here of how we do overwrite
* current logic introduces unhandled race conditions
* @param objectPath
* @param userFs
* @param createFilePOptions
* @param auditContext
* @return Response
* @throws S3Exception
*/
public Response createObject(String objectPath, FileSystem userFs,
CreateFilePOptions createFilePOptions, S3AuditContext auditContext)
throws S3Exception {
AlluxioURI objectUri = new AlluxioURI(objectPath);
final String decodedLengthHeader = mHandler.getHeader("x-amz-decoded-content-length");
final String contentLength = mHandler.getHeader("Content-Length");
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
// The request body can be in the aws-chunked encoding format, or not encoded at all
// determine if it's encoded, and then which parts of the stream to read depending on
// the encoding type.
boolean isChunkedEncoding = decodedLengthHeader != null;
long toRead;
InputStream readStream = mHandler.getInputStream();
if (isChunkedEncoding) {
toRead = Long.parseLong(decodedLengthHeader);
readStream = new ChunkedEncodingInputStream(readStream);
} else {
toRead = Long.parseLong(contentLength);
}
FileOutStream os = userFs.createFile(objectUri, createFilePOptions);
try (DigestOutputStream digestOutputStream = new DigestOutputStream(os, md5)) {
long read = ByteStreams.copy(ByteStreams.limit(readStream, toRead),
digestOutputStream);
if (read < toRead) {
throw new IOException(String.format(
"Failed to read all required bytes from the stream. Read %d/%d",
read, toRead));
}
}
byte[] digest = md5.digest();
String base64Digest = BaseEncoding.base64().encode(digest);
final String contentMD5 = mHandler.getHeader("Content-MD5");
if (contentMD5 != null && !contentMD5.equals(base64Digest)) {
// The object may be corrupted, delete the written object and return an error.
try {
userFs.delete(objectUri, DeletePOptions.newBuilder().setRecursive(true).build());
} catch (Exception e2) {
// intend to continue and return BAD_DIGEST S3Exception.
}
throw new S3Exception(objectUri.getPath(), S3ErrorCode.BAD_DIGEST);
}
String entityTag = Hex.encodeHexString(digest);
// persist the ETag via xAttr
// TODO(czhu): try to compute the ETag prior to creating the file
// to reduce total RPC RTT
S3RestUtils.setEntityTag(userFs, objectUri, entityTag);
return Response.ok().header(S3Constants.S3_ETAG_HEADER, entityTag).build();
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
/**
* Common util func to create directory in alluxio.
* @param objectPath
* @param userFs
* @param auditContext
* @return Response
* @throws S3Exception
*/
public Response createDirectory(String objectPath, FileSystem userFs,
S3AuditContext auditContext)
throws S3Exception {
// Need to create a folder
// TODO(czhu): verify S3 behaviour when ending an object path with a delimiter
// - this is a convenience method for the Alluxio fs which does not have a
// direct counterpart for S3, since S3 does not have "folders" as actual objects
try {
CreateDirectoryPOptions dirOptions = CreateDirectoryPOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setAllowExists(true)
.build();
userFs.createDirectory(new AlluxioURI(objectPath), dirOptions);
} catch (FileAlreadyExistsException e) {
// ok if directory already exists the user wanted to create it anyway
LOG.warn("attempting to create dir which already exists");
} catch (IOException | AlluxioException e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
return Response.ok().build();
}
/**
* Common func for copy from a source path to target path.
* @param userFs
* @param auditContext
* @param targetPath
* @param sourcePath
* @param copyFilePOption
* @return entityTag(Etag)
* @throws S3Exception
*/
public String copyObject(FileSystem userFs, S3AuditContext auditContext,
String targetPath, String sourcePath,
CreateFilePOptions copyFilePOption)
throws S3Exception {
AlluxioURI objectUri = new AlluxioURI(targetPath);
if (sourcePath.equals(targetPath)) {
// do not need to copy a file to itself, unless we are changing file attributes
// TODO(czhu): support changing metadata via CopyObject to self,
// verify for UploadPartCopy
auditContext.setSucceeded(false);
throw new S3Exception("Copying an object to itself invalid.",
targetPath, S3ErrorCode.INVALID_REQUEST);
}
try (FileInStream in = userFs.openFile(new AlluxioURI(sourcePath));
FileOutStream out = userFs.createFile(objectUri, copyFilePOption)) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
try (DigestOutputStream digestOut = new DigestOutputStream(out, md5)) {
IOUtils.copyLarge(in, digestOut, new byte[8 * Constants.MB]);
byte[] digest = md5.digest();
String entityTag = Hex.encodeHexString(digest);
// persist the ETag via xAttr
// TODO(czhu): compute the ETag prior to creating the file to reduce total RPC RTT
S3RestUtils.setEntityTag(userFs, objectUri, entityTag);
return entityTag;
} catch (IOException e) {
try {
out.cancel();
} catch (Throwable t2) {
e.addSuppressed(t2);
}
throw e;
}
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, targetPath, auditContext);
}
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
// PutObject / UploadPart ...
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
final String bucket = mHandler.getBucket();
final String object = mHandler.getObject();
Preconditions.checkNotNull(bucket, "required 'bucket' parameter is missing");
Preconditions.checkNotNull(object, "required 'object' parameter is missing");
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + bucket);
try (S3AuditContext auditContext =
mHandler.createAuditContext(mOPType.name(), user, bucket, object)) {
S3RestUtils.checkPathIsAlluxioDirectory(userFs, bucketPath, auditContext);
String objectPath = bucketPath + AlluxioURI.SEPARATOR + object;
if (objectPath.endsWith(AlluxioURI.SEPARATOR)) {
return createDirectory(objectPath, userFs, auditContext);
}
AlluxioURI objectUri = new AlluxioURI(objectPath);
// Populate the xattr Map with the metadata tags if provided
Map<String, ByteString> xattrMap = new HashMap<>();
final String taggingHeader = mHandler.getHeader(S3Constants.S3_TAGGING_HEADER);
S3RestUtils.populateTaggingInXAttr(xattrMap, taggingHeader, auditContext, objectPath);
// populate the xAttr map with the "Content-Type" header
final String contentTypeHeader = mHandler.getHeader(S3Constants.S3_CONTENT_TYPE_HEADER);
S3RestUtils.populateContentTypeInXAttr(xattrMap, contentTypeHeader);
CreateFilePOptions filePOptions =
CreateFilePOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setWriteType(S3RestUtils.getS3WriteType())
.putAllXattr(xattrMap).setXattrPropStrat(XAttrPropagationStrategy.LEAF_NODE)
.setOverwrite(true)
.build();
return createObject(objectPath, userFs, filePOptions, auditContext);
}
});
}
} // end of PutObjectTask
private static final class UploadPartTask extends PutObjectTask {
public UploadPartTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
// UploadPart related params
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
final String bucket = mHandler.getBucket();
final String object = mHandler.getObject();
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + bucket);
final String partNumberStr = mHandler.getQueryParameter("partNumber");
Integer partNumber = null;
if (StringUtils.isNotEmpty(partNumberStr)) {
try {
partNumber = Integer.parseInt(partNumberStr);
} catch (Exception ex) {
return new S3Exception(ex, object, S3ErrorCode.INVALID_ARGUMENT);
}
}
final String uploadId = mHandler.getQueryParameter("uploadId");
Preconditions.checkNotNull(partNumber, "required 'partNumber' parameter is missing");
Preconditions.checkNotNull(partNumber, "required 'uploadId' parameter is missing");
try (S3AuditContext auditContext =
mHandler.createAuditContext(mOPType.name(), user, bucket, object)) {
// This object is part of a multipart upload, should be uploaded into the temporary
// directory first.
String tmpDir =
S3RestUtils.getMultipartTemporaryDirForObject(bucketPath, object, uploadId);
try {
S3RestUtils.checkStatusesForUploadId(
mHandler.getMetaFS(), userFs, new AlluxioURI(tmpDir), uploadId);
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception((e instanceof FileDoesNotExistException)
? new S3Exception(object, S3ErrorCode.NO_SUCH_UPLOAD) : e,
object, auditContext);
}
String objectPath = tmpDir + AlluxioURI.SEPARATOR + partNumber;
// eg: /bucket/folder/object_<uploadId>/<partNumber>
// UploadPartCopy with source from another object
if (mHandler.getHeader(S3Constants.S3_COPY_SOURCE_HEADER) != null) {
final String copySourceParam = mHandler.getHeader(S3Constants.S3_COPY_SOURCE_HEADER);
String copySource = !copySourceParam.startsWith(AlluxioURI.SEPARATOR)
? AlluxioURI.SEPARATOR + copySourceParam : copySourceParam;
try {
copySource = URLDecoder.decode(copySource, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw S3RestUtils.toObjectS3Exception(ex, objectPath, auditContext);
}
CreateFilePOptions.Builder copyFilePOptionsBuilder = CreateFilePOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setOverwrite(true);
String entityTag = copyObject(userFs, auditContext, objectPath,
copySource, copyFilePOptionsBuilder.build());
return new CopyPartResult(entityTag);
}
// UploadPart with source from http body
CreateFilePOptions filePOptions =
CreateFilePOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setWriteType(S3RestUtils.getS3WriteType())
.setOverwrite(true)
.build();
return createObject(objectPath, userFs, filePOptions, auditContext);
}
});
}
} // end of UploadPartTask
private static final class CreateMultipartUploadTask extends S3ObjectTask {
public CreateMultipartUploadTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public Response continueTask() {
return S3RestUtils.call(getObjectTaskResource(), () -> {
// CreateMultipartUploadTask ...
final String user = mHandler.getUser();
final FileSystem userFs = S3RestUtils.createFileSystemForUser(user, mHandler.getMetaFS());
final String bucket = mHandler.getBucket();
final String object = mHandler.getObject();
String bucketPath = S3RestUtils.parsePath(AlluxioURI.SEPARATOR + bucket);
String objectPath = bucketPath + AlluxioURI.SEPARATOR + object;
// Populate the xattr Map with the metadata tags if provided
Map<String, ByteString> xattrMap = new HashMap<>();
TaggingData tagData = null;
final String taggingHeader = mHandler.getHeader(S3Constants.S3_TAGGING_HEADER);
final String contentTypeHeader = mHandler.getHeader(S3Constants.S3_CONTENT_TYPE_HEADER);
try (S3AuditContext auditContext = mHandler.createAuditContext(
"initiateMultipartUpload", user, bucket, object)) {
S3RestUtils.checkPathIsAlluxioDirectory(userFs, bucketPath, auditContext);
if (taggingHeader != null) { // Parse the tagging header if it exists
try {
tagData = S3RestUtils.deserializeTaggingHeader(
taggingHeader, S3Handler.MAX_HEADER_METADATA_SIZE);
xattrMap.put(S3Constants.TAGGING_XATTR_KEY, TaggingData.serialize(tagData));
} catch (S3Exception e) {
auditContext.setSucceeded(false);
throw e; // rethrow
} catch (IllegalArgumentException e) {
if (e.getCause() instanceof S3Exception) {
throw S3RestUtils.toObjectS3Exception((S3Exception) e.getCause(), objectPath,
auditContext);
}
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
LOG.debug("InitiateMultipartUpload tagData={}", tagData);
}
try {
// Find an unused UUID
String uploadId;
do {
uploadId = UUID.randomUUID().toString();
} while (mHandler.getMetaFS().exists(
new AlluxioURI(S3RestUtils.getMultipartMetaFilepathForUploadId(uploadId))));
// Create the directory containing the upload parts
AlluxioURI multipartTemporaryDir = new AlluxioURI(
S3RestUtils.getMultipartTemporaryDirForObject(bucketPath, object, uploadId));
userFs.createDirectory(multipartTemporaryDir, CreateDirectoryPOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setWriteType(S3RestUtils.getS3WriteType()).build());
// Create the Alluxio multipart upload metadata file
if (contentTypeHeader != null) {
xattrMap.put(S3Constants.CONTENT_TYPE_XATTR_KEY,
ByteString.copyFrom(contentTypeHeader, S3Constants.HEADER_CHARSET));
}
xattrMap.put(S3Constants.UPLOADS_BUCKET_XATTR_KEY,
ByteString.copyFrom(mHandler.getBucket(), S3Constants.XATTR_STR_CHARSET));
xattrMap.put(S3Constants.UPLOADS_OBJECT_XATTR_KEY,
ByteString.copyFrom(mHandler.getObject(), S3Constants.XATTR_STR_CHARSET));
xattrMap.put(S3Constants.UPLOADS_FILE_ID_XATTR_KEY, ByteString.copyFrom(
Longs.toByteArray(userFs.getStatus(multipartTemporaryDir).getFileId())));
mHandler.getMetaFS().createFile(
new AlluxioURI(S3RestUtils.getMultipartMetaFilepathForUploadId(uploadId)),
CreateFilePOptions.newBuilder()
.setRecursive(true)
.setMode(PMode.newBuilder()
.setOwnerBits(Bits.ALL)
.setGroupBits(Bits.ALL)
.setOtherBits(Bits.NONE).build())
.setWriteType(S3RestUtils.getS3WriteType())
.putAllXattr(xattrMap)
.setXattrPropStrat(XAttrPropagationStrategy.LEAF_NODE)
.build()
);
SetAttributePOptions attrPOptions = SetAttributePOptions.newBuilder()
.setOwner(user)
.build();
mHandler.getMetaFS().setAttribute(new AlluxioURI(
S3RestUtils.getMultipartMetaFilepathForUploadId(uploadId)), attrPOptions);
if (S3Handler.MULTIPART_CLEANER_ENABLED) {
MultipartUploadCleaner.apply(mHandler.getMetaFS(), userFs, bucket, object, uploadId);
}
return new InitiateMultipartUploadResult(bucket, object, uploadId);
} catch (Exception e) {
throw S3RestUtils.toObjectS3Exception(e, objectPath, auditContext);
}
}
});
}
} // end of CreateMultipartUploadTask
/**
* CompleteMultipartUploadTask.
*/
public static final class CompleteMultipartUploadTask extends S3ObjectTask {
private final boolean mKeepAliveEnabled = Configuration.getBoolean(
PropertyKey.PROXY_S3_COMPLETE_MULTIPART_UPLOAD_KEEPALIVE_ENABLED);
private final Long mKeepAliveTime = Configuration.getMs(
PropertyKey.PROXY_S3_COMPLETE_MULTIPART_UPLOAD_KEEPALIVE_TIME_INTERVAL);
private String mUploadId;
private FileSystem mUserFs;
private String mBucket;
private String mObject;
/**
* Create a CompleteMultipartUploadTask.
* @param handler
* @param opType
*/
public CompleteMultipartUploadTask(S3Handler handler, OpType opType) {
super(handler, opType);
}
@Override
public void handleTaskAsync() {
try {
final String user = mHandler.getUser();
mBucket = mHandler.getBucket();
mObject = mHandler.getObject();
final String uploadId = mHandler.getQueryParameter("uploadId");
LOG.debug("(bucket: {}, object: {}, uploadId: {}) queuing task...",
mBucket, mObject, uploadId);
HttpServletResponse httpServletResponse = mHandler.getServletResponse();
// Set headers before getting committed when flushing whitespaces
httpServletResponse.setContentType(MediaType.APPLICATION_XML);
CompletableFuture<Response> respFut = new CompletableFuture<>();
ExecutorService es = (ExecutorService) mHandler.getServletContext().getAttribute(
S3RequestServlet.PROXY_S3_V2_HEAVY_POOL);
es.submit(() -> {
Response completeMpUploadResponse = mHandler.getS3Task().continueTask();
respFut.complete(completeMpUploadResponse);
});
if (mKeepAliveEnabled) {
// Set status before getting committed when flushing whitespaces
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
long sleepMs = 1000;
while (!respFut.isDone()) {
LOG.debug("(bucket: {}, object: {}, uploadId: {}) sleeping for {}ms...",
mBucket, mObject, uploadId, sleepMs);
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
LOG.error(e.toString());
}
// TODO(czhu): figure out how to send whitespace characters while still
// returning a correct status code
// - calling getWriter().flush() commits the response (headers, status code, etc.)
// - https://docs.oracle.com/javaee/7/api/javax/servlet/ServletResponse.html#getWriter--
// periodically sends white space characters to keep the connection from timing out
LOG.debug("(bucket: {}, object: {}, uploadId: {}) sending whitespace...",
mBucket, mObject, uploadId);
httpServletResponse.getWriter().print(" ");
httpServletResponse.getWriter().flush();
sleepMs = Math.min(2 * sleepMs, mKeepAliveTime);
}
} // otherwise we perform a blocking call on future.get()