Search in sources :

Example 11 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project herd by FINRAOS.

the class S3DaoImpl method abortMultipartUploads.

@Override
public int abortMultipartUploads(S3FileTransferRequestParamsDto params, Date thresholdDate) {
    // Create an Amazon S3 client.
    AmazonS3Client s3Client = getAmazonS3(params);
    int abortedMultipartUploadsCount = 0;
    try {
        // List upload markers. Null implies initial list request.
        String uploadIdMarker = null;
        String keyMarker = null;
        boolean truncated;
        do {
            // Create the list multipart request, optionally using the last markers.
            ListMultipartUploadsRequest request = new ListMultipartUploadsRequest(params.getS3BucketName());
            request.setUploadIdMarker(uploadIdMarker);
            request.setKeyMarker(keyMarker);
            // Request the multipart upload listing.
            MultipartUploadListing uploadListing = s3Operations.listMultipartUploads(TransferManager.appendSingleObjectUserAgent(request), s3Client);
            for (MultipartUpload upload : uploadListing.getMultipartUploads()) {
                if (upload.getInitiated().compareTo(thresholdDate) < 0) {
                    // Abort the upload.
                    s3Operations.abortMultipartUpload(TransferManager.appendSingleObjectUserAgent(new AbortMultipartUploadRequest(params.getS3BucketName(), upload.getKey(), upload.getUploadId())), s3Client);
                    // Log the information about the aborted multipart upload.
                    LOGGER.info("Aborted S3 multipart upload. s3Key=\"{}\" s3BucketName=\"{}\" s3MultipartUploadInitiatedDate=\"{}\"", upload.getKey(), params.getS3BucketName(), upload.getInitiated());
                    // Increment the counter.
                    abortedMultipartUploadsCount++;
                }
            }
            // Determine whether there are more uploads to list.
            truncated = uploadListing.isTruncated();
            if (truncated) {
                // Record the list markers.
                uploadIdMarker = uploadListing.getNextUploadIdMarker();
                keyMarker = uploadListing.getNextKeyMarker();
            }
        } while (truncated);
    } finally {
        // Shutdown the Amazon S3 client instance to release resources.
        s3Client.shutdown();
    }
    return abortedMultipartUploadsCount;
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) MultipartUploadListing(com.amazonaws.services.s3.model.MultipartUploadListing) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) MultipartUpload(com.amazonaws.services.s3.model.MultipartUpload) ListMultipartUploadsRequest(com.amazonaws.services.s3.model.ListMultipartUploadsRequest)

Example 12 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project android-simpl3r by jgilfelt.

the class Uploader method start.

/**
 * Initiate a multipart file upload to Amazon S3
 *
 * @return the URL of a successfully uploaded file
 */
public String start() {
    // initialize
    List<PartETag> partETags = new ArrayList<PartETag>();
    final long contentLength = file.length();
    long filePosition = 0;
    int startPartNumber = 1;
    userInterrupted = false;
    userAborted = false;
    bytesUploaded = 0;
    // check if we can resume an incomplete download
    String uploadId = getCachedUploadId();
    if (uploadId != null) {
        // we can resume the download
        Log.i(TAG, "resuming upload for " + uploadId);
        // get the cached etags
        List<PartETag> cachedEtags = getCachedPartEtags();
        partETags.addAll(cachedEtags);
        // calculate the start position for resume
        startPartNumber = cachedEtags.size() + 1;
        filePosition = (startPartNumber - 1) * partSize;
        bytesUploaded = filePosition;
        Log.i(TAG, "resuming at part " + startPartNumber + " position " + filePosition);
    } else {
        // initiate a new multi part upload
        Log.i(TAG, "initiating new upload");
        InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(s3bucketName, s3key);
        configureInitiateRequest(initRequest);
        InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
        uploadId = initResponse.getUploadId();
    }
    final AbortMultipartUploadRequest abortRequest = new AbortMultipartUploadRequest(s3bucketName, s3key, uploadId);
    for (int k = startPartNumber; filePosition < contentLength; k++) {
        long thisPartSize = Math.min(partSize, (contentLength - filePosition));
        Log.i(TAG, "starting file part " + k + " with size " + thisPartSize);
        UploadPartRequest uploadRequest = new UploadPartRequest().withBucketName(s3bucketName).withKey(s3key).withUploadId(uploadId).withPartNumber(k).withFileOffset(filePosition).withFile(file).withPartSize(thisPartSize);
        ProgressListener s3progressListener = new ProgressListener() {

            public void progressChanged(ProgressEvent progressEvent) {
                // TODO calling shutdown too brute force?
                if (userInterrupted) {
                    s3Client.shutdown();
                    throw new UploadIterruptedException("User interrupted");
                } else if (userAborted) {
                    // aborted requests cannot be resumed, so clear any cached etags
                    clearProgressCache();
                    s3Client.abortMultipartUpload(abortRequest);
                    s3Client.shutdown();
                }
                bytesUploaded += progressEvent.getBytesTransfered();
                // Log.d(TAG, "bytesUploaded=" + bytesUploaded);
                // broadcast progress
                float fpercent = ((bytesUploaded * 100) / contentLength);
                int percent = Math.round(fpercent);
                if (progressListener != null) {
                    progressListener.progressChanged(progressEvent, bytesUploaded, percent);
                }
            }
        };
        uploadRequest.setProgressListener(s3progressListener);
        UploadPartResult result = s3Client.uploadPart(uploadRequest);
        partETags.add(result.getPartETag());
        // cache the part progress for this upload
        if (k == 1) {
            initProgressCache(uploadId);
        }
        // store part etag
        cachePartEtag(result);
        filePosition += thisPartSize;
    }
    CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(s3bucketName, s3key, uploadId, partETags);
    CompleteMultipartUploadResult result = s3Client.completeMultipartUpload(compRequest);
    bytesUploaded = 0;
    Log.i(TAG, "upload complete for " + uploadId);
    clearProgressCache();
    return result.getLocation();
}
Also used : InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) ArrayList(java.util.ArrayList) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) CompleteMultipartUploadResult(com.amazonaws.services.s3.model.CompleteMultipartUploadResult) ProgressEvent(com.amazonaws.services.s3.model.ProgressEvent) PartETag(com.amazonaws.services.s3.model.PartETag) UploadPartResult(com.amazonaws.services.s3.model.UploadPartResult) ProgressListener(com.amazonaws.services.s3.model.ProgressListener) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)

Example 13 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project aws-doc-sdk-examples by awsdocs.

the class LowLevelAbortMultipartUpload method main.

public static void main(String[] args) {
    Regions clientRegion = Regions.DEFAULT_REGION;
    String bucketName = "*** Bucket name ***";
    try {
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(clientRegion).withCredentials(new ProfileCredentialsProvider()).build();
        // Find all in-progress multipart uploads.
        ListMultipartUploadsRequest allMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName);
        MultipartUploadListing multipartUploadListing = s3Client.listMultipartUploads(allMultipartUploadsRequest);
        List<MultipartUpload> uploads = multipartUploadListing.getMultipartUploads();
        System.out.println("Before deletions, " + uploads.size() + " multipart uploads in progress.");
        // Abort each upload.
        for (MultipartUpload u : uploads) {
            System.out.println("Upload in progress: Key = \"" + u.getKey() + "\", id = " + u.getUploadId());
            s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(bucketName, u.getKey(), u.getUploadId()));
            System.out.println("Upload deleted: Key = \"" + u.getKey() + "\", id = " + u.getUploadId());
        }
        // Verify that all in-progress multipart uploads have been aborted.
        multipartUploadListing = s3Client.listMultipartUploads(allMultipartUploadsRequest);
        uploads = multipartUploadListing.getMultipartUploads();
        System.out.println("After aborting uploads, " + uploads.size() + " multipart uploads in progress.");
    } catch (AmazonServiceException e) {
        // The call was transmitted successfully, but Amazon S3 couldn't process
        // it, so it returned an error response.
        e.printStackTrace();
    } catch (SdkClientException e) {
        // Amazon S3 couldn't be contacted for a response, or the client
        // couldn't parse the response from Amazon S3.
        e.printStackTrace();
    }
}
Also used : AmazonS3(com.amazonaws.services.s3.AmazonS3) SdkClientException(com.amazonaws.SdkClientException) AmazonServiceException(com.amazonaws.AmazonServiceException) ProfileCredentialsProvider(com.amazonaws.auth.profile.ProfileCredentialsProvider) MultipartUploadListing(com.amazonaws.services.s3.model.MultipartUploadListing) Regions(com.amazonaws.regions.Regions) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) MultipartUpload(com.amazonaws.services.s3.model.MultipartUpload) ListMultipartUploadsRequest(com.amazonaws.services.s3.model.ListMultipartUploadsRequest)

Example 14 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project crate by crate.

the class S3BlobStoreContainerTests method testExecuteMultipartUploadAborted.

@Test
public void testExecuteMultipartUploadAborted() {
    final String bucketName = randomAlphaOfLengthBetween(1, 10);
    final String blobName = randomAlphaOfLengthBetween(1, 10);
    final BlobPath blobPath = new BlobPath();
    final long blobSize = ByteSizeUnit.MB.toBytes(765);
    final long bufferSize = ByteSizeUnit.MB.toBytes(150);
    final S3BlobStore blobStore = mock(S3BlobStore.class);
    when(blobStore.bucket()).thenReturn(bucketName);
    when(blobStore.bufferSizeInBytes()).thenReturn(bufferSize);
    when(blobStore.getStorageClass()).thenReturn(randomFrom(StorageClass.values()));
    final AmazonS3 client = mock(AmazonS3.class);
    final AmazonS3Reference clientReference = new AmazonS3Reference(client);
    doAnswer(invocation -> {
        clientReference.incRef();
        return clientReference;
    }).when(blobStore).clientReference();
    final String uploadId = randomAlphaOfLength(25);
    final int stage = randomInt(2);
    final List<AmazonClientException> exceptions = Arrays.asList(new AmazonClientException("Expected initialization request to fail"), new AmazonClientException("Expected upload part request to fail"), new AmazonClientException("Expected completion request to fail"));
    if (stage == 0) {
        // Fail the initialization request
        when(client.initiateMultipartUpload(any(InitiateMultipartUploadRequest.class))).thenThrow(exceptions.get(stage));
    } else if (stage == 1) {
        final InitiateMultipartUploadResult initResult = new InitiateMultipartUploadResult();
        initResult.setUploadId(uploadId);
        when(client.initiateMultipartUpload(any(InitiateMultipartUploadRequest.class))).thenReturn(initResult);
        // Fail the upload part request
        when(client.uploadPart(any(UploadPartRequest.class))).thenThrow(exceptions.get(stage));
    } else {
        final InitiateMultipartUploadResult initResult = new InitiateMultipartUploadResult();
        initResult.setUploadId(uploadId);
        when(client.initiateMultipartUpload(any(InitiateMultipartUploadRequest.class))).thenReturn(initResult);
        when(client.uploadPart(any(UploadPartRequest.class))).thenAnswer(invocationOnMock -> {
            final UploadPartRequest request = (UploadPartRequest) invocationOnMock.getArguments()[0];
            final UploadPartResult response = new UploadPartResult();
            response.setPartNumber(request.getPartNumber());
            response.setETag(randomAlphaOfLength(20));
            return response;
        });
        // Fail the completion request
        when(client.completeMultipartUpload(any(CompleteMultipartUploadRequest.class))).thenThrow(exceptions.get(stage));
    }
    final ArgumentCaptor<AbortMultipartUploadRequest> argumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
    doNothing().when(client).abortMultipartUpload(argumentCaptor.capture());
    final IOException e = expectThrows(IOException.class, () -> {
        final S3BlobContainer blobContainer = new S3BlobContainer(blobPath, blobStore);
        blobContainer.executeMultipartUpload(blobStore, blobName, new ByteArrayInputStream(new byte[0]), blobSize);
    });
    assertEquals("Unable to upload object [" + blobName + "] using multipart upload", e.getMessage());
    assertThat(e.getCause(), instanceOf(AmazonClientException.class));
    assertEquals(exceptions.get(stage).getMessage(), e.getCause().getMessage());
    if (stage == 0) {
        verify(client, times(1)).initiateMultipartUpload(any(InitiateMultipartUploadRequest.class));
        verify(client, times(0)).uploadPart(any(UploadPartRequest.class));
        verify(client, times(0)).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
        verify(client, times(0)).abortMultipartUpload(any(AbortMultipartUploadRequest.class));
    } else {
        verify(client, times(1)).initiateMultipartUpload(any(InitiateMultipartUploadRequest.class));
        if (stage == 1) {
            verify(client, times(1)).uploadPart(any(UploadPartRequest.class));
            verify(client, times(0)).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
        } else {
            verify(client, times(6)).uploadPart(any(UploadPartRequest.class));
            verify(client, times(1)).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
        }
        verify(client, times(1)).abortMultipartUpload(any(AbortMultipartUploadRequest.class));
        final AbortMultipartUploadRequest abortRequest = argumentCaptor.getValue();
        assertEquals(bucketName, abortRequest.getBucketName());
        assertEquals(blobName, abortRequest.getKey());
        assertEquals(uploadId, abortRequest.getUploadId());
    }
}
Also used : ESBlobStoreContainerTestCase(org.elasticsearch.repositories.ESBlobStoreContainerTestCase) IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) Tuple(io.crate.common.collections.Tuple) ArrayList(java.util.ArrayList) CompleteMultipartUploadResult(com.amazonaws.services.s3.model.CompleteMultipartUploadResult) ArgumentCaptor(org.mockito.ArgumentCaptor) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) S3BlobStoreTests.randomMockS3BlobStore(org.elasticsearch.repositories.s3.S3BlobStoreTests.randomMockS3BlobStore) Mockito.doAnswer(org.mockito.Mockito.doAnswer) CannedAccessControlList(com.amazonaws.services.s3.model.CannedAccessControlList) InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) AmazonS3(com.amazonaws.services.s3.AmazonS3) UploadPartResult(com.amazonaws.services.s3.model.UploadPartResult) PutObjectResult(com.amazonaws.services.s3.model.PutObjectResult) BlobPath(org.elasticsearch.common.blobstore.BlobPath) ExpectedException(org.junit.rules.ExpectedException) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest) Test(org.junit.Test) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) PutObjectRequest(com.amazonaws.services.s3.model.PutObjectRequest) Collectors(java.util.stream.Collectors) Mockito.verify(org.mockito.Mockito.verify) StorageClass(com.amazonaws.services.s3.model.StorageClass) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) Rule(org.junit.Rule) BlobStore(org.elasticsearch.common.blobstore.BlobStore) Matchers.containsString(org.hamcrest.Matchers.containsString) AmazonClientException(com.amazonaws.AmazonClientException) PartETag(com.amazonaws.services.s3.model.PartETag) Mockito.mock(org.mockito.Mockito.mock) BlobPath(org.elasticsearch.common.blobstore.BlobPath) AmazonS3(com.amazonaws.services.s3.AmazonS3) InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) S3BlobStoreTests.randomMockS3BlobStore(org.elasticsearch.repositories.s3.S3BlobStoreTests.randomMockS3BlobStore) AmazonClientException(com.amazonaws.AmazonClientException) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) UploadPartResult(com.amazonaws.services.s3.model.UploadPartResult) ByteArrayInputStream(java.io.ByteArrayInputStream) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest) Test(org.junit.Test)

Example 15 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project Singularity by HubSpot.

the class SingularityS3Uploader method multipartUpload.

private void multipartUpload(AmazonS3 s3Client, String key, File file, ObjectMetadata objectMetadata, Optional<StorageClass> maybeStorageClass) throws Exception {
    List<PartETag> partETags = new ArrayList<>();
    InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, key, objectMetadata);
    maybeStorageClass.ifPresent(initRequest::setStorageClass);
    InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
    long contentLength = file.length();
    long partSize = configuration.getUploadPartSize();
    try {
        long filePosition = 0;
        for (int i = 1; filePosition < contentLength; i++) {
            partSize = Math.min(partSize, (contentLength - filePosition));
            UploadPartRequest uploadRequest = new UploadPartRequest().withBucketName(bucketName).withKey(key).withUploadId(initResponse.getUploadId()).withPartNumber(i).withFileOffset(filePosition).withFile(file).withPartSize(partSize);
            partETags.add(s3Client.uploadPart(uploadRequest).getPartETag());
            filePosition += partSize;
        }
        CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest(bucketName, key, initResponse.getUploadId(), partETags);
        s3Client.completeMultipartUpload(completeRequest);
    } catch (Exception e) {
        s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(bucketName, key, initResponse.getUploadId()));
        throw new RuntimeException(e);
    }
}
Also used : InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) ArrayList(java.util.ArrayList) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) PartETag(com.amazonaws.services.s3.model.PartETag) NoSuchFileException(java.nio.file.NoSuchFileException) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)

Aggregations

AbortMultipartUploadRequest (com.amazonaws.services.s3.model.AbortMultipartUploadRequest)14 CompleteMultipartUploadRequest (com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)9 InitiateMultipartUploadRequest (com.amazonaws.services.s3.model.InitiateMultipartUploadRequest)9 InitiateMultipartUploadResult (com.amazonaws.services.s3.model.InitiateMultipartUploadResult)9 PartETag (com.amazonaws.services.s3.model.PartETag)9 UploadPartRequest (com.amazonaws.services.s3.model.UploadPartRequest)8 ArrayList (java.util.ArrayList)7 AmazonClientException (com.amazonaws.AmazonClientException)5 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)5 IOException (java.io.IOException)4 CompleteMultipartUploadResult (com.amazonaws.services.s3.model.CompleteMultipartUploadResult)3 UploadPartResult (com.amazonaws.services.s3.model.UploadPartResult)3 AmazonS3 (com.amazonaws.services.s3.AmazonS3)2 AmazonS3Exception (com.amazonaws.services.s3.model.AmazonS3Exception)2 CannedAccessControlList (com.amazonaws.services.s3.model.CannedAccessControlList)2 ListMultipartUploadsRequest (com.amazonaws.services.s3.model.ListMultipartUploadsRequest)2 MultipartUpload (com.amazonaws.services.s3.model.MultipartUpload)2 MultipartUploadListing (com.amazonaws.services.s3.model.MultipartUploadListing)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 SdkClientException (com.amazonaws.SdkClientException)1