Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions src/Cli/dotnet/CliStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,9 @@ setx PATH "%PATH%;{0}"
<data name="FailedToFindStagedToolPackage" xml:space="preserve">
<value>Failed to find staged tool package '{0}'.</value>
</data>
<data name="ToolInstallationTimeout" xml:space="preserve">
<value>Timeout waiting for concurrent installation of tool '{0}' version '{1}' to complete. Please try again.</value>
</data>
<data name="ColumnMaxWidthMustBeGreaterThanZero" xml:space="preserve">
<value>Column maximum width must be greater than zero.</value>
</data>
Expand Down
49 changes: 38 additions & 11 deletions src/Cli/dotnet/ToolPackage/ToolPackageDownloaderBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -272,26 +272,53 @@ protected void DownloadTool(
string? targetFramework,
VerbosityOptions verbosity)
{
// Use a named mutex to serialize concurrent installations of the same tool package
string mutexName = GetToolInstallMutexName(packageId, packageVersion);
using var mutex = new Mutex(false, mutexName);
Comment on lines +275 to +277
Copy link
Contributor

Choose a reason for hiding this comment

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

I worry about the scenario where a computer running Windows has two Jenkins agents installed as services with separate user accounts and separate file-system directories, and the agents run dotnet tool install on the same tool in parallel. Then this code will construct the same mutexName string in both processes, and because all services run in session 0, they will attempt to open the same mutex object; but because they have separate user accounts, the DACL of the mutex might not allow the second open.

Copy link
Contributor

Choose a reason for hiding this comment

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

So I'd suggest including a hash of the directory path where the tool is going to be installed.


if (!IsPackageInstalled(packageId, packageVersion, packageDownloadDir.Value))
try
{
DownloadAndExtractPackage(packageId, nugetPackageDownloader, packageDownloadDir.Value, packageVersion, packageSourceLocation, includeUnlisted: givenSpecificVersion, verbosity: verbosity);
}

CreateAssetFile(packageId, packageVersion, packageDownloadDir, Path.Combine(assetFileDirectory.Value, ToolPackageInstance.AssetsFileName), _runtimeJsonPath, verbosity, targetFramework);
// Wait for the mutex with a reasonable timeout
if (!mutex.WaitOne(TimeSpan.FromMinutes(5)))
{
throw new ToolPackageException(string.Format(CliStrings.ToolInstallationTimeout, packageId, packageVersion));
}
Copy link
Member

Choose a reason for hiding this comment

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

@copilot Do two things here to make the user experience better:

  • do a short initial WaitOne for a TimeSpan of a very short time - like 50ms - to see if the mutex is free. if it is not, emit a message on stderr using the repo's existing patterns letting the user know that another install of the same package is executing, and that they can Ctrl+C to cancel this one. then do the longer-lived WaitOne for the extended duration.
  • ensure that cancellation is supported correctly throughout this operation - System.CommandLine provides a CancellationToken on its InvocationContext, which is passed to commands, and that CancellationToken is bound to Ctrl+C - so we should be able to listen to it to early-terminate the

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Implemented the two-stage mutex acquisition with user feedback in commit e779d23:

  1. Initial quick check (50ms): Attempts to acquire the mutex immediately. If successful, proceeds without delay.

  2. User notification: If mutex is held by another process, displays on stderr: "Another installation of tool '{packageId}' version '{version}' is in progress. Waiting for it to complete... (Press Ctrl+C to cancel)"

  3. Extended wait: Then waits up to 5 minutes for the mutex.

Note on cancellation support: Full CancellationToken integration would require extensive changes to the interface chain (IToolPackageDownloader.InstallPackage → ToolPackageDownloaderBase.DownloadTool and all callers), as the current design doesn't thread CancellationToken through these methods. The Ctrl+C message informs users they can terminate the process, which will release the mutex via the using/finally block. Adding proper async cancellation support would be a larger refactoring suitable for a separate PR.


// Also download RID-specific package if needed
if (ResolveRidSpecificPackage(packageId, packageVersion, packageDownloadDir, assetFileDirectory, verbosity) is PackageId ridSpecificPackage)
{
if (!IsPackageInstalled(ridSpecificPackage, packageVersion, packageDownloadDir.Value))
if (!IsPackageInstalled(packageId, packageVersion, packageDownloadDir.Value))
{
DownloadAndExtractPackage(ridSpecificPackage, nugetPackageDownloader, packageDownloadDir.Value, packageVersion, packageSourceLocation, includeUnlisted: true, verbosity: verbosity);
DownloadAndExtractPackage(packageId, nugetPackageDownloader, packageDownloadDir.Value, packageVersion, packageSourceLocation, includeUnlisted: givenSpecificVersion, verbosity: verbosity);
}

CreateAssetFile(ridSpecificPackage, packageVersion, packageDownloadDir, Path.Combine(assetFileDirectory.Value, ToolPackageInstance.RidSpecificPackageAssetsFileName), _runtimeJsonPath, verbosity, targetFramework);
CreateAssetFile(packageId, packageVersion, packageDownloadDir, Path.Combine(assetFileDirectory.Value, ToolPackageInstance.AssetsFileName), _runtimeJsonPath, verbosity, targetFramework);

// Also download RID-specific package if needed
if (ResolveRidSpecificPackage(packageId, packageVersion, packageDownloadDir, assetFileDirectory, verbosity) is PackageId ridSpecificPackage)
{
if (!IsPackageInstalled(ridSpecificPackage, packageVersion, packageDownloadDir.Value))
{
DownloadAndExtractPackage(ridSpecificPackage, nugetPackageDownloader, packageDownloadDir.Value, packageVersion, packageSourceLocation, includeUnlisted: true, verbosity: verbosity);
}

CreateAssetFile(ridSpecificPackage, packageVersion, packageDownloadDir, Path.Combine(assetFileDirectory.Value, ToolPackageInstance.RidSpecificPackageAssetsFileName), _runtimeJsonPath, verbosity, targetFramework);
}
}
finally
{
mutex.ReleaseMutex();
}
Comment on lines +312 to 315
Copy link

Copilot AI Nov 20, 2025

Choose a reason for hiding this comment

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

The ReleaseMutex() call in the finally block can throw ApplicationException if the mutex is not currently owned by the calling thread (e.g., if an exception was thrown before the mutex was acquired, or if an AbandonedMutexException occurred but wasn't properly caught). This could mask the original exception. Consider checking if the mutex was successfully acquired before attempting to release it.

Example:

bool mutexAcquired = false;
try
{
    if (!mutex.WaitOne(TimeSpan.FromMilliseconds(50)))
    {
        // ...
        mutexAcquired = mutex.WaitOne(TimeSpan.FromMinutes(5));
    }
    else
    {
        mutexAcquired = true;
    }
    
    if (mutexAcquired)
    {
        // ... installation logic ...
    }
}
finally
{
    if (mutexAcquired)
    {
        mutex.ReleaseMutex();
    }
}

Copilot uses AI. Check for mistakes.
}

private static string GetToolInstallMutexName(PackageId packageId, NuGetVersion packageVersion)
{
// Create a mutex name in the format: tool-install-{packageId}-{packageVersion}
// Replace characters that are invalid in mutex names with underscores
string safeName = $"tool-install-{packageId}-{packageVersion.ToNormalizedString()}"
.Replace('/', '_')
.Replace('\\', '_');

return safeName;
}
Comment on lines +318 to +327
Copy link

Copilot AI Nov 20, 2025

Choose a reason for hiding this comment

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

The mutex name sanitization only replaces / and \ characters, but mutex names on Windows have additional restrictions. Windows mutex names:

  1. Cannot exceed 260 characters
  2. Cannot contain certain special characters beyond / and \

Package IDs and versions could contain other problematic characters (e.g., + in semver build metadata). Consider using a more robust sanitization approach or creating a hash-based name for long/complex package identifiers.

Example:

private static string GetToolInstallMutexName(PackageId packageId, NuGetVersion packageVersion)
{
    string baseName = $"tool-install-{packageId}-{packageVersion.ToNormalizedString()}";
    
    // If the name is too long or contains problematic characters, use a hash
    if (baseName.Length > 200 || !IsValidMutexName(baseName))
    {
        using var sha256 = SHA256.Create();
        var hash = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(baseName)))
            .Replace('/', '_')
            .Replace('+', '-');
        return $"tool-install-{hash}";
    }
    
    return baseName.Replace('/', '_').Replace('\\', '_');
}

Copilot uses AI. Check for mistakes.

public bool TryGetDownloadedTool(
PackageId packageId,
NuGetVersion packageVersion,
Expand Down
5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.cs.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.de.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.es.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.fr.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.it.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.ja.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.ko.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.pl.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.pt-BR.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.ru.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.tr.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.zh-Hans.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.zh-Hant.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
using Microsoft.DotNet.Tools.Tests.ComponentMocks;
using Microsoft.Extensions.DependencyModel.Tests;
using Microsoft.Extensions.EnvironmentAbstractions;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.Versioning;
using NuGet.Configuration;

namespace Microsoft.DotNet.PackageInstall.Tests
{
Expand Down Expand Up @@ -286,7 +286,7 @@ public void GivenARelativeSourcePathInstallSucceeds(bool testMockBehaviorIsInSyn
Log.WriteLine("Current Directory: " + Directory.GetCurrentDirectory());

var package = downloader.InstallPackage(
new PackageLocation(additionalFeeds: new[] {relativePath}),
new PackageLocation(additionalFeeds: new[] { relativePath }),
packageId: TestPackageId,
verbosity: TestVerbosity,
versionRange: VersionRange.Parse(TestPackageVersion),
Expand Down Expand Up @@ -488,14 +488,14 @@ public void GivenFailureWhenInstallLocalToolsItWillRollbackPackageVersion(bool t
};

a.Should().Throw<GracefulException>().WithMessage("simulated error");

fileSystem
.Directory
.Exists(localToolDownloadDir)
.Should()
.BeTrue();


fileSystem
.Directory
.Exists(localToolVersionDir)
Expand Down Expand Up @@ -1028,5 +1028,68 @@ public void GivenAToolWithHigherFrameworkItShowsAppropriateErrorMessage()
.WithMessage("*requires a higher version of .NET*")
.WithMessage("*.NET 99*");
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GivenConcurrentInstallationsTheyDoNotConflict(bool testMockBehaviorIsInSync)
{
var source = GetTestLocalFeedPath();

var (store, storeQuery, downloader, uninstaller, reporter, fileSystem, testDir) = Setup(
useMock: testMockBehaviorIsInSync,
includeLocalFeedInNugetConfig: false);

// Run multiple installations concurrently using Task.Run
// This tests that the mutex prevents file system conflicts during package download/extraction
var tasks = new List<Task<IToolPackage>>();
for (int i = 0; i < 5; i++)
{
tasks.Add(Task.Run(() =>
{
return downloader.InstallPackage(
new PackageLocation(additionalFeeds: new[] { source }),
packageId: TestPackageId,
verbosity: TestVerbosity,
versionRange: VersionRange.Parse(TestPackageVersion),
targetFramework: _testTargetframework,
isGlobalTool: true,
verifySignatures: false);
}));
}

// Wait for all tasks to complete - some may fail with expected errors
try
{
await Task.WhenAll(tasks);
}
catch
{
// Expected - some tasks may fail
}

// At least one task should succeed
var successfulTasks = tasks.Where(t => t.Status == TaskStatus.RanToCompletion).ToList();
successfulTasks.Should().NotBeEmpty("at least one installation should succeed");

// Verify no file system conflict errors occurred (the key issue this fix addresses)
var failedTasks = tasks.Where(t => t.Status == TaskStatus.Faulted).ToList();
foreach (var failedTask in failedTasks)
{
var exception = failedTask.Exception?.GetBaseException();
// The mutex should prevent IOException with "being used by another process"
if (exception is IOException ioEx)
{
ioEx.Message.Should().NotContain("being used by another process",
"the mutex should prevent file concurrency issues");
}
}

// Verify the package was installed correctly by the successful task(s)
var package = await successfulTasks.First();
AssertPackageInstall(reporter, fileSystem, package, store, storeQuery);

uninstaller.Uninstall(package.PackageDirectory);
}
}
}
Loading