Search in sources :

Example 1 with PresignedUrl

use of ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl in project cyberduck by iterate-ch.

the class SDSDirectS3UploadFeature method retrievePresignedUrls.

private List<PresignedUrl> retrievePresignedUrls(final CreateFileUploadResponse createFileUploadResponse, final TransferStatus status) throws ApiException {
    // Full size of file
    final long size = status.getLength() + status.getOffset();
    final List<PresignedUrl> presignedUrls = new ArrayList<>();
    final GeneratePresignedUrlsRequest presignedUrlsRequest = new GeneratePresignedUrlsRequest().firstPartNumber(1);
    {
        long remaining = status.getLength();
        // Determine number of parts
        for (int partNumber = 1; remaining >= 0; partNumber++) {
            final long length = Math.min(Math.max((size / (MAXIMUM_UPLOAD_PARTS - 1)), partsize), remaining);
            if (partNumber > 1 && length < Math.max((size / (MAXIMUM_UPLOAD_PARTS - 1)), partsize)) {
                // Separate last part with non default part size
                presignedUrls.addAll(new NodesApi(session.getClient()).generatePresignedUrlsFiles(new GeneratePresignedUrlsRequest().firstPartNumber(partNumber).lastPartNumber(partNumber).size(length), createFileUploadResponse.getUploadId(), StringUtils.EMPTY).getUrls());
            } else {
                presignedUrlsRequest.lastPartNumber(partNumber).size(length);
            }
            remaining -= length;
            if (0L == remaining) {
                break;
            }
        }
    }
    presignedUrls.addAll(0, new NodesApi(session.getClient()).generatePresignedUrlsFiles(presignedUrlsRequest, createFileUploadResponse.getUploadId(), StringUtils.EMPTY).getUrls());
    return presignedUrls;
}
Also used : NodesApi(ch.cyberduck.core.sds.io.swagger.client.api.NodesApi) PresignedUrl(ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl) GeneratePresignedUrlsRequest(ch.cyberduck.core.sds.io.swagger.client.model.GeneratePresignedUrlsRequest) ArrayList(java.util.ArrayList)

Example 2 with PresignedUrl

use of ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl in project cyberduck by iterate-ch.

the class SDSDirectS3UploadFeature method upload.

@Override
public Node upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    final ThreadPool pool = ThreadPoolFactory.get("multipart", concurrency);
    try {
        final CreateFileUploadRequest createFileUploadRequest = new CreateFileUploadRequest().directS3Upload(true).timestampModification(status.getTimestamp() != null ? new DateTime(status.getTimestamp()) : null).size(TransferStatus.UNKNOWN_LENGTH == status.getLength() ? null : status.getLength()).parentId(Long.parseLong(nodeid.getVersionId(file.getParent(), new DisabledListProgressListener()))).name(file.getName());
        final CreateFileUploadResponse createFileUploadResponse = new NodesApi(session.getClient()).createFileUploadChannel(createFileUploadRequest, StringUtils.EMPTY);
        if (log.isDebugEnabled()) {
            log.debug(String.format("upload started for %s with response %s", file, createFileUploadResponse));
        }
        final Map<Integer, TransferStatus> etags = new HashMap<>();
        final List<PresignedUrl> presignedUrls = this.retrievePresignedUrls(createFileUploadResponse, status);
        final List<Future<TransferStatus>> parts = new ArrayList<>();
        final InputStream in;
        final String random = new UUIDRandomStringService().random();
        if (SDSNodeIdProvider.isEncrypted(file)) {
            in = new SDSTripleCryptEncryptorFeature(session, nodeid).encrypt(file, local.getInputStream(), status);
        } else {
            in = local.getInputStream();
        }
        try {
            // Full size of file
            final long size = status.getLength() + status.getOffset();
            long offset = 0;
            long remaining = status.getLength();
            for (int partNumber = 1; remaining >= 0; partNumber++) {
                final long length = Math.min(Math.max((size / (MAXIMUM_UPLOAD_PARTS - 1)), partsize), remaining);
                final PresignedUrl presignedUrl = presignedUrls.get(partNumber - 1);
                if (SDSNodeIdProvider.isEncrypted(file)) {
                    final Local temporary = temp.create(String.format("%s-%d", random, partNumber));
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Encrypted contents for part %d to %s", partNumber, temporary));
                    }
                    new StreamCopier(status, StreamProgress.noop).withAutoclose(false).withLimit(length).transfer(in, new BufferOutputStream(new FileBuffer(temporary)));
                    parts.add(this.submit(pool, file, temporary, throttle, listener, status, presignedUrl.getUrl(), presignedUrl.getPartNumber(), 0L, length, callback));
                } else {
                    parts.add(this.submit(pool, file, local, throttle, listener, status, presignedUrl.getUrl(), presignedUrl.getPartNumber(), offset, length, callback));
                }
                remaining -= length;
                offset += length;
                if (0L == remaining) {
                    break;
                }
            }
        } finally {
            in.close();
        }
        for (Future<TransferStatus> future : parts) {
            try {
                final TransferStatus part = future.get();
                etags.put(part.getPart(), part);
            } catch (InterruptedException e) {
                log.error("Part upload failed with interrupt failure");
                status.setCanceled();
                throw new ConnectionCanceledException(e);
            } catch (ExecutionException e) {
                log.warn(String.format("Part upload failed with execution failure %s", e.getMessage()));
                if (e.getCause() instanceof BackgroundException) {
                    throw (BackgroundException) e.getCause();
                }
                throw new BackgroundException(e.getCause());
            }
        }
        final CompleteS3FileUploadRequest completeS3FileUploadRequest = new CompleteS3FileUploadRequest().keepShareLinks(status.isExists() ? new HostPreferences(session.getHost()).getBoolean("sds.upload.sharelinks.keep") : false).resolutionStrategy(status.isExists() ? CompleteS3FileUploadRequest.ResolutionStrategyEnum.OVERWRITE : CompleteS3FileUploadRequest.ResolutionStrategyEnum.FAIL);
        if (status.getFilekey() != null) {
            final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class);
            final FileKey fileKey = reader.readValue(status.getFilekey().array());
            final EncryptedFileKey encryptFileKey = Crypto.encryptFileKey(TripleCryptConverter.toCryptoPlainFileKey(fileKey), TripleCryptConverter.toCryptoUserPublicKey(session.keyPair().getPublicKeyContainer()));
            completeS3FileUploadRequest.setFileKey(TripleCryptConverter.toSwaggerFileKey(encryptFileKey));
        }
        etags.forEach((key, value) -> completeS3FileUploadRequest.addPartsItem(new S3FileUploadPart().partEtag(value.getChecksum().hash).partNumber(key)));
        if (log.isDebugEnabled()) {
            log.debug(String.format("Complete file upload with %s for %s", completeS3FileUploadRequest, file));
        }
        new NodesApi(session.getClient()).completeS3FileUpload(completeS3FileUploadRequest, createFileUploadResponse.getUploadId(), StringUtils.EMPTY);
        // Polling
        final ScheduledThreadPool polling = new ScheduledThreadPool();
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicReference<BackgroundException> failure = new AtomicReference<>();
        final ScheduledFuture f = polling.repeat(new Runnable() {

            @Override
            public void run() {
                try {
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Query upload status for %s", createFileUploadResponse));
                    }
                    final S3FileUploadStatus uploadStatus = new NodesApi(session.getClient()).requestUploadStatusFiles(createFileUploadResponse.getUploadId(), StringUtils.EMPTY, null);
                    switch(uploadStatus.getStatus()) {
                        case "finishing":
                            // Expected
                            break;
                        case "transfer":
                            failure.set(new InteroperabilityException(uploadStatus.getStatus()));
                            done.countDown();
                            break;
                        case "error":
                            failure.set(new InteroperabilityException(uploadStatus.getErrorDetails().getMessage()));
                            done.countDown();
                            break;
                        case "done":
                            // Set node id in transfer status
                            nodeid.cache(file, String.valueOf(uploadStatus.getNode().getId()));
                            // Mark parent status as complete
                            status.withResponse(new SDSAttributesAdapter(session).toAttributes(uploadStatus.getNode())).setComplete();
                            done.countDown();
                            break;
                    }
                } catch (ApiException e) {
                    failure.set(new SDSExceptionMappingService(nodeid).map("Upload {0} failed", e, file));
                    done.countDown();
                }
            }
        }, new HostPreferences(session.getHost()).getLong("sds.upload.s3.status.period"), TimeUnit.MILLISECONDS);
        Uninterruptibles.awaitUninterruptibly(done);
        polling.shutdown();
        if (null != failure.get()) {
            throw failure.get();
        }
        return null;
    } catch (CryptoSystemException | InvalidFileKeyException | InvalidKeyPairException | UnknownVersionException e) {
        throw new TripleCryptExceptionMappingService().map("Upload {0} failed", e, file);
    } catch (ApiException e) {
        throw new SDSExceptionMappingService(nodeid).map("Upload {0} failed", e, file);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    } finally {
        temp.shutdown();
        // Cancel future tasks
        pool.shutdown(false);
    }
}
Also used : DisabledListProgressListener(ch.cyberduck.core.DisabledListProgressListener) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DateTime(org.joda.time.DateTime) NodesApi(ch.cyberduck.core.sds.io.swagger.client.api.NodesApi) PresignedUrl(ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl) ScheduledThreadPool(ch.cyberduck.core.threading.ScheduledThreadPool) CreateFileUploadResponse(ch.cyberduck.core.sds.io.swagger.client.model.CreateFileUploadResponse) InvalidFileKeyException(com.dracoon.sdk.crypto.error.InvalidFileKeyException) S3FileUploadStatus(ch.cyberduck.core.sds.io.swagger.client.model.S3FileUploadStatus) ConnectionCanceledException(ch.cyberduck.core.exception.ConnectionCanceledException) Local(ch.cyberduck.core.Local) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) CreateFileUploadRequest(ch.cyberduck.core.sds.io.swagger.client.model.CreateFileUploadRequest) UnknownVersionException(com.dracoon.sdk.crypto.error.UnknownVersionException) BackgroundException(ch.cyberduck.core.exception.BackgroundException) EncryptedFileKey(com.dracoon.sdk.crypto.model.EncryptedFileKey) FileBuffer(ch.cyberduck.core.io.FileBuffer) ThreadPool(ch.cyberduck.core.threading.ThreadPool) ScheduledThreadPool(ch.cyberduck.core.threading.ScheduledThreadPool) BufferOutputStream(ch.cyberduck.core.io.BufferOutputStream) InvalidKeyPairException(com.dracoon.sdk.crypto.error.InvalidKeyPairException) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) ExecutionException(java.util.concurrent.ExecutionException) FileKey(ch.cyberduck.core.sds.io.swagger.client.model.FileKey) EncryptedFileKey(com.dracoon.sdk.crypto.model.EncryptedFileKey) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) InputStream(java.io.InputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) UUIDRandomStringService(ch.cyberduck.core.UUIDRandomStringService) ScheduledFuture(java.util.concurrent.ScheduledFuture) S3FileUploadPart(ch.cyberduck.core.sds.io.swagger.client.model.S3FileUploadPart) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) TripleCryptExceptionMappingService(ch.cyberduck.core.sds.triplecrypt.TripleCryptExceptionMappingService) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) StreamCopier(ch.cyberduck.core.io.StreamCopier) CompleteS3FileUploadRequest(ch.cyberduck.core.sds.io.swagger.client.model.CompleteS3FileUploadRequest) ApiException(ch.cyberduck.core.sds.io.swagger.client.ApiException) CryptoSystemException(com.dracoon.sdk.crypto.error.CryptoSystemException)

Example 3 with PresignedUrl

use of ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl in project cyberduck by iterate-ch.

the class PresignedMultipartOutputStream method write.

@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
    try {
        if (null != canceled.get()) {
            throw canceled.get();
        }
        final byte[] content = Arrays.copyOfRange(b, off, len);
        final HttpEntity entity = EntityBuilder.create().setBinary(content).build();
        new DefaultRetryCallable<>(session.getHost(), new BackgroundExceptionCallable<Void>() {

            @Override
            public Void call() throws BackgroundException {
                final SDSApiClient client = session.getClient();
                try {
                    final List<PresignedUrl> target = new NodesApi(session.getClient()).generatePresignedUrlsFiles(new GeneratePresignedUrlsRequest().firstPartNumber(++partNumber).lastPartNumber(partNumber).size((long) content.length), createFileUploadResponse.getUploadId(), StringUtils.EMPTY).getUrls();
                    for (PresignedUrl url : target) {
                        final HttpPut request = new HttpPut(url.getUrl());
                        request.setEntity(entity);
                        request.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
                        request.setHeader(HttpHeaders.CONTENT_TYPE, MimeTypeService.DEFAULT_CONTENT_TYPE);
                        final HttpResponse response = client.getClient().execute(request);
                        try {
                            // Validate response
                            switch(response.getStatusLine().getStatusCode()) {
                                case HttpStatus.SC_OK:
                                    // Upload complete
                                    offset += content.length;
                                    if (response.containsHeader("ETag")) {
                                        etags.put(partNumber, response.getFirstHeader("ETag").getValue());
                                    } else {
                                        log.error(String.format("Missing ETag in response %s", response));
                                    }
                                    break;
                                default:
                                    EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity()));
                                    throw new SDSExceptionMappingService(nodeid).map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(response.getEntity())));
                            }
                        } catch (BackgroundException e) {
                            // Cancel upload on error reply
                            canceled.set(e);
                            throw e;
                        } finally {
                            EntityUtils.consume(response.getEntity());
                        }
                    }
                } catch (ApiException e) {
                    throw new SDSExceptionMappingService(nodeid).map("Upload {0} failed", e, file);
                } catch (HttpResponseException e) {
                    throw new DefaultHttpResponseExceptionMappingService().map(e);
                } catch (IOException e) {
                    throw new DefaultIOExceptionMappingService().map(e);
                }
                // Void
                return null;
            }
        }, overall).call();
    } catch (BackgroundException e) {
        throw new IOException(e.getMessage(), e);
    }
}
Also used : DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) BackgroundExceptionCallable(ch.cyberduck.core.threading.BackgroundExceptionCallable) NodesApi(ch.cyberduck.core.sds.io.swagger.client.api.NodesApi) PresignedUrl(ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl) GeneratePresignedUrlsRequest(ch.cyberduck.core.sds.io.swagger.client.model.GeneratePresignedUrlsRequest) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) BackgroundException(ch.cyberduck.core.exception.BackgroundException) ApiException(ch.cyberduck.core.sds.io.swagger.client.ApiException)

Aggregations

NodesApi (ch.cyberduck.core.sds.io.swagger.client.api.NodesApi)3 PresignedUrl (ch.cyberduck.core.sds.io.swagger.client.model.PresignedUrl)3 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)2 BackgroundException (ch.cyberduck.core.exception.BackgroundException)2 ApiException (ch.cyberduck.core.sds.io.swagger.client.ApiException)2 GeneratePresignedUrlsRequest (ch.cyberduck.core.sds.io.swagger.client.model.GeneratePresignedUrlsRequest)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 DisabledListProgressListener (ch.cyberduck.core.DisabledListProgressListener)1 Local (ch.cyberduck.core.Local)1 UUIDRandomStringService (ch.cyberduck.core.UUIDRandomStringService)1 ConnectionCanceledException (ch.cyberduck.core.exception.ConnectionCanceledException)1 InteroperabilityException (ch.cyberduck.core.exception.InteroperabilityException)1 DefaultHttpResponseExceptionMappingService (ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService)1 BufferOutputStream (ch.cyberduck.core.io.BufferOutputStream)1 FileBuffer (ch.cyberduck.core.io.FileBuffer)1 StreamCopier (ch.cyberduck.core.io.StreamCopier)1 HostPreferences (ch.cyberduck.core.preferences.HostPreferences)1 CompleteS3FileUploadRequest (ch.cyberduck.core.sds.io.swagger.client.model.CompleteS3FileUploadRequest)1 CreateFileUploadRequest (ch.cyberduck.core.sds.io.swagger.client.model.CreateFileUploadRequest)1