Skip to content

TransferManager callbacks with async upload/download, impossible to AbortMultipartUpload #647

Closed

Description

@diablodale

Hi. I think I found a limitation of TransferManager when async uploading multiple files -> handling cancel/failed -> cleanup with AbortMultipartUpload.

Setup

SDK 1.1.42 on Windows x64
Visual Studio 2017 using 2015 toolkit (v140)

Repro

Below is pseudocode. Assume this is within a class method

vector<string> filePaths {...it has be loaded with multiple strings...};
TransferManagerConfiguration transferConfig;
transferConfig.s3Client = s3Client;

transferConfig.transferStatusUpdatedCallback = [this](const TransferManager* transferManager, const TransferHandle& hTransfer) {
    TransferStatus transferStatus = hTransfer.GetStatus();
    switch (transferStatus) {
        case TransferStatus::CANCELED:
        case TransferStatus::FAILED:
            if (hTransfer.IsMultipart()) {
                // need shared_ptr<TransferHandle> created from UploadFile(), but it is not available
                const_cast<TransferManager*>(transferManager)->AbortMultipartUpload(????????);
            }
            break;
    };
};

auto transferManager = TransferManager::Create(transferConfig);
for (const auto& filePath : filePaths) {
    auto hUpload = transferManager->UploadFile(filePath.c_str(), bucketname, keyname, "binary/octet-stream", Aws::Map<Aws::String, Aws::String>());
}

This method used in the test case

std::shared_ptr<TransferHandle> requestPtr(nullptr);
works only because the test case is synchronous. This is because the lambda capture of the shared_ptr<TransferHandle> requestPtr is by reference and the codebase does synchronous uploads due to WaitUntilFinished(). Therefore in that codebase requestPtr will correctly point to the one and only upload handle.

Contrast that to my example above, the loop at the bottom initiates multiple uploads. There is no waiting with a WaitUntilFinished(). Instead, the example code is asynchronous and I manage using the callbacks. Therefore, the equivalent shared_ptr<TransferHandle> hUpload rapidly changes and is almost guaranteed to not contain the same TransferHandle that is passed into the lambda as a parameter. Therefore, the codebase no longer has a shared_ptr<TransferHandle> that is needed to cleanup a failed/cancelled file with AbortMultipartUpload().

I don't think changing the lambda capture of shared_ptr<TransferHandle> to by-copy helps. Doing so would increment the refCount to the current in-the-moment shared_ptr containing nullptr when the lambda is defined. Later, when the loop starts and the first assignment to requestPtr occurs, requestPtr points to new shared_ptr that is created by UploadFile(). The lambda's by-copy capture of shared_ptr<TransferHandle> contains nullptr and has a refCount of 1 since the lambda is the only code that now has a reference.

A change/adapt of the SDK's api can likely resolve this. Transfer status updates are triggered with TriggerTransferStatusUpdatedCallback. See one example at

TriggerTransferStatusUpdatedCallback(*handle);

If instead the code was TriggerTransferStatusUpdatedCallback(handle) with no dereference, then a shared_ptr would be passed and with a few SDK tweaks would reach the lambda as a shared_ptr. Naturally, all functionality of today's naked pointer is possible + additional goodness like being able to call AbortMultipartUpload(), RetryUpload(), and other APIs needed for async scenarios.

Activity

  1. singku commented on Sep 4, 2017

    @singku
    Contributor

    The handle passed to lambda function is the handle you want to manipulate. During the for loop, the
    returned handle hUpload is changing, that's correct, but it doesn't affect the transferManager to call transferStatusUpdatedCallback with correct handle.

  2. diablodale commented on Sep 4, 2017

    @diablodale
    ContributorAuthor

    That is impossible. To remind you, AbortMultipartUpload() requires a shared_ptr.
    The param into the callback is only a raw TransferHandle*. The SDK API will not accept that raw pointer.

  3. diablodale commented on Sep 4, 2017

    @diablodale
    ContributorAuthor

    Meanwhile, while we discuss that a shared_ptr<TransferManager> is a more flexible and capable param for the SDK to provide the callback...

    ...a found an (untested) workaround for at least the AbortMultipartUpload() api. First, adjust the lamba to capture by-copy the shared_ptr<S3Client> assigned to the TransferManagerConfiguration. Then the following synchronous :-( code may work when put into the lambda for transferStatusUpdatedCallback

    Aws::S3::Model::AbortMultipartUploadRequest abortRequest;
    abortRequest.WithBucket(hTransfer.GetBucketName())
      .WithKey(hTransfer.GetKey())
      .WithUploadId(hTransfer.GetMultiPartId());
    auto abortOutcome(s3Client->AbortMultipartUpload(abortRequest));
  4. singku commented on Sep 4, 2017

    @singku
    Contributor

    I should say that the handle has the correct information you want to manipulate. True, it's not the same handle as returned by UploadFile, it's just a copy from shared_ptr handle. I think it's better to update the lambda function parameter type. Otherwise, if the refCnt of shared_ptr became zero and freed the mem, the copied handle will have wrong info.

  5. diablodale commented on Sep 4, 2017

    @diablodale
    ContributorAuthor

    I do not see the existing raw pointer works broadly in the callback. For example, do you know a technique for RetryUpload() to work?

    Inside transferStatusUpdatedCallback we have the TransferManager. We do not have shared_ptr<TransferHandle>.

    How can we do the following in transferStatusUpdatedCallback? For this test scenario, TransferHandle.GetStatus() = FAILED.

    TransferStatus transferStatus = hTransfer.GetStatus();
    switch (transferStatus) {
      case TransferStatus::FAILED:
        requestPtr = transferManager->RetryUpload(hTransfer.GetTargetFilePath(), ????????);

    Again, we need the shared_ptr<TransferHandle>. The raw pointer won't work and I can't use my S3Client workaround.

    This scenario is the asynchronous version of the test cases' synchronous approach at

    requestPtr = transferManager->RetryUpload(cancelTestFileName, requestPtr);

  6. diablodale commented on Sep 4, 2017

    @diablodale
    ContributorAuthor

    TransferManager does not appear to be safe in async mode. I think this callback problem above is a symptom of TransferManager not being designed for async thread-safe usage. In general, all of the threads doing work in TransferManager should have copies of POD and shared_ptrs to more complex data/objects.

    Crashes occur when the function that created the TransferManager and TransferHandle ends. Both of these objects are automatics of shared_ptr<TransferManager> and shared_ptr<TransferHandle> created from TransferManager->UploadFile()`. As automatics, they go out of scope when the function ends regardless of the TransferManager worker threads. The two automatics are destroyed or their refCount decremented and destroyed if the refCount is zero. I suspect the worker threads are continuing to run.

    Using the simple async code at the top of this issue, I can reproduce a crash that usually occurs one of two places. FYI, you can remove the entire transferConfig.transferStatusUpdatedCallback = assignment. It will crash without it.

    • AWS's ResourceManager Aws::Utils::ExclusiveOwnershipResourceManager::Acquire()
    • TransferManager Aws::Transfer::TransferManager::DoSinglePartUpload() on the line auto putObjectRequest = m_transferConfig.putObjectTemplate;

    In the 2nd, I think the m_transferConfig is in memory, but the putObjectTemplate is not valid.

    The trigger for the crash is when hUpload->WaitUntilFinished(); is not used. If not used, and your function ends, the crash occurs.

    100% of the test cases in aws-sdk-cpp/aws-cpp-sdk-transfer-tests/TransferTests.cpp use WaitUntilFinished(). Therefore, the async scenarios have not been tested.

    No known workaround. You must use WaitUntilFinished()

  7. marcomagdy commented on Sep 5, 2017

    @marcomagdy
    Contributor

    TransferManager does not appear to be safe in async mode.
    No known workaround. You must use WaitUntilFinished()

    @diablodale That's not true. A more accurate statement would be, you must ensure the lifetime of TransferManager outlasts the lifetime of the worker threads doing uploads/downloads. WaitUntilFinished() is one way to achieve that. You can do that in other ways depending on your application's logic.

    You are right about the parameter type in the callback. It needs to be a shared_ptr<TransferHandle>.

  8. marcomagdy commented on Sep 5, 2017

    @marcomagdy
    Contributor

    Actually, we do ensure the lifetime of TransferManager outlasts the worker threads. see here.
    So, even though you're getting a raw pointer to TansferManager in the callback, it's guaranteed to be a valid pointer and not a dangling one.

    A sample crashing code would be helpful if you can provide one.

  9. diablodale commented on Sep 5, 2017

    @diablodale
    ContributorAuthor

    The relevant code is at the top as I described.

    Using the simple async code at the top of this issue, I can reproduce a crash that usually occurs one of two places. FYI, you can remove the entire transferConfig.transferStatusUpdatedCallback = assignment. It will crash without it.

    This is not a console "I only have a main(), only one main thread, and then I die" application. Instead, this is a windows app which has UI stuff going on. And when, for example, a button is pressed, a thread calls a myS3Class::myupload() method of a C++ class dedicated to S3 (e.g. has member var of a shared_ptr). Insert the example code at the top in that class. With the files, just send one file...no need for multiple. Make the file size (or your connection) such that the upload will take ~5 seconds.

    You should get a crash. The thread that calls myupload() will zoom through the entirely of the method in a few milliseconds and exit the method. Meanwhile, a worker thread somewhere is trying to upload. And then a crash.

  10. added
    bug
    on Sep 5, 2017
  11. marcomagdy commented on Sep 5, 2017

    @marcomagdy
    Contributor

    @diablodale ok, I see the problem.
    To summarize this thread, there're two separate issues at hand here:

    1. The callback parameter type being a raw pointer is not very useful when all of TransferManager methods require a shared_ptr. (I need to check if fixing this will be a breaking change, if not will get it fixed ASAP).
    2. The race condition when TransferManager goes out of scope before the worker thread gets a chance to +1 its lifetime. (I'll get this patched today)
  12. diablodale commented on Sep 5, 2017

    @diablodale
    ContributorAuthor

    For (1), you are welcome to expand the param sig to additionally include a shared_ptr. Dual interfaces. Or make an additional interface "...Ex" ;-) Ack-ack!

    For (2), I made time today to write a simple repro project of the crash. I used VS2017 to make a boilerplate windows application.

    Code is here tm_issue647.zip

    Install VS2017 with C++ support for native Windows applications and the optional v140 toolchain. You may (or may not) be able to compile this project with VS2015 as the vsproj files/options changed.

    If you need to hack the source into a new VS project, then I am using the NuGet packages for aws, s3, and transfermgr. The version is 1.1.42. I am statically linking all three packages. The app should be compiled using the v140 toolchain and make an Windows EXE file. I am not using precompiled headers.

    1. Adjust the code at the top of MyS3.cpp to have your bucket, key, and local file for uploading. Make the upload file such that it will take 5+ seconds to upload.
    2. Compile it.
    3. When you see the UI, the code has already initialized AWS and created an S3 client.
    4. Choose File/upload. This will start using TransferManager code and start an upload with it.
    5. CRASH

    If you want to not crash. Then uncomment line 35 of MyS3.cpp so that the code will hUpload->WaitUntilFinished();

  13. marcomagdy commented on Sep 25, 2017

    @marcomagdy
    Contributor

    @diablodale this should be fixed now in v1.2.0.

    • TransferManager does not own its thread-executor, and all the worker threads spawned by it will be joined if the life of the thread-executor ends.
    • TransferHandle parameters in TransferManager callbacks are now passed as shared_ptr.

    Please reopen this issue if you're still experiencing the same problem.
    Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions