Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 83 additions & 4 deletions cpp/src/arrow/filesystem/s3fs.cc
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,14 @@ std::shared_ptr<S3RetryStrategy> S3RetryStrategy::GetAwsStandardRetryStrategy(
static_cast<long>(max_attempts))); // NOLINT: runtime/int
}

namespace {

// Defined below, next to S3ClientFinalizer.
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> MakeFinalizableCredentialsProvider(
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> provider);

} // namespace

// -----------------------------------------------------------------------
// S3Options implementation

Expand All @@ -234,8 +242,8 @@ S3Options::S3Options() {
}

void S3Options::ConfigureDefaultCredentials() {
credentials_provider =
std::make_shared<Aws::Auth::DefaultAWSCredentialsProviderChain>();
credentials_provider = MakeFinalizableCredentialsProvider(
std::make_shared<Aws::Auth::DefaultAWSCredentialsProviderChain>());
credentials_kind = S3CredentialsKind::Default;
}

Expand Down Expand Up @@ -266,8 +274,8 @@ void S3Options::ConfigureAssumeRoleWithWebIdentityCredentials() {
// The AWS SDK uses environment variables AWS_DEFAULT_REGION,
// AWS_ROLE_ARN, AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_SESSION_NAME
// to configure the required credentials
credentials_provider =
std::make_shared<Aws::Auth::STSAssumeRoleWebIdentityCredentialsProvider>();
credentials_provider = MakeFinalizableCredentialsProvider(
std::make_shared<Aws::Auth::STSAssumeRoleWebIdentityCredentialsProvider>());
credentials_kind = S3CredentialsKind::WebIdentity;
}

Expand Down Expand Up @@ -900,8 +908,47 @@ class S3ClientHolder {
std::shared_ptr<S3Client> client_;
};

// Credentials provider wrapper whose underlying provider is released by
// FinalizeS3(), even if S3Options copies outlive it. CRT-based providers
// (e.g. STS web identity) hold a reference to the default ClientBootstrap
// and would otherwise make Aws::ShutdownAPI() block forever (GH-50188).
class FinalizableCredentialsProvider : public Aws::Auth::AWSCredentialsProvider {
public:
explicit FinalizableCredentialsProvider(
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> provider)
: provider_(std::move(provider)) {}

Aws::Auth::AWSCredentials GetAWSCredentials() override {
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> provider;
{
std::unique_lock lock(mutex_);
provider = provider_;
}
if (!provider) {
// S3 was finalized
return {};
}
return provider->GetAWSCredentials();
}

void Finalize() {
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> provider;
{
std::unique_lock lock(mutex_);
provider = std::move(provider_);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: maybe a comment so intent is clear.

Suggested change
provider = std::move(provider_);
// Don't reset as provider's destructor could run while mutex is locked and could deadlock
provider = std::move(provider_);

}
// Do not hold mutex while the provider destructor potentially runs
}

private:
std::mutex mutex_;
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> provider_;
};

class S3ClientFinalizer : public std::enable_shared_from_this<S3ClientFinalizer> {
using ClientHolderList = std::vector<std::weak_ptr<S3ClientHolder>>;
using CredentialsProviderList =
std::vector<std::weak_ptr<FinalizableCredentialsProvider>>;

public:
Result<std::shared_ptr<S3ClientHolder>> AddClient(std::shared_ptr<S3Client> client) {
Expand All @@ -921,11 +968,27 @@ class S3ClientFinalizer : public std::enable_shared_from_this<S3ClientFinalizer>
return holder;
}

void AddCredentialsProvider(
const std::shared_ptr<FinalizableCredentialsProvider>& provider) {
std::unique_lock lock(mutex_);
if (finalized_) {
lock.unlock();
provider->Finalize();
return;
}
auto end = std::remove_if(
providers_.begin(), providers_.end(),
[](std::weak_ptr<FinalizableCredentialsProvider> p) { return p.expired(); });
providers_.erase(end, providers_.end());
Comment on lines +979 to +982

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I think this could be simplified as we required C++ 20 now but we would require #include <vector> too. We can follow up this simplification pattern afterwards as we could do with client too and this PR shouldn't grow more.

Suggested change
auto end = std::remove_if(
providers_.begin(), providers_.end(),
[](std::weak_ptr<FinalizableCredentialsProvider> p) { return p.expired(); });
providers_.erase(end, providers_.end());
std::erase_if(providers_, [](const auto& p) { return p.expired(); });

providers_.emplace_back(provider);
}

void Finalize() {
std::unique_lock lock(mutex_);
finalized_ = true;

ClientHolderList finalizing = std::move(holders_);
CredentialsProviderList finalizing_providers = std::move(providers_);
lock.unlock(); // avoid lock ordering issue with S3ClientHolder::Finalize

// Finalize all client holders, such that no S3Client remains alive
Expand All @@ -936,6 +999,14 @@ class S3ClientFinalizer : public std::enable_shared_from_this<S3ClientFinalizer>
holder->Finalize();
}
}
// Then release the credentials providers, which S3Options instances
// may still reference (GH-50188).
for (auto&& weak_provider : finalizing_providers) {
auto provider = weak_provider.lock();
if (provider) {
provider->Finalize();
}
}
}

auto LockShared() { return std::shared_lock(mutex_); }
Expand All @@ -945,6 +1016,7 @@ class S3ClientFinalizer : public std::enable_shared_from_this<S3ClientFinalizer>

std::shared_mutex mutex_;
ClientHolderList holders_;
CredentialsProviderList providers_;
bool finalized_ = false;
};

Expand Down Expand Up @@ -1002,6 +1074,13 @@ Result<std::shared_ptr<S3ClientHolder>> GetClientHolder(
return GetClientFinalizer()->AddClient(std::move(client));
}

std::shared_ptr<Aws::Auth::AWSCredentialsProvider> MakeFinalizableCredentialsProvider(
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> provider) {
auto wrapped = std::make_shared<FinalizableCredentialsProvider>(std::move(provider));
GetClientFinalizer()->AddCredentialsProvider(wrapped);
return wrapped;
}

// -----------------------------------------------------------------------
// S3 client factory: build S3Client from S3Options

Expand Down
22 changes: 22 additions & 0 deletions python/pyarrow/tests/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2158,6 +2158,28 @@ def test_s3_finalize_region_resolver():
subprocess.check_call([sys.executable, "-c", code])


@pytest.mark.s3
@pytest.mark.parametrize("explicit_finalize", [False, True])
def test_s3_finalize_with_live_web_identity_fs(tmp_path, explicit_finalize):
# GH-50188: finalize_s3() (or exit) used to hang if a filesystem using
# web identity credentials was still alive. No network access needed.
token_file = tmp_path / "token"
token_file.write_text("dummy-token")
env = dict(os.environ,
AWS_WEB_IDENTITY_TOKEN_FILE=str(token_file),
AWS_ROLE_ARN="arn:aws:iam::123456789012:role/dummy",
AWS_REGION="us-east-1")
code = f"""if 1:
from pyarrow.fs import S3FileSystem, finalize_s3

# Keep the filesystem alive until after S3 finalization
fs = S3FileSystem(region='us-east-1')
if {explicit_finalize}:
finalize_s3()
"""
subprocess.run([sys.executable, "-c", code], env=env, check=True, timeout=60)


@pytest.mark.processes
@pytest.mark.threading
@pytest.mark.s3
Expand Down
Loading