-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCloudStorageS3.java
More file actions
299 lines (268 loc) · 12.1 KB
/
CloudStorageS3.java
File metadata and controls
299 lines (268 loc) · 12.1 KB
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
package com.uid2.shared.cloud;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.WebIdentityTokenCredentialsProvider;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class CloudStorageS3 implements TaggableCloudStorage {
private static final Logger LOGGER = LoggerFactory.getLogger(CloudStorageS3.class);
private final AmazonS3 s3;
private final String bucket;
private long preSignedUrlExpiryInSeconds = 3600;
public CloudStorageS3(String accessKeyId, String secretAccessKey, String region, String bucket, String s3Endpoint) {
// Reading https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html
AWSCredentials creds = new BasicAWSCredentials(
accessKeyId,
secretAccessKey);
if (s3Endpoint.isEmpty()) {
this.s3 = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(creds))
.build();
} else {
this.s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(creds))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(s3Endpoint, region))
.enablePathStyleAccess()
.build();
}
this.bucket = bucket;
}
public CloudStorageS3(String region, String bucket, String s3Endpoint) {
this.bucket = bucket;
// In theory `new InstanceProfileCredentialsProvider()` or even omitting credentials provider should work,
// but for some unknown reason it doesn't. The credential it provides look realistic, but are not valid.
// After a lot of experimentation and help of Abu Abraham and Isaac Wilson the only working solution we've
// found was to explicitly extract env vars populated by the service account from the role and to
// manually set it on the credentials provider.
WebIdentityTokenCredentialsProvider credentialsProvider = WebIdentityTokenCredentialsProvider.builder()
.roleArn(System.getenv("AWS_ROLE_ARN"))
.webIdentityTokenFile(System.getenv("AWS_WEB_IDENTITY_TOKEN_FILE"))
.build();
if (s3Endpoint.isEmpty()) {
this.s3 = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(region)
.build();
} else {
this.s3 = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(s3Endpoint, region))
.enablePathStyleAccess()
.build();
}
}
@Override
public void upload(String localPath, String cloudPath) throws CloudStorageException {
try {
File file = new File(localPath);
var putResult = this.s3.putObject(bucket, cloudPath, file);
this.checkVersioningEnabled(putResult);
} catch (Throwable t) {
throw new CloudStorageException("s3 put error: " + t.getMessage(), t);
}
}
@Override
public void upload(InputStream input, String cloudPath) throws CloudStorageException {
try {
var putResult = this.s3.putObject(bucket, cloudPath, input, null);
this.checkVersioningEnabled(putResult);
} catch (Throwable t) {
throw new CloudStorageException("s3 put error: " + t.getMessage(), t);
}
}
@Override
public void upload(String localPath, String cloudPath, Map<String, String> tags) throws CloudStorageException {
try {
File file = new File(localPath);
PutObjectRequest putRequest = new PutObjectRequest(bucket, cloudPath, file);
List<Tag> newTags = new ArrayList<>();
tags.forEach((k, v) -> newTags.add(new Tag(k, v)));
putRequest.setTagging(new ObjectTagging(newTags));
var putResult = this.s3.putObject(putRequest);
this.checkVersioningEnabled(putResult);
} catch (Throwable t) {
throw new CloudStorageException("s3 put error: " + t.getMessage(), t);
}
}
@Override
public void upload(InputStream input, String cloudPath, Map<String, String> tags) throws CloudStorageException {
try {
PutObjectRequest putRequest = new PutObjectRequest(bucket, cloudPath, input, null);
List<Tag> newTags = new ArrayList<>();
tags.forEach((k, v) -> newTags.add(new Tag(k, v)));
putRequest.setTagging(new ObjectTagging(newTags));
var putResult = this.s3.putObject(putRequest);
this.checkVersioningEnabled(putResult);
} catch (Throwable t) {
throw new CloudStorageException("s3 put error: " + t.getMessage(), t);
}
}
@Override
public InputStream download(String cloudPath) throws CloudStorageException {
try {
S3Object obj = this.s3.getObject(bucket, cloudPath);
return obj.getObjectContent();
} catch (AmazonS3Exception e) {
LOGGER.error("AWS S3 error: " + e.getMessage() + " for path: " + cloudPath + " in bucket: " + bucket);
if (e.getErrorCode().equals("NoSuchKey")) {
throw new CloudStorageException("The specified key does not exist: " + e.getClass().getSimpleName() + ": " + bucket);
} else {
throw new CloudStorageException("s3 get error: " + e.getClass().getSimpleName() + ": " + bucket);
}
} catch (Throwable t) {
// Do not log the message or the original exception as that may contain the pre-signed url
throw new CloudStorageException("s3 get error: " + t.getClass().getSimpleName() + ": " + bucket);
}
}
@Override
public void delete(String cloudPath) throws CloudStorageException {
try {
this.s3.deleteObject(bucket, cloudPath);
} catch (Throwable t) {
throw new CloudStorageException("s3 delete error: " + t.getMessage(), t);
}
}
@Override
public void delete(Collection<String> cloudPaths) throws CloudStorageException {
if (cloudPaths.size() == 0) return;
if (cloudPaths.size() <= 1000) {
deleteInternal(cloudPaths);
return;
}
List<String> pathList = new ArrayList<>();
int i = 0;
final int len = cloudPaths.size();
for (String p : cloudPaths) {
pathList.add(p);
++i;
if (pathList.size() == 1000 || i == len) {
deleteInternal(pathList);
pathList.clear();
}
}
if (pathList.size() != 0) throw new IllegalStateException();
}
@Override
public List<String> list(String prefix) throws CloudStorageException {
try {
ListObjectsV2Request req = new ListObjectsV2Request()
.withBucketName(bucket)
.withPrefix(prefix);
ListObjectsV2Result result = null;
List<S3ObjectSummary> objects = null;
int reqCount = 0;
List<String> s3Paths = new ArrayList<>();
do {
result = this.s3.listObjectsV2(req);
objects = result.getObjectSummaries();
LOGGER.trace("s3 listobjectv2 request for " + prefix + " " + reqCount++ + ", returned keycount " + result.getKeyCount());
if (objects.size() > 0) {
LOGGER.trace("--> 1st key = " + objects.get(0).getKey());
}
for (S3ObjectSummary os : objects) {
s3Paths.add(os.getKey());
}
if (result.isTruncated()) {
req.setContinuationToken(result.getNextContinuationToken());
LOGGER.trace("--> truncated, continuationtoken: " + req.getContinuationToken());
}
} while (result.isTruncated());
return s3Paths;
} catch (Throwable t) {
throw new CloudStorageException("s3 list error: " + t.getMessage(), t);
}
}
@Override
public URL preSignUrl(String cloudPath) throws CloudStorageException {
try {
// Set the presigned URL to expire after one hour.
java.util.Date expiration = new java.util.Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += preSignedUrlExpiryInSeconds * 1000;
expiration.setTime(expTimeMillis);
// Generate the presigned URL.
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(this.bucket, cloudPath)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
URL url = this.s3.generatePresignedUrl(generatePresignedUrlRequest);
return url;
} catch (Throwable t) {
throw new CloudStorageException("s3 preSignUrl error: " + t.getMessage(), t);
}
}
@Override
public void setPreSignedUrlExpiry(long expiryInSeconds) {
this.preSignedUrlExpiryInSeconds = expiryInSeconds;
}
@Override
public String mask(String cloudPath) {
return cloudPath;
}
@Override
public void setTags(String cloudPath, Map<String, String> tags) throws CloudStorageException {
try {
if (this.s3.doesObjectExist(this.bucket, cloudPath)) {
List<Tag> newTags = new ArrayList<>();
tags.forEach((k, v) -> newTags.add(new Tag(k, v)));
this.s3.setObjectTagging(new SetObjectTaggingRequest(
this.bucket,
cloudPath,
new ObjectTagging(newTags)));
} else {
LOGGER.warn("CloudPath: {} does not exist in bucket: {}. Tags not set", cloudPath, this.bucket);
}
} catch (Throwable t) {
throw new CloudStorageException("s3 set tags error", t);
}
}
private void deleteInternal(Collection<String> cloudPaths) throws CloudStorageException {
List<DeleteObjectsRequest.KeyVersion> keys = new ArrayList<>();
for (String p : cloudPaths) {
keys.add(new DeleteObjectsRequest.KeyVersion(p));
}
DeleteObjectsRequest dor = new DeleteObjectsRequest(bucket)
.withKeys(keys)
.withQuiet(false);
try {
this.s3.deleteObjects(dor);
} catch (Throwable t) {
throw new CloudStorageException("s3 get error: " + t.getMessage(), t);
}
}
private void checkVersioningEnabled(PutObjectResult putObjectResult) {
try {
String versionId = putObjectResult.getVersionId();
if (versionId == null || versionId.isEmpty()) {
LOGGER.warn(
"Bucket: {} in Region: {} does not have versioning configured. There is a potential for data loss",
this.bucket,
this.s3.getRegionName());
} else {
LOGGER.info(
"Bucket: {} in Region: {} has versioning configured.",
this.bucket,
this.s3.getRegionName());
}
} catch (Throwable t) {
// don't want this to fail when writing, but should be logged
LOGGER.error(
String.format("Unable to determine if the S3 bucket: %s has versioning enabled", this.bucket),
t);
}
}
}