-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
BuildManager.cs
3271 lines (2809 loc) · 146 KB
/
BuildManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.BackEnd.SdkResolution;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Eventing;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Experimental;
using Microsoft.Build.Experimental.ProjectCache;
using Microsoft.Build.FileAccesses;
using Microsoft.Build.Framework;
using Microsoft.Build.Framework.Telemetry;
using Microsoft.Build.Graph;
using Microsoft.Build.Internal;
using Microsoft.Build.Logging;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.Debugging;
using Microsoft.NET.StringTools;
using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord;
using LoggerDescription = Microsoft.Build.Logging.LoggerDescription;
#nullable disable
namespace Microsoft.Build.Execution
{
/// <summary>
/// This class is the public entry point for executing builds.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Refactoring at the end of Beta1 is not appropriate.")]
public class BuildManager : INodePacketHandler, IBuildComponentHost, IDisposable
{
// TODO: Figure out a more elegant way to do this.
// The rationale for this is that we can detect during design-time builds in the Evaluator (which populates this) that the project cache will be used so that we don't
// need to evaluate the project at build time just to figure that out, which would regress perf for scenarios which don't use the project cache.
internal static ConcurrentDictionary<ProjectCacheDescriptor, ProjectCacheDescriptor> ProjectCacheDescriptors { get; } = new(ProjectCacheDescriptorEqualityComparer.Instance);
/// <summary>
/// The object used for thread-safe synchronization of static members.
/// </summary>
private static readonly Object s_staticSyncLock = new Object();
/// <summary>
/// The object used for thread-safe synchronization of BuildManager shared data and the Scheduler.
/// </summary>
private readonly Object _syncLock = new Object();
/// <summary>
/// The singleton instance for the BuildManager.
/// </summary>
private static BuildManager s_singletonInstance;
/// <summary>
/// The next build id;
/// </summary>
private static int s_nextBuildId;
/// <summary>
/// The next build request configuration ID to use.
/// These must be unique across build managers, as they
/// are used as part of cache file names, for example.
/// </summary>
private static int s_nextBuildRequestConfigurationId;
/// <summary>
/// The cache for build request configurations.
/// </summary>
private IConfigCache _configCache;
/// <summary>
/// The cache for build results.
/// </summary>
private IResultsCache _resultsCache;
/// <summary>
/// The object responsible for creating and managing nodes.
/// </summary>
private INodeManager _nodeManager;
/// <summary>
/// The object responsible for creating and managing task host nodes.
/// </summary>
private INodeManager _taskHostNodeManager;
/// <summary>
/// The object which determines which projects to build, and where.
/// </summary>
private IScheduler _scheduler;
/// <summary>
/// The node configuration to use for spawning new nodes.
/// </summary>
private NodeConfiguration _nodeConfiguration;
/// <summary>
/// Any exception which occurs on a logging thread will go here.
/// </summary>
private ExceptionDispatchInfo _threadException;
/// <summary>
/// Set of active nodes in the system.
/// </summary>
private readonly HashSet<NGen<int>> _activeNodes;
/// <summary>
/// Event signalled when all nodes have shutdown.
/// </summary>
private AutoResetEvent _noNodesActiveEvent;
/// <summary>
/// Mapping of nodes to the configurations they know about.
/// </summary>
private readonly Dictionary<NGen<int>, HashSet<NGen<int>>> _nodeIdToKnownConfigurations;
/// <summary>
/// Flag indicating if we are currently shutting down. When set, we stop processing packets other than NodeShutdown.
/// </summary>
private bool _shuttingDown;
/// <summary>
/// CancellationTokenSource to use for async operations. This will be cancelled when we are shutting down to cancel any async operations.
/// </summary>
private CancellationTokenSource _executionCancellationTokenSource;
/// <summary>
/// The current state of the BuildManager.
/// </summary>
private BuildManagerState _buildManagerState;
/// <summary>
/// The name given to this BuildManager as the component host.
/// </summary>
private readonly string _hostName;
/// <summary>
/// The parameters with which the build was started.
/// </summary>
private BuildParameters _buildParameters;
/// <summary>
/// The current pending and active submissions.
/// </summary>
/// <remarks>
/// { submissionId, BuildSubmission }
/// </remarks>
private readonly Dictionary<int, BuildSubmission> _buildSubmissions;
/// <summary>
/// The current pending and active graph build submissions.
/// </summary>
/// <remarks>
/// { submissionId, GraphBuildSubmission }
/// </remarks>
private readonly Dictionary<int, GraphBuildSubmission> _graphBuildSubmissions;
/// <summary>
/// Event signalled when all build submissions are complete.
/// </summary>
private AutoResetEvent _noActiveSubmissionsEvent;
/// <summary>
/// The overall success of the build.
/// </summary>
private bool _overallBuildSuccess;
/// <summary>
/// The next build submission id.
/// </summary>
private int _nextBuildSubmissionId;
/// <summary>
/// The last BuildParameters used for building.
/// </summary>
private bool? _previousLowPriority = null;
/// <summary>
/// Mapping of unnamed project instances to the file names assigned to them.
/// </summary>
private readonly Dictionary<ProjectInstance, string> _unnamedProjectInstanceToNames;
/// <summary>
/// The next ID to assign to a project which has no name.
/// </summary>
private int _nextUnnamedProjectId;
/// <summary>
/// The build component factories.
/// </summary>
private readonly BuildComponentFactoryCollection _componentFactories;
/// <summary>
/// Mapping of submission IDs to their first project started events.
/// </summary>
private readonly Dictionary<int, BuildEventArgs> _projectStartedEvents;
/// <summary>
/// Whether a cache has been provided by a project instance, meaning
/// we've acquired at least one build submission that included a project instance.
/// Once that has happened, we use the provided one, rather than our default.
/// </summary>
private bool _acquiredProjectRootElementCacheFromProjectInstance;
/// <summary>
/// The project started event handler
/// </summary>
private readonly ProjectStartedEventHandler _projectStartedEventHandler;
/// <summary>
/// The project finished event handler
/// </summary>
private readonly ProjectFinishedEventHandler _projectFinishedEventHandler;
/// <summary>
/// The logging exception event handler
/// </summary>
private readonly LoggingExceptionDelegate _loggingThreadExceptionEventHandler;
/// <summary>
/// Legacy threading semantic data associated with this build manager.
/// </summary>
private readonly LegacyThreadingData _legacyThreadingData;
/// <summary>
/// The worker queue.
/// </summary>
private ActionBlock<Action> _workQueue;
/// <summary>
/// Flag indicating we have disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// When the BuildManager was created.
/// </summary>
private DateTime _instantiationTimeUtc;
/// <summary>
/// Messages to be logged
/// </summary>
private IEnumerable<DeferredBuildMessage> _deferredBuildMessages;
/// <summary>
/// Build telemetry to be send when this build ends.
/// <remarks>Could be null</remarks>
/// </summary>
private BuildTelemetry _buildTelemetry;
private ProjectCacheService _projectCacheService;
private bool _hasProjectCacheServiceInitializedVsScenario;
#if DEBUG
/// <summary>
/// <code>true</code> to wait for a debugger to be attached, otherwise <code>false</code>.
/// </summary>
[SuppressMessage("ApiDesign",
"RS0016:Add public types and members to the declared API",
Justification = "Only available in the Debug configuration.")]
public static bool WaitForDebugger { get; set; }
#endif
/// <summary>
/// Creates a new unnamed build manager.
/// Normally there is only one build manager in a process, and it is the default build manager.
/// Access it with <see cref="BuildManager.DefaultBuildManager"/>
/// </summary>
public BuildManager()
: this("Unnamed")
{
}
/// <summary>
/// Creates a new build manager with an arbitrary distinct name.
/// Normally there is only one build manager in a process, and it is the default build manager.
/// Access it with <see cref="BuildManager.DefaultBuildManager"/>
/// </summary>
public BuildManager(string hostName)
{
ErrorUtilities.VerifyThrowArgumentNull(hostName, nameof(hostName));
_hostName = hostName;
_buildManagerState = BuildManagerState.Idle;
_buildSubmissions = new Dictionary<int, BuildSubmission>();
_graphBuildSubmissions = new Dictionary<int, GraphBuildSubmission>();
_noActiveSubmissionsEvent = new AutoResetEvent(true);
_activeNodes = new HashSet<NGen<int>>();
_noNodesActiveEvent = new AutoResetEvent(true);
_nodeIdToKnownConfigurations = new Dictionary<NGen<int>, HashSet<NGen<int>>>();
_unnamedProjectInstanceToNames = new Dictionary<ProjectInstance, string>();
_nextUnnamedProjectId = 1;
_componentFactories = new BuildComponentFactoryCollection(this);
_componentFactories.RegisterDefaultFactories();
SerializationContractInitializer.Initialize();
_projectStartedEvents = new Dictionary<int, BuildEventArgs>();
_projectStartedEventHandler = OnProjectStarted;
_projectFinishedEventHandler = OnProjectFinished;
_loggingThreadExceptionEventHandler = OnLoggingThreadException;
_legacyThreadingData = new LegacyThreadingData();
_instantiationTimeUtc = DateTime.UtcNow;
}
/// <summary>
/// Finalizes an instance of the <see cref="BuildManager"/> class.
/// </summary>
~BuildManager()
{
Dispose(false /* disposing */);
}
/// <summary>
/// Enumeration describing the current state of the build manager.
/// </summary>
private enum BuildManagerState
{
/// <summary>
/// This is the default state. <see cref="BeginBuild(BuildParameters)"/> may be called in this state. All other methods raise InvalidOperationException
/// </summary>
Idle,
/// <summary>
/// This is the state the BuildManager is in after <see cref="BeginBuild(BuildParameters)"/> has been called but before <see cref="EndBuild()"/> has been called.
/// <see cref="BuildManager.PendBuildRequest(Microsoft.Build.Execution.BuildRequestData)"/>, <see cref="BuildManager.BuildRequest(Microsoft.Build.Execution.BuildRequestData)"/>, <see cref="BuildManager.PendBuildRequest(GraphBuildRequestData)"/>, <see cref="BuildManager.BuildRequest(GraphBuildRequestData)"/>, and <see cref="BuildManager.EndBuild()"/> may be called in this state.
/// </summary>
Building,
/// <summary>
/// This is the state the BuildManager is in after <see cref="BuildManager.EndBuild()"/> has been called but before all existing submissions have completed.
/// </summary>
WaitingForBuildToComplete
}
/// <summary>
/// Gets the singleton instance of the Build Manager.
/// </summary>
public static BuildManager DefaultBuildManager
{
get
{
if (s_singletonInstance == null)
{
lock (s_staticSyncLock)
{
if (s_singletonInstance == null)
{
s_singletonInstance = new BuildManager("Default");
}
}
}
return s_singletonInstance;
}
}
/// <summary>
/// Retrieves a hosted<see cref="ISdkResolverService"/> instance for resolving SDKs.
/// </summary>
private ISdkResolverService SdkResolverService => (this as IBuildComponentHost).GetComponent(BuildComponentType.SdkResolverService) as ISdkResolverService;
/// <summary>
/// Retrieves the logging service associated with a particular build
/// </summary>
/// <returns>The logging service.</returns>
ILoggingService IBuildComponentHost.LoggingService => _componentFactories.GetComponent(BuildComponentType.LoggingService) as ILoggingService;
/// <summary>
/// Retrieves the name of the component host.
/// </summary>
string IBuildComponentHost.Name => _hostName;
/// <summary>
/// Retrieves the build parameters associated with this build.
/// </summary>
/// <returns>The build parameters.</returns>
BuildParameters IBuildComponentHost.BuildParameters => _buildParameters;
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular build manager
/// </summary>
LegacyThreadingData IBuildComponentHost.LegacyThreadingData => _legacyThreadingData;
/// <summary>
/// <see cref="BuildManager.BeginBuild(BuildParameters,IEnumerable{DeferredBuildMessage})"/>
/// </summary>
public readonly struct DeferredBuildMessage
{
public MessageImportance Importance { get; }
public string Text { get; }
public string FilePath { get; }
public DeferredBuildMessage(string text, MessageImportance importance)
{
Importance = importance;
Text = text;
FilePath = null;
}
public DeferredBuildMessage(string text, MessageImportance importance, string filePath)
{
Importance = importance;
Text = text;
FilePath = filePath;
}
}
/// <summary>
/// Prepares the BuildManager to receive build requests.
/// </summary>
/// <param name="parameters">The build parameters. May be null.</param>
/// <param name="deferredBuildMessages"> Build messages to be logged before the build begins. </param>
/// <exception cref="InvalidOperationException">Thrown if a build is already in progress.</exception>
public void BeginBuild(BuildParameters parameters, IEnumerable<DeferredBuildMessage> deferredBuildMessages)
{
// TEMP can be modified from the environment. Most of Traits is lasts for the duration of the process (with a manual reset for tests)
// and environment variables we use as properties are stored in a dictionary at the beginning of the build, so they also cannot be
// changed during a build. Some of our older stuff uses live environment variable checks. The TEMP directory previously used a live
// environment variable check, but it now uses a cached value. Nevertheless, we should support changing it between builds, so reset
// it here in case the user is using Visual Studio or the MSBuild server, as those each last for multiple builds without changing
// BuildManager.
FileUtilities.ClearTempFileDirectory();
// deferredBuildMessages cannot be an optional parameter on a single BeginBuild method because it would break binary compatibility.
_deferredBuildMessages = deferredBuildMessages;
BeginBuild(parameters);
_deferredBuildMessages = null;
}
private void UpdatePriority(Process p, ProcessPriorityClass priority)
{
try
{
p.PriorityClass = priority;
}
catch (Win32Exception) { }
}
/// <summary>
/// Prepares the BuildManager to receive build requests.
/// </summary>
/// <param name="parameters">The build parameters. May be null.</param>
/// <exception cref="InvalidOperationException">Thrown if a build is already in progress.</exception>
public void BeginBuild(BuildParameters parameters)
{
if (_previousLowPriority != null)
{
if (parameters.LowPriority != _previousLowPriority)
{
if (NativeMethodsShared.IsWindows || parameters.LowPriority)
{
ProcessPriorityClass priority = parameters.LowPriority ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Normal;
IEnumerable<Process> processes = _nodeManager?.GetProcesses();
if (processes is not null)
{
foreach (Process p in processes)
{
UpdatePriority(p, priority);
}
}
processes = _taskHostNodeManager?.GetProcesses();
if (processes is not null)
{
foreach (Process p in processes)
{
UpdatePriority(p, priority);
}
}
}
else
{
_nodeManager?.ShutdownAllNodes();
_taskHostNodeManager?.ShutdownAllNodes();
}
}
}
_previousLowPriority = parameters.LowPriority;
if (Traits.Instance.DebugEngine)
{
parameters.DetailedSummary = true;
parameters.LogTaskInputs = true;
}
lock (_syncLock)
{
AttachDebugger();
// Check for build in progress.
RequireState(BuildManagerState.Idle, "BuildInProgress");
MSBuildEventSource.Log.BuildStart();
// Initiate build telemetry data
DateTime now = DateTime.UtcNow;
// Acquire it from static variable so we can apply data collected up to this moment
_buildTelemetry = KnownTelemetry.PartialBuildTelemetry;
if (_buildTelemetry != null)
{
KnownTelemetry.PartialBuildTelemetry = null;
}
else
{
_buildTelemetry = new()
{
StartAt = now,
};
}
_buildTelemetry.InnerStartAt = now;
if (BuildParameters.DumpOpportunisticInternStats)
{
Strings.EnableDiagnostics();
}
_executionCancellationTokenSource = new CancellationTokenSource();
_overallBuildSuccess = true;
// Clone off the build parameters.
_buildParameters = parameters?.Clone() ?? new BuildParameters();
// Initialize additional build parameters.
_buildParameters.BuildId = GetNextBuildId();
if (_buildParameters.UsesCachedResults() && parameters.ProjectIsolationMode == ProjectIsolationMode.False)
{
// If input or output caches are used and the project isolation mode is set to
// ProjectIsolationMode.False, then set it to ProjectIsolationMode.True. The explicit
// condition on ProjectIsolationMode is necessary to ensure that, if we're using input
// or output caches and ProjectIsolationMode is set to ProjectIsolationMode.MessageUponIsolationViolation,
// ProjectIsolationMode isn't changed to ProjectIsolationMode.True.
_buildParameters.ProjectIsolationMode = ProjectIsolationMode.True;
}
if (_buildParameters.UsesOutputCache() && string.IsNullOrWhiteSpace(_buildParameters.OutputResultsCacheFile))
{
_buildParameters.OutputResultsCacheFile = FileUtilities.NormalizePath("msbuild-cache");
}
#if FEATURE_REPORTFILEACCESSES
if (_buildParameters.ReportFileAccesses)
{
EnableDetouredNodeLauncher();
}
#endif
// Initialize components.
_nodeManager = ((IBuildComponentHost)this).GetComponent(BuildComponentType.NodeManager) as INodeManager;
var loggingService = InitializeLoggingService();
// Log deferred messages and response files
LogDeferredMessages(loggingService, _deferredBuildMessages);
// Log known deferred telemetry
KnownTelemetry.LoggingConfigurationTelemetry.UpdateEventProperties();
loggingService.LogTelemetry(buildEventContext: null, KnownTelemetry.LoggingConfigurationTelemetry.EventName, KnownTelemetry.LoggingConfigurationTelemetry.Properties);
InitializeCaches();
#if FEATURE_REPORTFILEACCESSES
var fileAccessManager = ((IBuildComponentHost)this).GetComponent(BuildComponentType.FileAccessManager) as IFileAccessManager;
#endif
_projectCacheService = new ProjectCacheService(
this,
loggingService,
#if FEATURE_REPORTFILEACCESSES
fileAccessManager,
#endif
_configCache,
_buildParameters.ProjectCacheDescriptor);
_taskHostNodeManager = ((IBuildComponentHost)this).GetComponent(BuildComponentType.TaskHostNodeManager) as INodeManager;
_scheduler = ((IBuildComponentHost)this).GetComponent(BuildComponentType.Scheduler) as IScheduler;
_nodeManager.RegisterPacketHandler(NodePacketType.BuildRequestBlocker, BuildRequestBlocker.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.BuildRequestConfiguration, BuildRequestConfiguration.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.BuildRequestConfigurationResponse, BuildRequestConfigurationResponse.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.BuildResult, BuildResult.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.FileAccessReport, FileAccessReport.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.NodeShutdown, NodeShutdown.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.ProcessReport, ProcessReport.FactoryForDeserialization, this);
_nodeManager.RegisterPacketHandler(NodePacketType.ResolveSdkRequest, SdkResolverRequest.FactoryForDeserialization, SdkResolverService as INodePacketHandler);
_nodeManager.RegisterPacketHandler(NodePacketType.ResourceRequest, ResourceRequest.FactoryForDeserialization, this);
if (_threadException != null)
{
ShutdownLoggingService(loggingService);
_threadException.Throw();
}
if (_workQueue == null)
{
_workQueue = new ActionBlock<Action>(action => ProcessWorkQueue(action));
}
_buildManagerState = BuildManagerState.Building;
_noActiveSubmissionsEvent.Set();
_noNodesActiveEvent.Set();
}
ILoggingService InitializeLoggingService()
{
ILoggingService loggingService = CreateLoggingService(
AppendDebuggingLoggers(_buildParameters.Loggers),
_buildParameters.ForwardingLoggers,
_buildParameters.WarningsAsErrors,
_buildParameters.WarningsNotAsErrors,
_buildParameters.WarningsAsMessages);
_nodeManager.RegisterPacketHandler(NodePacketType.LogMessage, LogMessagePacket.FactoryForDeserialization, loggingService as INodePacketHandler);
try
{
loggingService.LogBuildStarted();
if (_buildParameters.UsesInputCaches())
{
loggingService.LogComment(BuildEventContext.Invalid, MessageImportance.Normal, "UsingInputCaches", string.Join(";", _buildParameters.InputResultsCacheFiles));
}
if (_buildParameters.UsesOutputCache())
{
loggingService.LogComment(BuildEventContext.Invalid, MessageImportance.Normal, "WritingToOutputCache", _buildParameters.OutputResultsCacheFile);
}
}
catch (Exception)
{
ShutdownLoggingService(loggingService);
throw;
}
return loggingService;
}
// VS builds discard many msbuild events so attach a binlogger to capture them all.
IEnumerable<ILogger> AppendDebuggingLoggers(IEnumerable<ILogger> loggers)
{
if (DebugUtils.ShouldDebugCurrentProcess is false ||
Traits.Instance.DebugEngine is false)
{
return loggers;
}
var binlogPath = DebugUtils.FindNextAvailableDebugFilePath($"{DebugUtils.ProcessInfoString}_BuildManager_{_hostName}.binlog");
var logger = new BinaryLogger { Parameters = binlogPath };
return (loggers ?? Enumerable.Empty<ILogger>()).Concat(new[] { logger });
}
void InitializeCaches()
{
Debug.Assert(Monitor.IsEntered(_syncLock));
var usesInputCaches = _buildParameters.UsesInputCaches();
if (usesInputCaches)
{
ReuseOldCaches(_buildParameters.InputResultsCacheFiles);
}
_configCache = ((IBuildComponentHost)this).GetComponent(BuildComponentType.ConfigCache) as IConfigCache;
_resultsCache = ((IBuildComponentHost)this).GetComponent(BuildComponentType.ResultsCache) as IResultsCache;
if (!usesInputCaches && (_buildParameters.ResetCaches || _configCache.IsConfigCacheSizeLargerThanThreshold()))
{
ResetCaches();
}
else
{
if (!usesInputCaches)
{
List<int> configurationsCleared = _configCache.ClearNonExplicitlyLoadedConfigurations();
if (configurationsCleared != null)
{
foreach (int configurationId in configurationsCleared)
{
_resultsCache.ClearResultsForConfiguration(configurationId);
}
}
}
foreach (var config in _configCache)
{
config.ResultsNodeId = Scheduler.InvalidNodeId;
}
_buildParameters.ProjectRootElementCache.DiscardImplicitReferences();
}
}
}
#if FEATURE_REPORTFILEACCESSES
/// <summary>
/// Configure the build to use I/O tracking for nodes.
/// </summary>
/// <remarks>
/// Must be a separate non-inlinable method to avoid loading the BuildXL assembly when not opted in.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnableDetouredNodeLauncher()
{
// Currently BuildXL only supports x64. Once this feature moves out of the experimental phase, this will need to be addressed.
ErrorUtilities.VerifyThrowInvalidOperation(NativeMethodsShared.ProcessorArchitecture == NativeMethodsShared.ProcessorArchitectures.X64, "ReportFileAccessesX64Only");
// To properly report file access, we need to disable the in-proc node which won't be detoured.
_buildParameters.DisableInProcNode = true;
// Node reuse must be disabled as future builds will not be able to listen to events raised by detours.
_buildParameters.EnableNodeReuse = false;
_componentFactories.ReplaceFactory(BuildComponentType.NodeLauncher, DetouredNodeLauncher.CreateComponent);
}
#endif
private static void AttachDebugger()
{
if (Debugger.IsAttached)
{
return;
}
if (!DebugUtils.ShouldDebugCurrentProcess)
{
return;
}
switch (Environment.GetEnvironmentVariable("MSBuildDebugBuildManagerOnStart"))
{
#if FEATURE_DEBUG_LAUNCH
case "1":
Debugger.Launch();
break;
#endif
case "2":
// Sometimes easier to attach rather than deal with JIT prompt
Process currentProcess = Process.GetCurrentProcess();
Console.WriteLine($"Waiting for debugger to attach ({currentProcess.MainModule.FileName} PID {currentProcess.Id}). Press enter to continue...");
Console.ReadLine();
break;
}
}
/// <summary>
/// Cancels all outstanding submissions asynchronously.
/// </summary>
public void CancelAllSubmissions()
{
CancelAllSubmissions(true);
}
private void CancelAllSubmissions(bool async)
{
var parentThreadCulture = _buildParameters != null
? _buildParameters.Culture
: CultureInfo.CurrentCulture;
var parentThreadUICulture = _buildParameters != null
? _buildParameters.UICulture
: CultureInfo.CurrentUICulture;
void Callback(object state)
{
lock (_syncLock)
{
if (_shuttingDown)
{
return;
}
// If we are Idle, obviously there is nothing to cancel. If we are waiting for the build to end, then presumably all requests have already completed
// and there is nothing left to cancel. Putting this here eliminates the possibility of us racing with EndBuild to access the nodeManager before
// EndBuild sets it to null.
if (_buildManagerState != BuildManagerState.Building)
{
return;
}
_overallBuildSuccess = false;
foreach (BuildSubmission submission in _buildSubmissions.Values)
{
if (submission.BuildRequest != null)
{
BuildResult result = new BuildResult(submission.BuildRequest, new BuildAbortedException());
_resultsCache.AddResult(result);
submission.CompleteResults(result);
}
}
foreach (GraphBuildSubmission submission in _graphBuildSubmissions.Values)
{
if (submission.IsStarted)
{
submission.CompleteResults(new GraphBuildResult(submission.SubmissionId, new BuildAbortedException()));
}
}
ShutdownConnectedNodes(true /* abort */);
CheckForActiveNodesAndCleanUpSubmissions();
}
}
ThreadPoolExtensions.QueueThreadPoolWorkItemWithCulture(Callback, parentThreadCulture, parentThreadUICulture);
}
/// <summary>
/// Clears out all of the cached information.
/// </summary>
public void ResetCaches()
{
lock (_syncLock)
{
ErrorIfState(BuildManagerState.WaitingForBuildToComplete, "WaitingForEndOfBuild");
ErrorIfState(BuildManagerState.Building, "BuildInProgress");
_configCache = ((IBuildComponentHost)this).GetComponent(BuildComponentType.ConfigCache) as IConfigCache;
_resultsCache = ((IBuildComponentHost)this).GetComponent(BuildComponentType.ResultsCache) as IResultsCache;
_resultsCache.ClearResults();
// This call clears out the directory.
_configCache.ClearConfigurations();
_buildParameters?.ProjectRootElementCache.DiscardImplicitReferences();
}
}
/// <summary>
/// This methods requests the BuildManager to find a matching ProjectInstance in its cache of previously-built projects.
/// If none exist, a new instance will be created from the specified project.
/// </summary>
/// <param name="project">The Project for which an instance should be retrieved.</param>
/// <returns>The instance.</returns>
public ProjectInstance GetProjectInstanceForBuild(Project project)
{
lock (_syncLock)
{
_configCache = ((IBuildComponentHost)this).GetComponent(BuildComponentType.ConfigCache) as IConfigCache;
BuildRequestConfiguration configuration = _configCache.GetMatchingConfiguration(
new ConfigurationMetadata(project),
(config, loadProject) => CreateConfiguration(project, config),
loadProject: true);
ErrorUtilities.VerifyThrow(configuration.Project != null, "Configuration should have been loaded.");
return configuration.Project;
}
}
/// <summary>
/// Submits a build request to the current build but does not start it immediately. Allows the user to
/// perform asynchronous execution or access the submission ID prior to executing the request.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if StartBuild has not been called or if EndBuild has been called.</exception>
public BuildSubmission PendBuildRequest(BuildRequestData requestData)
{
lock (_syncLock)
{
ErrorUtilities.VerifyThrowArgumentNull(requestData, nameof(requestData));
ErrorIfState(BuildManagerState.WaitingForBuildToComplete, "WaitingForEndOfBuild");
ErrorIfState(BuildManagerState.Idle, "NoBuildInProgress");
VerifyStateInternal(BuildManagerState.Building);
var newSubmission = new BuildSubmission(this, GetNextSubmissionId(), requestData, _buildParameters.LegacyThreadingSemantics);
if (_buildTelemetry != null)
{
_buildTelemetry.Project ??= requestData.ProjectFullPath;
_buildTelemetry.Target ??= string.Join(",", requestData.TargetNames);
}
_buildSubmissions.Add(newSubmission.SubmissionId, newSubmission);
_noActiveSubmissionsEvent.Reset();
return newSubmission;
}
}
/// <summary>
/// Submits a graph build request to the current build but does not start it immediately. Allows the user to
/// perform asynchronous execution or access the submission ID prior to executing the request.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if StartBuild has not been called or if EndBuild has been called.</exception>
public GraphBuildSubmission PendBuildRequest(GraphBuildRequestData requestData)
{
lock (_syncLock)
{
ErrorUtilities.VerifyThrowArgumentNull(requestData, nameof(requestData));
ErrorIfState(BuildManagerState.WaitingForBuildToComplete, "WaitingForEndOfBuild");
ErrorIfState(BuildManagerState.Idle, "NoBuildInProgress");
VerifyStateInternal(BuildManagerState.Building);
var newSubmission = new GraphBuildSubmission(this, GetNextSubmissionId(), requestData);
if (_buildTelemetry != null)
{
// Project graph can have multiple entry points, for purposes of identifying event for same build project,
// we believe that including only one entry point will provide enough precision.
_buildTelemetry.Project ??= requestData.ProjectGraphEntryPoints?.FirstOrDefault().ProjectFile;
_buildTelemetry.Target ??= string.Join(",", requestData.TargetNames);
}
_graphBuildSubmissions.Add(newSubmission.SubmissionId, newSubmission);
_noActiveSubmissionsEvent.Reset();
return newSubmission;
}
}
/// <summary>
/// Convenience method. Submits a build request and blocks until the results are available.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if StartBuild has not been called or if EndBuild has been called.</exception>
public BuildResult BuildRequest(BuildRequestData requestData)
{
BuildSubmission submission = PendBuildRequest(requestData);
BuildResult result = submission.Execute();
return result;
}
/// <summary>
/// Convenience method. Submits a graph build request and blocks until the results are available.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if StartBuild has not been called or if EndBuild has been called.</exception>
public GraphBuildResult BuildRequest(GraphBuildRequestData requestData) => PendBuildRequest(requestData).Execute();
/// <summary>
/// Signals that no more build requests are expected (or allowed) and the BuildManager may clean up.
/// </summary>
/// <remarks>
/// This call blocks until all currently pending requests are complete.
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if there is no build in progress.</exception>
public void EndBuild()
{
lock (_syncLock)
{
ErrorIfState(BuildManagerState.WaitingForBuildToComplete, "WaitingForEndOfBuild");
ErrorIfState(BuildManagerState.Idle, "NoBuildInProgress");
VerifyStateInternal(BuildManagerState.Building);
_buildManagerState = BuildManagerState.WaitingForBuildToComplete;
}
var exceptionsThrownInEndBuild = false;
try
{
lock (_syncLock)
{
// If there are any submissions which never started, remove them now.
var submissionsToCheck = new List<BuildSubmission>(_buildSubmissions.Values);
foreach (BuildSubmission submission in submissionsToCheck)
{
CheckSubmissionCompletenessAndRemove(submission);
}
var graphSubmissionsToCheck = new List<GraphBuildSubmission>(_graphBuildSubmissions.Values);
foreach (GraphBuildSubmission submission in graphSubmissionsToCheck)
{
CheckSubmissionCompletenessAndRemove(submission);
}
}
_noActiveSubmissionsEvent.WaitOne();
ShutdownConnectedNodes(false /* normal termination */);
_noNodesActiveEvent.WaitOne();
// Wait for all of the actions in the work queue to drain.
// _workQueue.Completion.Wait() could throw here if there was an unhandled exception in the work queue,
// but the top level exception handler there should catch everything and have forwarded it to the
// OnThreadException method in this class already.
_workQueue.Complete();
_workQueue.Completion.Wait();
Task projectCacheDispose = _projectCacheService.DisposeAsync().AsTask();