This repository has been archived by the owner on Nov 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 520
Build queue for --watch #1189
Merged
+329
−11
Merged
Build queue for --watch #1189
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
cebf823
Central build queue, w/ build from solution
06bdc5d
Fix some warnings
5c47ab4
Need to use -target and not -targets
7f518b5
Remove unnecessary function
298a24c
Handle failures building solution better
6835a9b
Merge branch 'dotnet:main' into build-queue
james-allan-lloyd 55129eb
Merge branch 'main' into build-queue
philliphoff 1616660
Styling updates.
philliphoff 3736765
Scaffold explicit start/stop of builds.
philliphoff e825a0e
More styling updates.
philliphoff 8ff450c
Cleanup working directory.
philliphoff 181a239
Make build result more consistent.
philliphoff b562362
Tweak logging.
philliphoff 1711ea5
Update formatting.
philliphoff 85440d5
Update more formatting.
philliphoff bb1ae72
Add locks for critical areas.
philliphoff b901e2d
Update schema and reference doc.
philliphoff 3acd282
Fix formatting.
philliphoff 5a7b5cd
Updates per PR feedback.
philliphoff 931558a
More updates per PR feedback.
philliphoff File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,293 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading; | ||
using System.Threading.Channels; | ||
using System.Threading.Tasks; | ||
using Microsoft.Build.Construction; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Microsoft.Tye.Hosting | ||
{ | ||
internal sealed class BuildWatcher : IAsyncDisposable | ||
{ | ||
private CancellationTokenSource? _cancellationTokenSource; | ||
private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1); | ||
private readonly ILogger _logger; | ||
private Task? _processor; | ||
private Channel<BuildRequest>? _queue; | ||
|
||
public BuildWatcher(ILogger logger) | ||
{ | ||
_logger = logger; | ||
} | ||
|
||
public Task StartAsync(string? solutionPath, string workingDirectory) | ||
{ | ||
return WithLockAsync( | ||
async () => | ||
{ | ||
await ResetAsync(); | ||
|
||
_queue = Channel.CreateUnbounded<BuildRequest>(); | ||
_cancellationTokenSource = new CancellationTokenSource(); | ||
_processor = Task.Run(() => ProcessTaskQueueAsync(_logger, _queue.Reader, solutionPath, workingDirectory, _cancellationTokenSource.Token)); | ||
}); | ||
} | ||
|
||
public Task StopAsync() | ||
{ | ||
return WithLockAsync(ResetAsync); | ||
} | ||
|
||
public async Task<int> BuildProjectFileAsync(string projectFilePath) | ||
{ | ||
var request = new BuildRequest(projectFilePath); | ||
|
||
await WithLockAsync( | ||
async () => | ||
{ | ||
if (_queue == null) | ||
{ | ||
throw new InvalidOperationException("The worker is not running."); | ||
} | ||
|
||
await _queue.Writer.WriteAsync(request); | ||
}); | ||
|
||
return await request.Task; | ||
} | ||
|
||
#region IAsyncDisposable Members | ||
|
||
public async ValueTask DisposeAsync() | ||
{ | ||
await WithLockAsync(ResetAsync); | ||
|
||
_lock.Dispose(); | ||
} | ||
|
||
#endregion | ||
|
||
private async Task WithLockAsync(Func<Task> action) | ||
{ | ||
await _lock.WaitAsync(); | ||
|
||
try | ||
{ | ||
await action(); | ||
} | ||
finally | ||
{ | ||
_lock.Release(); | ||
} | ||
} | ||
|
||
private async Task ResetAsync() | ||
{ | ||
if (_queue != null) | ||
{ | ||
_queue.Writer.TryComplete(); | ||
_queue = null; | ||
} | ||
|
||
if (_cancellationTokenSource != null) | ||
{ | ||
_cancellationTokenSource.Cancel(); | ||
_cancellationTokenSource.Dispose(); | ||
_cancellationTokenSource = null; | ||
} | ||
|
||
if (_processor != null) | ||
{ | ||
await _processor; | ||
|
||
_processor = null; | ||
} | ||
} | ||
|
||
private static string GetProjectName(SolutionFile solution, string projectFile) | ||
{ | ||
foreach (var project in solution.ProjectsInOrder) | ||
{ | ||
if (project.AbsolutePath == projectFile) | ||
{ | ||
return project.ProjectName; | ||
} | ||
} | ||
|
||
throw new InvalidOperationException($"Could not find project in solution: {projectFile}"); | ||
} | ||
|
||
private static async Task ProcessTaskQueueAsync( | ||
ILogger logger, | ||
ChannelReader<BuildRequest> requestReader, | ||
string? solutionPath, | ||
string workingDirectory, | ||
CancellationToken cancellationToken) | ||
{ | ||
logger.LogInformation("Build Watcher: Watching for builds..."); | ||
|
||
try | ||
{ | ||
while (await requestReader.WaitToReadAsync(cancellationToken)) | ||
{ | ||
var delay = TimeSpan.FromMilliseconds(250); | ||
|
||
logger.LogInformation("Build Watcher: Builds requested; waiting {DelayInMs}ms for more...", delay.TotalMilliseconds); | ||
|
||
await Task.Delay(delay); | ||
|
||
logger.LogInformation("Build Watcher: Getting requests..."); | ||
|
||
var requests = new List<BuildRequest>(); | ||
|
||
while (requestReader.TryRead(out var request)) | ||
{ | ||
requests.Add(request); | ||
} | ||
|
||
logger.LogInformation("Build Watcher: Processing {Count} requests...", requests.Count); | ||
|
||
var solution = (solutionPath != null) ? SolutionFile.Parse(solutionPath) : null; | ||
|
||
var solutionBatch = new Dictionary<string, List<BuildRequest>>(); // store the list of promises | ||
var projectBatch = new Dictionary<string, List<BuildRequest>>(); | ||
|
||
foreach (var request in requests) | ||
{ | ||
if (solution?.ProjectShouldBuild(request.ProjectFilePath) == true) | ||
{ | ||
if (!solutionBatch.ContainsKey(request.ProjectFilePath)) | ||
{ | ||
solutionBatch.Add(request.ProjectFilePath, new List<BuildRequest>()); | ||
} | ||
|
||
solutionBatch[request.ProjectFilePath].Add(request); | ||
} | ||
else | ||
{ | ||
// this will also prevent us building multiple times if a project is used by multiple services | ||
if (!projectBatch.ContainsKey(request.ProjectFilePath)) | ||
{ | ||
projectBatch.Add(request.ProjectFilePath, new List<BuildRequest>()); | ||
} | ||
|
||
projectBatch[request.ProjectFilePath].Add(request); | ||
} | ||
} | ||
|
||
async Task WithRequestCompletion(IEnumerable<BuildRequest> requests, Func<Task<int>> buildFunc) | ||
{ | ||
try | ||
{ | ||
int exitCode = await buildFunc(); | ||
|
||
foreach (var request in requests) | ||
{ | ||
request.Complete(exitCode); | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
foreach (var request in requests) | ||
{ | ||
request.Complete(ex); | ||
} | ||
} | ||
} | ||
|
||
var tasks = new List<Task>(); | ||
|
||
if (solutionBatch.Any()) | ||
{ | ||
var targets = String.Join(",", solutionBatch.Keys.Select(key => GetProjectName(solution!, key))); | ||
|
||
tasks.Add( | ||
WithRequestCompletion( | ||
solutionBatch.Values.SelectMany(x => x), | ||
async () => | ||
{ | ||
logger.LogInformation("Build Watcher: Building {Targets} of solution {SolutionPath}...", targets, solutionPath); | ||
|
||
var buildResult = await ProcessUtil.RunAsync("dotnet", $"msbuild {solutionPath} -target:{targets}", throwOnError: false, workingDirectory: workingDirectory, cancellationToken: cancellationToken); | ||
|
||
if (buildResult.ExitCode != 0) | ||
{ | ||
logger.LogInformation("Build Watcher: Solution build failed with exit code {ExitCode}: \r\n" + buildResult.StandardOutput, buildResult.ExitCode); | ||
} | ||
|
||
return buildResult.ExitCode; | ||
})); | ||
} | ||
|
||
foreach (var project in projectBatch) | ||
{ | ||
tasks.Add( | ||
WithRequestCompletion( | ||
project.Value, | ||
async () => | ||
{ | ||
logger.LogInformation("Build Watcher: Building project {ProjectPath}...", project.Key); | ||
|
||
var buildResult = await ProcessUtil.RunAsync("dotnet", $"build \"{project.Key}\" /nologo", throwOnError: false, workingDirectory: workingDirectory, cancellationToken: cancellationToken); | ||
|
||
if (buildResult.ExitCode != 0) | ||
{ | ||
logger.LogInformation("Build Watcher: Project build failed with exit code {ExitCode}: \r\n" + buildResult.StandardOutput, buildResult.ExitCode); | ||
} | ||
|
||
return buildResult.ExitCode; | ||
})); | ||
} | ||
|
||
logger.LogInformation("Build Watcher: Waiting for builds to complete..."); | ||
|
||
// NOTE: WithRequestCompletion() will trap exceptions so build errors should not bubble up from WhenAll(). | ||
|
||
await Task.WhenAll(tasks); | ||
|
||
logger.LogInformation("Build Watcher: Done with requests; waiting for more..."); | ||
} | ||
} | ||
catch (OperationCanceledException) | ||
{ | ||
// NO-OP: Trap exception due to cancellation. | ||
} | ||
catch (Exception ex) | ||
{ | ||
logger.LogError(ex, "Build Watcher: Error while processing builds."); | ||
} | ||
|
||
logger.LogInformation("Build Watcher: Done watching."); | ||
} | ||
|
||
private class BuildRequest | ||
{ | ||
private readonly TaskCompletionSource<int> _result = new TaskCompletionSource<int>(); | ||
|
||
public BuildRequest(string projectFilePath) | ||
{ | ||
ProjectFilePath = projectFilePath; | ||
} | ||
|
||
public string ProjectFilePath { get; } | ||
|
||
public Task<int> Task => _result.Task; | ||
|
||
public void Complete(int exitCode) | ||
{ | ||
_result.TrySetResult(exitCode); | ||
} | ||
|
||
public void Complete(Exception ex) | ||
{ | ||
_result.TrySetException(ex); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note for #1438, this code is not replacing "special characters" with an
_
in the targets.https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-build-specific-targets-in-solutions-by-using-msbuild-exe?view=vs-2022
(I believe that documentation has a bit of a bug in itself, that last "in the specified target name" should be "in the specified project name" to not be confused with the target name portion of -targets argument.)