/
StorageImpl.java
1851 lines (1683 loc) · 67.9 KB
/
StorageImpl.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
/*
* Copyright 2015 Google LLC
*
* Licensed 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.
*/
package com.google.cloud.storage;
import static com.google.cloud.RetryHelper.runWithRetries;
import static com.google.cloud.storage.PolicyHelper.convertFromApiPolicy;
import static com.google.cloud.storage.PolicyHelper.convertToApiPolicy;
import static com.google.cloud.storage.SignedUrlEncodingHelper.Rfc3986UriEncode;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.DELIMITER;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_GENERATION_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_GENERATION_NOT_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_METAGENERATION_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_METAGENERATION_NOT_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_SOURCE_GENERATION_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_SOURCE_GENERATION_NOT_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_SOURCE_METAGENERATION_MATCH;
import static com.google.cloud.storage.spi.v1.StorageRpc.Option.IF_SOURCE_METAGENERATION_NOT_MATCH;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.api.gax.paging.Page;
import com.google.api.services.storage.model.BucketAccessControl;
import com.google.api.services.storage.model.ObjectAccessControl;
import com.google.api.services.storage.model.StorageObject;
import com.google.api.services.storage.model.TestIamPermissionsResponse;
import com.google.auth.ServiceAccountSigner;
import com.google.cloud.BaseService;
import com.google.cloud.BatchResult;
import com.google.cloud.PageImpl;
import com.google.cloud.PageImpl.NextPageFetcher;
import com.google.cloud.Policy;
import com.google.cloud.ReadChannel;
import com.google.cloud.RetryHelper.RetryHelperException;
import com.google.cloud.Tuple;
import com.google.cloud.WriteChannel;
import com.google.cloud.storage.Acl.Entity;
import com.google.cloud.storage.HmacKey.HmacKeyMetadata;
import com.google.cloud.storage.PostPolicyV4.ConditionV4Type;
import com.google.cloud.storage.PostPolicyV4.PostConditionsV4;
import com.google.cloud.storage.PostPolicyV4.PostFieldsV4;
import com.google.cloud.storage.PostPolicyV4.PostPolicyV4Document;
import com.google.cloud.storage.spi.v1.StorageRpc;
import com.google.cloud.storage.spi.v1.StorageRpc.RewriteResponse;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Ints;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
final class StorageImpl extends BaseService<StorageOptions> implements Storage {
private static final byte[] EMPTY_BYTE_ARRAY = {};
private static final String EMPTY_BYTE_ARRAY_MD5 = "1B2M2Y8AsgTpgAmY7PhCfg==";
private static final String EMPTY_BYTE_ARRAY_CRC32C = "AAAAAA==";
private static final String PATH_DELIMITER = "/";
/** Signed URLs are only supported through the GCS XML API endpoint. */
private static final String STORAGE_XML_URI_SCHEME = "https";
private static final String STORAGE_XML_URI_HOST_NAME = "storage.googleapis.com";
private static final int DEFAULT_BUFFER_SIZE = 15 * 1024 * 1024;
private static final int MIN_BUFFER_SIZE = 256 * 1024;
private static final Function<Tuple<Storage, Boolean>, Boolean> DELETE_FUNCTION =
new Function<Tuple<Storage, Boolean>, Boolean>() {
@Override
public Boolean apply(Tuple<Storage, Boolean> tuple) {
return tuple.y();
}
};
private final StorageRpc storageRpc;
StorageImpl(StorageOptions options) {
super(options);
storageRpc = options.getStorageRpcV1();
}
@Override
public Bucket create(BucketInfo bucketInfo, BucketTargetOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = bucketInfo.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(bucketInfo, options);
try {
return Bucket.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.storage.model.Bucket>() {
@Override
public com.google.api.services.storage.model.Bucket call() {
return storageRpc.create(bucketPb, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob create(BlobInfo blobInfo, BlobTargetOption... options) {
BlobInfo updatedInfo =
blobInfo
.toBuilder()
.setMd5(EMPTY_BYTE_ARRAY_MD5)
.setCrc32c(EMPTY_BYTE_ARRAY_CRC32C)
.build();
return internalCreate(updatedInfo, EMPTY_BYTE_ARRAY, 0, 0, options);
}
@Override
public Blob create(BlobInfo blobInfo, byte[] content, BlobTargetOption... options) {
content = firstNonNull(content, EMPTY_BYTE_ARRAY);
BlobInfo updatedInfo =
blobInfo
.toBuilder()
.setMd5(BaseEncoding.base64().encode(Hashing.md5().hashBytes(content).asBytes()))
.setCrc32c(
BaseEncoding.base64()
.encode(Ints.toByteArray(Hashing.crc32c().hashBytes(content).asInt())))
.build();
return internalCreate(updatedInfo, content, 0, content.length, options);
}
@Override
public Blob create(
BlobInfo blobInfo, byte[] content, int offset, int length, BlobTargetOption... options) {
content = firstNonNull(content, EMPTY_BYTE_ARRAY);
BlobInfo updatedInfo =
blobInfo
.toBuilder()
.setMd5(
BaseEncoding.base64()
.encode(Hashing.md5().hashBytes(content, offset, length).asBytes()))
.setCrc32c(
BaseEncoding.base64()
.encode(
Ints.toByteArray(
Hashing.crc32c().hashBytes(content, offset, length).asInt())))
.build();
return internalCreate(updatedInfo, content, offset, length, options);
}
@Override
@Deprecated
public Blob create(BlobInfo blobInfo, InputStream content, BlobWriteOption... options) {
Tuple<BlobInfo, BlobTargetOption[]> targetOptions = BlobTargetOption.convert(blobInfo, options);
StorageObject blobPb = targetOptions.x().toPb();
Map<StorageRpc.Option, ?> optionsMap = optionMap(targetOptions.x(), targetOptions.y());
InputStream inputStreamParam =
firstNonNull(content, new ByteArrayInputStream(EMPTY_BYTE_ARRAY));
// retries are not safe when the input is an InputStream, so we can't retry.
return Blob.fromPb(this, storageRpc.create(blobPb, inputStreamParam, optionsMap));
}
private Blob internalCreate(
BlobInfo info,
final byte[] content,
final int offset,
final int length,
BlobTargetOption... options) {
Preconditions.checkNotNull(content);
final StorageObject blobPb = info.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(info, options);
try {
return Blob.fromPb(
this,
runWithRetries(
new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.create(
blobPb, new ByteArrayInputStream(content, offset, length), optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob createFrom(BlobInfo blobInfo, Path path, BlobWriteOption... options)
throws IOException {
return createFrom(blobInfo, path, DEFAULT_BUFFER_SIZE, options);
}
@Override
public Blob createFrom(BlobInfo blobInfo, Path path, int bufferSize, BlobWriteOption... options)
throws IOException {
if (Files.isDirectory(path)) {
throw new StorageException(0, path + " is a directory");
}
try (InputStream input = Files.newInputStream(path)) {
return createFrom(blobInfo, input, bufferSize, options);
}
}
@Override
public Blob createFrom(BlobInfo blobInfo, InputStream content, BlobWriteOption... options)
throws IOException {
return createFrom(blobInfo, content, DEFAULT_BUFFER_SIZE, options);
}
@Override
public Blob createFrom(
BlobInfo blobInfo, InputStream content, int bufferSize, BlobWriteOption... options)
throws IOException {
BlobWriteChannel blobWriteChannel;
try (WriteChannel writer = writer(blobInfo, options)) {
blobWriteChannel = (BlobWriteChannel) writer;
uploadHelper(Channels.newChannel(content), writer, bufferSize);
}
StorageObject objectProto = blobWriteChannel.getStorageObject();
return Blob.fromPb(this, objectProto);
}
/*
* Uploads the given content to the storage using specified write channel and the given buffer
* size. This method does not close any channels.
*/
private static void uploadHelper(ReadableByteChannel reader, WriteChannel writer, int bufferSize)
throws IOException {
bufferSize = Math.max(bufferSize, MIN_BUFFER_SIZE);
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
writer.setChunkSize(bufferSize);
while (reader.read(buffer) >= 0) {
buffer.flip();
writer.write(buffer);
buffer.clear();
}
}
@Override
public Bucket get(String bucket, BucketGetOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = BucketInfo.of(bucket).toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(options);
try {
com.google.api.services.storage.model.Bucket answer =
runWithRetries(
new Callable<com.google.api.services.storage.model.Bucket>() {
@Override
public com.google.api.services.storage.model.Bucket call() {
return storageRpc.get(bucketPb, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock());
return answer == null ? null : Bucket.fromPb(this, answer);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob get(String bucket, String blob, BlobGetOption... options) {
return get(BlobId.of(bucket, blob), options);
}
@Override
public Blob get(BlobId blob, BlobGetOption... options) {
final StorageObject storedObject = blob.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
try {
StorageObject storageObject =
runWithRetries(
new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.get(storedObject, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock());
return storageObject == null ? null : Blob.fromPb(this, storageObject);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob get(BlobId blob) {
return get(blob, new BlobGetOption[0]);
}
private static class BucketPageFetcher implements NextPageFetcher<Bucket> {
private static final long serialVersionUID = 5850406828803613729L;
private final Map<StorageRpc.Option, ?> requestOptions;
private final StorageOptions serviceOptions;
BucketPageFetcher(
StorageOptions serviceOptions, String cursor, Map<StorageRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(StorageRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
}
@Override
public Page<Bucket> getNextPage() {
return listBuckets(serviceOptions, requestOptions);
}
}
private static class BlobPageFetcher implements NextPageFetcher<Blob> {
private static final long serialVersionUID = 81807334445874098L;
private final Map<StorageRpc.Option, ?> requestOptions;
private final StorageOptions serviceOptions;
private final String bucket;
BlobPageFetcher(
String bucket,
StorageOptions serviceOptions,
String cursor,
Map<StorageRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(StorageRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.bucket = bucket;
}
@Override
public Page<Blob> getNextPage() {
return listBlobs(bucket, serviceOptions, requestOptions);
}
}
private static class HmacKeyMetadataPageFetcher implements NextPageFetcher<HmacKeyMetadata> {
private static final long serialVersionUID = 308012320541700881L;
private final StorageOptions serviceOptions;
private final Map<StorageRpc.Option, ?> options;
HmacKeyMetadataPageFetcher(StorageOptions serviceOptions, Map<StorageRpc.Option, ?> options) {
this.serviceOptions = serviceOptions;
this.options = options;
}
@Override
public Page<HmacKeyMetadata> getNextPage() {
return listHmacKeys(serviceOptions, options);
}
}
@Override
public Page<Bucket> list(BucketListOption... options) {
return listBuckets(getOptions(), optionMap(options));
}
@Override
public Page<Blob> list(final String bucket, BlobListOption... options) {
return listBlobs(bucket, getOptions(), optionMap(options));
}
private static Page<Bucket> listBuckets(
final StorageOptions serviceOptions, final Map<StorageRpc.Option, ?> optionsMap) {
try {
Tuple<String, Iterable<com.google.api.services.storage.model.Bucket>> result =
runWithRetries(
new Callable<
Tuple<String, Iterable<com.google.api.services.storage.model.Bucket>>>() {
@Override
public Tuple<String, Iterable<com.google.api.services.storage.model.Bucket>>
call() {
return serviceOptions.getStorageRpcV1().list(optionsMap);
}
},
serviceOptions.getRetrySettings(),
EXCEPTION_HANDLER,
serviceOptions.getClock());
String cursor = result.x();
Iterable<Bucket> buckets =
result.y() == null
? ImmutableList.<Bucket>of()
: Iterables.transform(
result.y(),
new Function<com.google.api.services.storage.model.Bucket, Bucket>() {
@Override
public Bucket apply(com.google.api.services.storage.model.Bucket bucketPb) {
return Bucket.fromPb(serviceOptions.getService(), bucketPb);
}
});
return new PageImpl<>(
new BucketPageFetcher(serviceOptions, cursor, optionsMap), cursor, buckets);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
private static Page<Blob> listBlobs(
final String bucket,
final StorageOptions serviceOptions,
final Map<StorageRpc.Option, ?> optionsMap) {
try {
Tuple<String, Iterable<StorageObject>> result =
runWithRetries(
new Callable<Tuple<String, Iterable<StorageObject>>>() {
@Override
public Tuple<String, Iterable<StorageObject>> call() {
return serviceOptions.getStorageRpcV1().list(bucket, optionsMap);
}
},
serviceOptions.getRetrySettings(),
EXCEPTION_HANDLER,
serviceOptions.getClock());
String cursor = result.x();
Iterable<Blob> blobs =
result.y() == null
? ImmutableList.<Blob>of()
: Iterables.transform(
result.y(),
new Function<StorageObject, Blob>() {
@Override
public Blob apply(StorageObject storageObject) {
return Blob.fromPb(serviceOptions.getService(), storageObject);
}
});
return new PageImpl<>(
new BlobPageFetcher(bucket, serviceOptions, cursor, optionsMap), cursor, blobs);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Bucket update(BucketInfo bucketInfo, BucketTargetOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = bucketInfo.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(bucketInfo, options);
try {
return Bucket.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.storage.model.Bucket>() {
@Override
public com.google.api.services.storage.model.Bucket call() {
return storageRpc.patch(bucketPb, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob update(BlobInfo blobInfo, BlobTargetOption... options) {
final StorageObject storageObject = blobInfo.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blobInfo, options);
try {
return Blob.fromPb(
this,
runWithRetries(
new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.patch(storageObject, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob update(BlobInfo blobInfo) {
return update(blobInfo, new BlobTargetOption[0]);
}
@Override
public boolean delete(String bucket, BucketSourceOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = BucketInfo.of(bucket).toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(options);
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.delete(bucketPb, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean delete(String bucket, String blob, BlobSourceOption... options) {
return delete(BlobId.of(bucket, blob), options);
}
@Override
public boolean delete(BlobId blob, BlobSourceOption... options) {
final StorageObject storageObject = blob.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.delete(storageObject, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean delete(BlobId blob) {
return delete(blob, new BlobSourceOption[0]);
}
@Override
public Blob compose(final ComposeRequest composeRequest) {
final List<StorageObject> sources =
Lists.newArrayListWithCapacity(composeRequest.getSourceBlobs().size());
for (ComposeRequest.SourceBlob sourceBlob : composeRequest.getSourceBlobs()) {
sources.add(
BlobInfo.newBuilder(
BlobId.of(
composeRequest.getTarget().getBucket(),
sourceBlob.getName(),
sourceBlob.getGeneration()))
.build()
.toPb());
}
final StorageObject target = composeRequest.getTarget().toPb();
final Map<StorageRpc.Option, ?> targetOptions =
optionMap(
composeRequest.getTarget().getGeneration(),
composeRequest.getTarget().getMetageneration(),
composeRequest.getTargetOptions());
try {
return Blob.fromPb(
this,
runWithRetries(
new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.compose(sources, target, targetOptions);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public CopyWriter copy(final CopyRequest copyRequest) {
final StorageObject source = copyRequest.getSource().toPb();
final Map<StorageRpc.Option, ?> sourceOptions =
optionMap(
copyRequest.getSource().getGeneration(), null, copyRequest.getSourceOptions(), true);
final StorageObject targetObject = copyRequest.getTarget().toPb();
final Map<StorageRpc.Option, ?> targetOptions =
optionMap(
copyRequest.getTarget().getGeneration(),
copyRequest.getTarget().getMetageneration(),
copyRequest.getTargetOptions());
try {
RewriteResponse rewriteResponse =
runWithRetries(
new Callable<RewriteResponse>() {
@Override
public RewriteResponse call() {
return storageRpc.openRewrite(
new StorageRpc.RewriteRequest(
source,
sourceOptions,
copyRequest.overrideInfo(),
targetObject,
targetOptions,
copyRequest.getMegabytesCopiedPerChunk()));
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock());
return new CopyWriter(getOptions(), rewriteResponse);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public byte[] readAllBytes(String bucket, String blob, BlobSourceOption... options) {
return readAllBytes(BlobId.of(bucket, blob), options);
}
@Override
public byte[] readAllBytes(BlobId blob, BlobSourceOption... options) {
final StorageObject storageObject = blob.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
try {
return runWithRetries(
new Callable<byte[]>() {
@Override
public byte[] call() {
return storageRpc.load(storageObject, optionsMap);
}
},
getOptions().getRetrySettings(),
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public StorageBatch batch() {
return new StorageBatch(this.getOptions());
}
@Override
public ReadChannel reader(String bucket, String blob, BlobSourceOption... options) {
Map<StorageRpc.Option, ?> optionsMap = optionMap(options);
return new BlobReadChannel(getOptions(), BlobId.of(bucket, blob), optionsMap);
}
@Override
public ReadChannel reader(BlobId blob, BlobSourceOption... options) {
Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
return new BlobReadChannel(getOptions(), blob, optionsMap);
}
@Override
public BlobWriteChannel writer(BlobInfo blobInfo, BlobWriteOption... options) {
Tuple<BlobInfo, BlobTargetOption[]> targetOptions = BlobTargetOption.convert(blobInfo, options);
return writer(targetOptions.x(), targetOptions.y());
}
@Override
public BlobWriteChannel writer(URL signedURL) {
return new BlobWriteChannel(getOptions(), signedURL);
}
private BlobWriteChannel writer(BlobInfo blobInfo, BlobTargetOption... options) {
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blobInfo, options);
return new BlobWriteChannel(getOptions(), blobInfo, optionsMap);
}
@Override
public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOption... options) {
EnumMap<SignUrlOption.Option, Object> optionMap = Maps.newEnumMap(SignUrlOption.Option.class);
for (SignUrlOption option : options) {
optionMap.put(option.getOption(), option.getValue());
}
boolean isV2 =
getPreferredSignatureVersion(optionMap).equals(SignUrlOption.SignatureVersion.V2);
boolean isV4 =
getPreferredSignatureVersion(optionMap).equals(SignUrlOption.SignatureVersion.V4);
ServiceAccountSigner credentials =
(ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED);
if (credentials == null) {
checkState(
this.getOptions().getCredentials() instanceof ServiceAccountSigner,
"Signing key was not provided and could not be derived");
credentials = (ServiceAccountSigner) this.getOptions().getCredentials();
}
long expiration =
isV4
? TimeUnit.SECONDS.convert(unit.toMillis(duration), TimeUnit.MILLISECONDS)
: TimeUnit.SECONDS.convert(
getOptions().getClock().millisTime() + unit.toMillis(duration),
TimeUnit.MILLISECONDS);
checkArgument(
!(optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE)
&& optionMap.containsKey(SignUrlOption.Option.PATH_STYLE)
&& optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)),
"Only one of VIRTUAL_HOSTED_STYLE, PATH_STYLE, or BUCKET_BOUND_HOST_NAME SignUrlOptions can be"
+ " specified.");
String bucketName = slashlessBucketNameFromBlobInfo(blobInfo);
String escapedBlobName = "";
if (!Strings.isNullOrEmpty(blobInfo.getName())) {
escapedBlobName = Rfc3986UriEncode(blobInfo.getName(), false);
}
boolean usePathStyle = shouldUsePathStyleForSignedUrl(optionMap);
String storageXmlHostName =
usePathStyle
? STORAGE_XML_URI_SCHEME + "://" + getBaseStorageHostName(optionMap)
: STORAGE_XML_URI_SCHEME + "://" + bucketName + "." + getBaseStorageHostName(optionMap);
if (optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)) {
storageXmlHostName = (String) optionMap.get(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME);
}
String stPath =
usePathStyle
? constructResourceUriPath(bucketName, escapedBlobName, optionMap)
: constructResourceUriPath("", escapedBlobName, optionMap);
URI path = URI.create(stPath);
// For V2 signing, even if we don't specify the bucket in the URI path, we still need the
// canonical resource string that we'll sign to include the bucket.
URI pathForSigning =
isV2 ? URI.create(constructResourceUriPath(bucketName, escapedBlobName, optionMap)) : path;
try {
SignatureInfo signatureInfo =
buildSignatureInfo(
optionMap, blobInfo, expiration, pathForSigning, credentials.getAccount());
String unsignedPayload = signatureInfo.constructUnsignedPayload();
byte[] signatureBytes = credentials.sign(unsignedPayload.getBytes(UTF_8));
StringBuilder stBuilder = new StringBuilder();
stBuilder.append(storageXmlHostName).append(path);
if (isV4) {
BaseEncoding encoding = BaseEncoding.base16().lowerCase();
String signature = URLEncoder.encode(encoding.encode(signatureBytes), UTF_8.name());
String v4QueryString = signatureInfo.constructV4QueryString();
stBuilder.append('?');
if (!Strings.isNullOrEmpty(v4QueryString)) {
stBuilder.append(v4QueryString).append('&');
}
stBuilder.append("X-Goog-Signature=").append(signature);
} else {
BaseEncoding encoding = BaseEncoding.base64();
String signature = URLEncoder.encode(encoding.encode(signatureBytes), UTF_8.name());
String v2QueryString = signatureInfo.constructV2QueryString();
stBuilder.append('?');
if (!Strings.isNullOrEmpty(v2QueryString)) {
stBuilder.append(v2QueryString).append('&');
}
stBuilder.append("GoogleAccessId=").append(credentials.getAccount());
stBuilder.append("&Expires=").append(expiration);
stBuilder.append("&Signature=").append(signature);
}
return new URL(stBuilder.toString());
} catch (MalformedURLException | UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public PostPolicyV4 generateSignedPostPolicyV4(
BlobInfo blobInfo,
long duration,
TimeUnit unit,
PostFieldsV4 fields,
PostConditionsV4 conditions,
PostPolicyV4Option... options) {
EnumMap<SignUrlOption.Option, Object> optionMap = Maps.newEnumMap(SignUrlOption.Option.class);
// Convert to a map of SignUrlOptions so we can re-use some utility methods
for (PostPolicyV4Option option : options) {
optionMap.put(SignUrlOption.Option.valueOf(option.getOption().name()), option.getValue());
}
optionMap.put(SignUrlOption.Option.SIGNATURE_VERSION, SignUrlOption.SignatureVersion.V4);
ServiceAccountSigner credentials =
(ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED);
if (credentials == null) {
checkState(
this.getOptions().getCredentials() instanceof ServiceAccountSigner,
"Signing key was not provided and could not be derived");
credentials = (ServiceAccountSigner) this.getOptions().getCredentials();
}
checkArgument(
!(optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE)
&& optionMap.containsKey(SignUrlOption.Option.PATH_STYLE)
&& optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)),
"Only one of VIRTUAL_HOSTED_STYLE, PATH_STYLE, or BUCKET_BOUND_HOST_NAME SignUrlOptions can be"
+ " specified.");
String bucketName = slashlessBucketNameFromBlobInfo(blobInfo);
boolean usePathStyle = shouldUsePathStyleForSignedUrl(optionMap);
String url;
if (usePathStyle) {
url = STORAGE_XML_URI_SCHEME + "://" + STORAGE_XML_URI_HOST_NAME + "/" + bucketName + "/";
} else {
url = STORAGE_XML_URI_SCHEME + "://" + bucketName + "." + STORAGE_XML_URI_HOST_NAME + "/";
}
if (optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)) {
url = optionMap.get(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME) + "/";
}
SimpleDateFormat googDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat expirationFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
googDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
yearMonthDayFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
expirationFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
long timestamp = getOptions().getClock().millisTime();
String date = googDateFormat.format(timestamp);
String signingCredential =
credentials.getAccount()
+ "/"
+ yearMonthDayFormat.format(timestamp)
+ "/auto/storage/goog4_request";
Map<String, String> policyFields = new HashMap<>();
PostConditionsV4.Builder conditionsBuilder = conditions.toBuilder();
for (Map.Entry<String, String> entry : fields.getFieldsMap().entrySet()) {
// Every field needs a corresponding policy condition, so add them if they're missing
conditionsBuilder.addCustomCondition(
ConditionV4Type.MATCHES, entry.getKey(), entry.getValue());
policyFields.put(entry.getKey(), entry.getValue());
}
PostConditionsV4 v4Conditions =
conditionsBuilder
.addBucketCondition(ConditionV4Type.MATCHES, blobInfo.getBucket())
.addKeyCondition(ConditionV4Type.MATCHES, blobInfo.getName())
.addCustomCondition(ConditionV4Type.MATCHES, "x-goog-date", date)
.addCustomCondition(ConditionV4Type.MATCHES, "x-goog-credential", signingCredential)
.addCustomCondition(ConditionV4Type.MATCHES, "x-goog-algorithm", "GOOG4-RSA-SHA256")
.build();
PostPolicyV4Document document =
PostPolicyV4Document.of(
expirationFormat.format(timestamp + unit.toMillis(duration)), v4Conditions);
String policy = BaseEncoding.base64().encode(document.toJson().getBytes());
String signature =
BaseEncoding.base16().encode(credentials.sign(policy.getBytes())).toLowerCase();
for (PostPolicyV4.ConditionV4 condition : v4Conditions.getConditions()) {
if (condition.type == ConditionV4Type.MATCHES) {
policyFields.put(condition.operand1, condition.operand2);
}
}
policyFields.put("key", blobInfo.getName());
policyFields.put("x-goog-credential", signingCredential);
policyFields.put("x-goog-algorithm", "GOOG4-RSA-SHA256");
policyFields.put("x-goog-date", date);
policyFields.put("x-goog-signature", signature);
policyFields.put("policy", policy);
policyFields.remove("bucket");
return PostPolicyV4.of(url, policyFields);
}
public PostPolicyV4 generateSignedPostPolicyV4(
BlobInfo blobInfo,
long duration,
TimeUnit unit,
PostFieldsV4 fields,
PostPolicyV4Option... options) {
return generateSignedPostPolicyV4(
blobInfo, duration, unit, fields, PostConditionsV4.newBuilder().build(), options);
}
public PostPolicyV4 generateSignedPostPolicyV4(
BlobInfo blobInfo,
long duration,
TimeUnit unit,
PostConditionsV4 conditions,
PostPolicyV4Option... options) {
return generateSignedPostPolicyV4(
blobInfo, duration, unit, PostFieldsV4.newBuilder().build(), conditions, options);
}
public PostPolicyV4 generateSignedPostPolicyV4(
BlobInfo blobInfo, long duration, TimeUnit unit, PostPolicyV4Option... options) {
return generateSignedPostPolicyV4(
blobInfo, duration, unit, PostFieldsV4.newBuilder().build(), options);
}
private String constructResourceUriPath(
String slashlessBucketName,
String escapedBlobName,
EnumMap<SignUrlOption.Option, Object> optionMap) {
if (Strings.isNullOrEmpty(slashlessBucketName)) {
if (Strings.isNullOrEmpty(escapedBlobName)) {
return PATH_DELIMITER;
}
if (escapedBlobName.startsWith(PATH_DELIMITER)) {
return escapedBlobName;
}
return PATH_DELIMITER + escapedBlobName;
}
StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append(PATH_DELIMITER).append(slashlessBucketName);
if (Strings.isNullOrEmpty(escapedBlobName)) {
boolean isV2 =
getPreferredSignatureVersion(optionMap).equals(SignUrlOption.SignatureVersion.V2);
// If using virtual-hosted style URLs with V2 signing, the path string for a bucket resource
// must end with a forward slash.
if (optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE) && isV2) {
pathBuilder.append(PATH_DELIMITER);
}
return pathBuilder.toString();
}
pathBuilder.append(PATH_DELIMITER);
pathBuilder.append(escapedBlobName);
return pathBuilder.toString();
}
private SignUrlOption.SignatureVersion getPreferredSignatureVersion(
EnumMap<SignUrlOption.Option, Object> optionMap) {
// Check for an explicitly specified version in the map.
for (SignUrlOption.SignatureVersion version : SignUrlOption.SignatureVersion.values()) {
if (version.equals(optionMap.get(SignUrlOption.Option.SIGNATURE_VERSION))) {
return version;
}
}
// TODO(#6362): V2 is the default, and thus can be specified either explicitly or implicitly
// Change this to V4 once we make it the default.
return SignUrlOption.SignatureVersion.V2;
}
private boolean shouldUsePathStyleForSignedUrl(EnumMap<SignUrlOption.Option, Object> optionMap) {
// TODO(#6362): If we decide to change the default style used to generate URLs, switch this
// logic to return false unless PATH_STYLE was explicitly specified.
if (optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE)
|| optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)) {
return false;
}
return true;