-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathOutOfProcTaskHostNode.cs
More file actions
2116 lines (1831 loc) · 91.9 KB
/
Copy pathOutOfProcTaskHostNode.cs
File metadata and controls
2116 lines (1831 loc) · 91.9 KB
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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Eventing;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Framework.Utilities;
using Microsoft.Build.Experimental.FileAccess;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
#if FEATURE_APPDOMAIN
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
#endif
#nullable disable
namespace Microsoft.Build.CommandLine
{
/// <summary>
/// This class represents an implementation of INode for out-of-proc node for hosting tasks.
/// </summary>
internal class OutOfProcTaskHostNode :
#if FEATURE_APPDOMAIN
MarshalByRefObject,
#endif
INodePacketFactory, INodePacketHandler, IBuildEngine10
{
/// <summary>
/// Keeps a record of all environment variables that, on startup of the task host, have a different
/// value from those that are passed to the task host in the configuration packet for the first task.
/// These environments are assumed to be effectively identical, so the only difference between the
/// two sets of values should be any environment variables that differ between e.g. a 32-bit and a 64-bit
/// process. Those are the variables that this dictionary should store.
///
/// - The key into the dictionary is the name of the environment variable.
/// - The Key of the KeyValuePair is the value of the variable in the owning worker node process -- the value that we
/// wish to ensure is replaced by whatever the correct value in our current process is.
/// - The Value of the KeyValuePair is the value of the variable in the current process -- the value that
/// we wish to replay the Key value with in the environment that we receive from the owning worker node before
/// applying it to the current process.
///
/// Note that either value in the KeyValuePair can be null, as it is completely possible to have an
/// environment variable that is set in 32-bit processes but not in 64-bit, or vice versa.
///
/// This dictionary must be static because otherwise, if a node is sitting around waiting for reuse, it will
/// have inherited the environment from the previous build, and any differences between the two will be seen
/// as "legitimate". There is no way for us to know what the differences between the startup environment of
/// the previous build and the environment of the first task run in the task host in this build -- so we
/// must assume that the 4ish system environment variables that this is really meant to catch haven't
/// somehow magically changed between two builds spaced no more than 15 minutes apart.
/// </summary>
private static IDictionary<string, KeyValuePair<string, string>> s_mismatchedEnvironmentValues;
/// <summary>
/// The endpoint used to talk to the host.
/// </summary>
private NodeEndpointOutOfProcTaskHost _nodeEndpoint;
/// <summary>
/// The packet factory.
/// </summary>
private NodePacketFactory _packetFactory;
/// <summary>
/// The event which is set when we receive packets.
/// </summary>
private AutoResetEvent _packetReceivedEvent;
/// <summary>
/// The queue of packets we have received but which have not yet been processed.
/// </summary>
private Queue<INodePacket> _receivedPackets;
/// <summary>
/// The current configuration for this task host.
/// </summary>
private TaskHostConfiguration _currentConfiguration;
/// <summary>
/// The saved environment for the process.
/// </summary>
private IDictionary<string, string> _savedEnvironment;
/// <summary>
/// The build process environment most recently received in full from the parent on this connection.
/// When a <see cref="TaskHostConfiguration"/> arrives marked <see cref="InvariantPayloadTransferMode.Identical"/>
/// it is reconstructed from this baseline.
/// </summary>
private Dictionary<string, string> _forwardEnvironmentBaseline;
/// <summary>
/// The global properties most recently received in full from the parent on this connection. When a
/// <see cref="TaskHostConfiguration"/> arrives marked <see cref="InvariantPayloadTransferMode.Identical"/> they
/// are reconstructed from this baseline.
/// </summary>
private Dictionary<string, string> _forwardGlobalParametersBaseline;
/// <summary>
/// The build process environment whose values are currently reflected in this task host process. Used to
/// skip the redundant per-task environment apply + restore when the next task's environment is identical
/// and the previous task did not mutate it. Set to <see langword="null"/> whenever a task blocks on a
/// callback (<see cref="SaveOperatingEnvironment"/>) or the node is reused for a new build, so nested
/// activity and build boundaries always force a fresh apply.
/// </summary>
private IDictionary<string, string> _lastAppliedConfigEnvironment;
/// <summary>
/// The event which is set when we should shut down.
/// </summary>
private ManualResetEvent _shutdownEvent;
/// <summary>
/// The reason we are shutting down.
/// </summary>
private NodeEngineShutdownReason _shutdownReason;
/// <summary>
/// Count of tasks that are actively executing (not blocked on a callback).
/// When a task blocks on BuildProjectFile, this decrements. When it resumes, this increments.
/// Used to determine if we can accept new TaskHostConfiguration packets.
/// </summary>
private int _activeTaskCount;
/// <summary>
/// Number of tasks currently blocked on a BuildProjectFile callback.
/// A blocked task does NOT prevent new tasks from being scheduled to this TaskHost.
/// </summary>
private int _blockedTaskCount;
/// <summary>
/// The event which is set when a task has completed.
/// </summary>
private AutoResetEvent _taskCompleteEvent;
/// <summary>
/// The completed task packet waiting to be sent by the main thread.
/// Distinct results must survive coalesced completion event signals.
/// </summary>
private readonly ConcurrentQueue<TaskHostTaskComplete> _taskCompletePackets = new();
/// <summary>
/// The event which is set when a task is cancelled
/// </summary>
private ManualResetEvent _taskCancelledEvent;
/// <summary>
/// Signalled when the current build cancelled a task. FOR UNIT TESTING ONLY: a cancellation
/// from one build must not still be signalled when the node is reset for the next.
/// </summary>
internal ManualResetEvent TaskCancelledEvent => _taskCancelledEvent;
/// <summary>
/// Flag indicating if we should debug communications or not.
/// </summary>
private bool _debugCommunications;
/// <summary>
/// Flag indicating whether we should modify the environment based on any differences we find between that of the
/// task host at startup and the environment passed to us in our initial task configuration packet.
/// </summary>
private bool _updateEnvironment;
/// <summary>
/// An interim step between MSBuildTaskHostDoNotUpdateEnvironment=1 and the default update behavior: go ahead and
/// do all the updates that we would otherwise have done by default, but log any updates that are made (at low
/// importance) so that the user is aware.
/// </summary>
private bool _updateEnvironmentAndLog;
/// <summary>
/// Whether this task host was launched with node reuse, so it does not exit at the end of a
/// build. Whether it then stays connected to its launcher as a sidecar, or disconnects into
/// the machine-wide pool, is what <see cref="NodeBuildComplete.PrepareForReuse"/> says.
/// </summary>
private bool _nodeReuse;
/// <summary>
/// The task object cache.
/// </summary>
private RegisteredTaskObjectCacheBase _registeredTaskObjectCache = new();
#if FEATURE_REPORTFILEACCESSES
/// <summary>
/// The file accesses reported by the most recently completed task.
/// </summary>
private List<FileAccessData> _fileAccessData = new List<FileAccessData>();
#endif
/// <summary>
/// Counter for generating unique request IDs for callback correlation.
/// </summary>
private int _nextCallbackRequestId;
/// <summary>
/// Pending callback requests awaiting responses from the owning worker node.
/// Key is the request ID, value is the TaskCompletionSource to signal when response arrives.
/// </summary>
private readonly ConcurrentDictionary<int, TaskCompletionSource<INodePacket>> _pendingCallbackRequests = new();
/// <summary>
/// All active task execution contexts, keyed by task ID.
/// Supports nested task execution when tasks block on BuildProjectFile callbacks.
/// </summary>
private readonly ConcurrentDictionary<int, TaskExecutionContext> _taskContexts
= new ConcurrentDictionary<int, TaskExecutionContext>();
/// <summary>
/// The task context for the calling thread. Each task runs on its own thread
/// (spawned in HandleTaskHostConfiguration). When Task A blocks on BuildProjectFile,
/// Task B starts on a new thread. AsyncLocal ensures each thread sees its own context
/// for logging, pending callbacks, and environment state.
/// </summary>
private readonly AsyncLocal<TaskExecutionContext> _currentTaskContext
= new AsyncLocal<TaskExecutionContext>();
#if FEATURE_APPDOMAIN
private const string TaskContextIdSlot = "MSBuild.TaskHost.TaskContextId";
#endif
/// <summary>
/// Counter for generating task IDs when configuration doesn't provide one.
/// </summary>
private int _nextLocalTaskId;
/// <summary>
/// The packet version negotiated with the owning worker node.
/// Used to determine if the worker node supports callback packets.
/// </summary>
private byte _parentPacketVersion;
/// <summary>
/// Minimum packet version required for IBuildEngine callback support.
/// </summary>
private const byte CallbacksMinPacketVersion = 4;
/// <summary>
/// Whether the owning worker node supports IBuildEngine callbacks.
/// True if the worker node's packet version is high enough.
/// </summary>
private bool CallbacksSupported => _parentPacketVersion >= CallbacksMinPacketVersion;
private RedirectConsoleWriter _consoleOutWriter;
private RedirectConsoleWriter _consoleErrorWriter;
private TextWriter _originalConsoleOut;
private TextWriter _originalConsoleError;
/// <summary>
/// Gets the effective configuration for the current task thread.
/// Uses the per-task context first, falling back to <see cref="_currentConfiguration"/>.
/// </summary>
private TaskHostConfiguration EffectiveConfiguration => GetCurrentConfiguration();
/// <summary>
/// Constructor.
/// </summary>
public OutOfProcTaskHostNode()
{
// We don't know what the current build thinks this variable should be until RunTask(), but as a fallback in case there are
// communications before we get the configuration set up, just go with what was already in the environment from when this node
// was initially launched.
_debugCommunications = Traits.Instance.DebugNodeCommunication;
_receivedPackets = new Queue<INodePacket>();
// These WaitHandles are disposed in HandleShutDown()
_packetReceivedEvent = new AutoResetEvent(false);
_shutdownEvent = new ManualResetEvent(false);
_taskCompleteEvent = new AutoResetEvent(false);
_taskCancelledEvent = new ManualResetEvent(false);
_packetFactory = new NodePacketFactory();
INodePacketFactory thisINodePacketFactory = (INodePacketFactory)this;
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.TaskHostConfiguration, TaskHostConfiguration.FactoryForDeserialization, this);
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.TaskHostTaskCancelled, TaskHostTaskCancelled.FactoryForDeserialization, this);
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.NodeBuildComplete, NodeBuildComplete.FactoryForDeserialization, this);
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.TaskHostIsRunningMultipleNodesResponse, TaskHostIsRunningMultipleNodesResponse.FactoryForDeserialization, this);
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.TaskHostCoresResponse, TaskHostCoresResponse.FactoryForDeserialization, this);
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.TaskHostBuildResponse, TaskHostBuildResponse.FactoryForDeserialization, this);
thisINodePacketFactory.RegisterPacketHandler(NodePacketType.TaskHostConsoleConfiguration, TaskHostConsoleConfiguration.FactoryForDeserialization, this);
EngineServices = new EngineServicesImpl(this);
}
#region IBuildEngine Implementation (Properties)
/// <summary>
/// Returns the value of ContinueOnError for the currently executing task.
/// </summary>
public bool ContinueOnError
{
get
{
Assumed.NotNull(EffectiveConfiguration, "We should never have a null configuration during a BuildEngine callback!");
return EffectiveConfiguration.ContinueOnError;
}
}
/// <summary>
/// Returns the line number of the location in the project file of the currently executing task.
/// </summary>
public int LineNumberOfTaskNode
{
get
{
Assumed.NotNull(EffectiveConfiguration, "We should never have a null configuration during a BuildEngine callback!");
return EffectiveConfiguration.LineNumberOfTask;
}
}
/// <summary>
/// Returns the column number of the location in the project file of the currently executing task.
/// </summary>
public int ColumnNumberOfTaskNode
{
get
{
Assumed.NotNull(EffectiveConfiguration, "We should never have a null configuration during a BuildEngine callback!");
return EffectiveConfiguration.ColumnNumberOfTask;
}
}
/// <summary>
/// Returns the project file of the currently executing task.
/// </summary>
public string ProjectFileOfTaskNode
{
get
{
Assumed.NotNull(EffectiveConfiguration, "We should never have a null configuration during a BuildEngine callback!");
return EffectiveConfiguration.ProjectFileOfTask;
}
}
#endregion // IBuildEngine Implementation (Properties)
#region IBuildEngine2 Implementation (Properties)
/// <summary>
/// Implementation of IBuildEngine2.IsRunningMultipleNodes.
/// Queries the owning worker node and returns the actual value.
/// Returns false if the worker node doesn't support callbacks (cross-version scenario).
/// </summary>
public bool IsRunningMultipleNodes
{
get
{
if (!CallbacksSupported)
{
LogErrorFromResource("BuildEngineCallbacksInTaskHostUnsupported");
return false;
}
var request = new TaskHostIsRunningMultipleNodesRequest();
var response = SendCallbackRequestAndWaitForResponse<TaskHostIsRunningMultipleNodesResponse>(request);
return response.IsRunningMultipleNodes;
}
}
#endregion // IBuildEngine2 Implementation (Properties)
#region IBuildEngine7 Implementation
/// <summary>
/// Enables or disables emitting a default error when a task fails without logging errors
/// </summary>
public bool AllowFailureWithoutError
{
get
{
TaskExecutionContext context = GetCurrentTaskContext();
Assumed.NotNull(context);
return context.AllowFailureWithoutError;
}
set
{
TaskExecutionContext context = GetCurrentTaskContext();
Assumed.NotNull(context);
context.AllowFailureWithoutError = value;
}
}
#endregion
#region IBuildEngine8 Implementation
/// <summary>
/// Contains all warnings that should be logged as errors.
/// Non-null empty set when all warnings should be treated as errors.
/// Fallback for code paths without a TaskExecutionContext (e.g., main thread).
/// Task threads use EffectiveWarningsAs* which reads per-task context first.
/// </summary>
private ICollection<string> _warningsAsErrors;
/// <summary>Fallback for WarningsNotAsErrors. See <see cref="_warningsAsErrors"/>.</summary>
private ICollection<string> _warningsNotAsErrors;
/// <summary>Fallback for WarningsAsMessages. See <see cref="_warningsAsErrors"/>.</summary>
private ICollection<string> _warningsAsMessages;
/// <summary>
/// Gets the effective WarningsAsErrors for the current task context.
/// Uses per-task saved values when available (during concurrent execution),
/// falling back to the shared field.
/// </summary>
private ICollection<string> EffectiveWarningsAsErrors
{
get
{
var context = GetCurrentTaskContext();
return context?.WarningsAsErrors ?? _warningsAsErrors;
}
}
private ICollection<string> EffectiveWarningsNotAsErrors
{
get
{
var context = GetCurrentTaskContext();
return context?.WarningsNotAsErrors ?? _warningsNotAsErrors;
}
}
private ICollection<string> EffectiveWarningsAsMessages
{
get
{
var context = GetCurrentTaskContext();
return context?.WarningsAsMessages ?? _warningsAsMessages;
}
}
public bool ShouldTreatWarningAsError(string warningCode)
{
var warningsAsErrors = EffectiveWarningsAsErrors;
var warningsAsMessages = EffectiveWarningsAsMessages;
// Warnings as messages overrides warnings as errors.
if (warningsAsErrors is null || warningsAsMessages?.Contains(warningCode) == true)
{
return false;
}
if (ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave18_6))
{
// An empty set means all warnings are errors.
return (warningsAsErrors.Count == 0 && WarningAsErrorNotOverriden(warningCode)) || warningsAsErrors.Contains(warningCode);
}
// Pre-18.6 behavior preserved for backward compatibility: incorrectly checks WarningsAsMessages instead of WarningsAsErrors.
return (warningsAsErrors.Count == 0 && WarningAsErrorNotOverriden(warningCode)) || warningsAsMessages.Contains(warningCode);
}
private bool WarningAsErrorNotOverriden(string warningCode)
{
return EffectiveWarningsNotAsErrors?.Contains(warningCode) != true;
}
#endregion
#region IBuildEngine Implementation (Methods)
/// <summary>
/// Sends the provided error back to the owning worker node to be logged, tagging it with
/// the worker node's ID so that, as far as anyone is concerned, it might as well have
/// just come from the worker node to begin with.
/// </summary>
public void LogErrorEvent(BuildErrorEventArgs e)
{
SendBuildEvent(e);
}
/// <summary>
/// Sends the provided warning back to the owning worker node to be logged, tagging it with
/// the worker node's ID so that, as far as anyone is concerned, it might as well have
/// just come from the worker node to begin with.
/// </summary>
public void LogWarningEvent(BuildWarningEventArgs e)
{
SendBuildEvent(e);
}
/// <summary>
/// Sends the provided message back to the owning worker node to be logged, tagging it with
/// the worker node's ID so that, as far as anyone is concerned, it might as well have
/// just come from the worker node to begin with.
/// </summary>
public void LogMessageEvent(BuildMessageEventArgs e)
{
SendBuildEvent(e);
}
/// <summary>
/// Sends the provided custom event back to the owning worker node to be logged, tagging it with
/// the worker node's ID so that, as far as anyone is concerned, it might as well have
/// just come from the worker node to begin with.
/// </summary>
public void LogCustomEvent(CustomBuildEventArgs e)
{
SendBuildEvent(e);
}
/// <summary>
/// Implementation of IBuildEngine.BuildProjectFile. Delegates to the 5-param overload.
/// </summary>
public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs)
{
if (!CallbacksSupported)
{
LogErrorFromResource("BuildEngineCallbacksInTaskHostUnsupported");
return false;
}
return BuildProjectFile(projectFileName, targetNames, globalProperties, targetOutputs, null);
}
#endregion // IBuildEngine Implementation (Methods)
#region IBuildEngine2 Implementation (Methods)
/// <summary>
/// Implementation of IBuildEngine2.BuildProjectFile. Delegates to the 7-param BuildProjectFilesInParallel.
/// </summary>
public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion)
{
if (!CallbacksSupported)
{
LogErrorFromResource("BuildEngineCallbacksInTaskHostUnsupported");
return false;
}
return BuildProjectFilesInParallel(
[projectFileName],
targetNames,
[globalProperties],
[targetOutputs],
[toolsVersion],
true,
false);
}
/// <summary>
/// Implementation of IBuildEngine2.BuildProjectFilesInParallel. Delegates to the 6-param IBuildEngine3 overload.
/// </summary>
public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion)
{
if (!CallbacksSupported)
{
LogErrorFromResource("BuildEngineCallbacksInTaskHostUnsupported");
return false;
}
if (projectFileNames is null)
{
return false;
}
Assumed.True(targetOutputsPerProject is null || projectFileNames.Length == targetOutputsPerProject.Length, $"projectFileNames has {projectFileNames.Length} entries but targetOutputsPerProject has {targetOutputsPerProject?.Length ?? 0} -- lengths must match.");
bool includeTargetOutputs = targetOutputsPerProject is not null;
BuildEngineResult result = BuildProjectFilesInParallel(projectFileNames, targetNames, globalProperties, new List<string>[projectFileNames.Length], toolsVersion, includeTargetOutputs);
if (includeTargetOutputs && result.TargetOutputsPerProject is not null)
{
for (int i = 0; i < targetOutputsPerProject.Length && i < result.TargetOutputsPerProject.Count; i++)
{
if (targetOutputsPerProject[i] is not null)
{
foreach (KeyValuePair<string, ITaskItem[]> output in result.TargetOutputsPerProject[i])
{
targetOutputsPerProject[i].Add(output.Key, output.Value);
}
}
}
}
return result.Result;
}
#endregion // IBuildEngine2 Implementation (Methods)
#region IBuildEngine3 Implementation
/// <summary>
/// Implementation of IBuildEngine3.BuildProjectFilesInParallel. This is the canonical form that
/// sends the request to the owning worker node and waits for the response.
/// </summary>
public BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs)
{
if (!CallbacksSupported)
{
LogErrorFromResource("BuildEngineCallbacksInTaskHostUnsupported");
return new BuildEngineResult(false, null);
}
string projectFilesJoined = null;
if (MSBuildEventSource.Log.IsEnabled())
{
projectFilesJoined = string.Join(";", projectFileNames ?? []);
string targetNamesJoined = string.Join(";", targetNames ?? []);
MSBuildEventSource.Log.TaskHostBuildProjectFileStart(projectFilesJoined, targetNamesJoined);
}
var request = new TaskHostBuildRequest(
projectFileNames,
targetNames,
TaskHostBuildRequest.ConvertGlobalProperties(globalProperties),
TaskHostBuildRequest.ConvertRemoveGlobalProperties(removeGlobalProperties),
toolsVersion,
returnTargetOutputs);
// Block while the callback is processed so the node can accept nested tasks.
BlockForCallback();
bool success = false;
try
{
var response = SendCallbackRequestAndWaitForResponse<TaskHostBuildResponse>(request);
var result = response.ToBuildEngineResult();
success = result.Result;
return result;
}
finally
{
if (MSBuildEventSource.Log.IsEnabled())
{
MSBuildEventSource.Log.TaskHostBuildProjectFileStop(projectFilesJoined!, success);
}
ResumeAfterCallback();
}
}
/// <summary>
/// No-op. Explicit yield is not supported in the OOP TaskHost.
/// Nested task dispatch uses BuildProjectFile callback blocking instead.
/// </summary>
public void Yield()
{
}
/// <summary>
/// No-op. See <see cref="Yield"/>.
/// </summary>
public void Reacquire()
{
}
#endregion // IBuildEngine3 Implementation
#region IBuildEngine4 Implementation
/// <summary>
/// Registers an object with the system that will be disposed of at some specified time
/// in the future.
/// </summary>
/// <param name="key">The key used to retrieve the object.</param>
/// <param name="obj">The object to be held for later disposal.</param>
/// <param name="lifetime">The lifetime of the object.</param>
/// <param name="allowEarlyCollection">The object may be disposed earlier that the requested time if
/// MSBuild needs to reclaim memory.</param>
public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
{
_registeredTaskObjectCache.RegisterTaskObject(key, obj, lifetime, allowEarlyCollection);
}
/// <summary>
/// Retrieves a previously registered task object stored with the specified key.
/// </summary>
/// <param name="key">The key used to retrieve the object.</param>
/// <param name="lifetime">The lifetime of the object.</param>
/// <returns>
/// The registered object, or null is there is no object registered under that key or the object
/// has been discarded through early collection.
/// </returns>
public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime)
{
return _registeredTaskObjectCache.GetRegisteredTaskObject(key, lifetime);
}
/// <summary>
/// Unregisters a previously-registered task object.
/// </summary>
/// <param name="key">The key used to retrieve the object.</param>
/// <param name="lifetime">The lifetime of the object.</param>
/// <returns>
/// The registered object, or null is there is no object registered under that key or the object
/// has been discarded through early collection.
/// </returns>
public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime)
{
return _registeredTaskObjectCache.UnregisterTaskObject(key, lifetime);
}
#endregion
#region IBuildEngine5 Implementation
/// <summary>
/// Logs a telemetry event.
/// </summary>
/// <param name="eventName">The event name.</param>
/// <param name="properties">The list of properties associated with the event.</param>
public void LogTelemetry(string eventName, IDictionary<string, string> properties)
{
SendBuildEvent(new TelemetryEventArgs
{
EventName = eventName,
Properties = properties == null ? new Dictionary<string, string>() : new Dictionary<string, string>(properties),
});
}
#endregion
#region IBuildEngine6 Implementation
/// <summary>
/// Gets the global properties for the current project.
/// </summary>
/// <returns>An <see cref="IReadOnlyDictionary{String, String}" /> containing the global properties of the current project.</returns>
public IReadOnlyDictionary<string, string> GetGlobalProperties()
{
return new Dictionary<string, string>(EffectiveConfiguration.GlobalProperties);
}
#endregion
#region IBuildEngine9 Implementation
public int RequestCores(int requestedCores)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(requestedCores);
if (!CallbacksSupported)
{
// Callbacks not available (cross-version scenario). Throw so callers' existing
// catch (NotImplementedException) blocks fire and fall back gracefully.
throw new NotImplementedException();
}
var request = new TaskHostCoresRequest(requestedCores, isRelease: false);
var response = SendCallbackRequestAndWaitForResponse<TaskHostCoresResponse>(request);
return response.GrantedCores;
}
public void ReleaseCores(int coresToRelease)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(coresToRelease);
if (!CallbacksSupported)
{
throw new NotImplementedException();
}
var request = new TaskHostCoresRequest(coresToRelease, isRelease: true);
SendCallbackRequestAndWaitForResponse<TaskHostCoresResponse>(request);
}
#endregion
#region IBuildEngine10 Members
[Serializable]
private sealed class EngineServicesImpl : EngineServices
{
private readonly OutOfProcTaskHostNode _taskHost;
internal EngineServicesImpl(OutOfProcTaskHostNode taskHost)
{
_taskHost = taskHost;
}
/// <summary>
/// No logging verbosity optimization in OOP nodes.
/// </summary>
public override bool LogsMessagesOfImportance(MessageImportance importance) => true;
/// <inheritdoc />
public override bool IsTaskInputLoggingEnabled
{
get
{
Assumed.NotNull(_taskHost.EffectiveConfiguration, "We should never have a null configuration during a BuildEngine callback!");
return _taskHost.EffectiveConfiguration.IsTaskInputLoggingEnabled;
}
}
#if FEATURE_REPORTFILEACCESSES
/// <summary>
/// Reports a file access from a task.
/// </summary>
/// <param name="fileAccessData">The file access to report.</param>
public void ReportFileAccess(FileAccessData fileAccessData)
{
_taskHost._fileAccessData.Add(fileAccessData);
}
#endif
}
public EngineServices EngineServices { get; }
#endregion
#region INodePacketFactory Members
/// <summary>
/// Registers the specified handler for a particular packet type.
/// </summary>
/// <param name="packetType">The packet type.</param>
/// <param name="factory">The factory for packets of the specified type.</param>
/// <param name="handler">The handler to be called when packets of the specified type are received.</param>
public void RegisterPacketHandler(NodePacketType packetType, NodePacketFactoryMethod factory, INodePacketHandler handler)
{
_packetFactory.RegisterPacketHandler(packetType, factory, handler);
}
/// <summary>
/// Unregisters a packet handler.
/// </summary>
/// <param name="packetType">The packet type.</param>
public void UnregisterPacketHandler(NodePacketType packetType)
{
_packetFactory.UnregisterPacketHandler(packetType);
}
/// <summary>
/// Takes a serializer, deserializes the packet and routes it to the appropriate handler.
/// </summary>
/// <param name="nodeId">The node from which the packet was received.</param>
/// <param name="packetType">The packet type.</param>
/// <param name="translator">The translator containing the data from which the packet should be reconstructed.</param>
public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator)
{
_packetFactory.DeserializeAndRoutePacket(nodeId, packetType, translator);
}
/// <summary>
/// Takes a serializer and deserializes the packet.
/// </summary>
/// <param name="packetType">The packet type.</param>
/// <param name="translator">The translator containing the data from which the packet should be reconstructed.</param>
public INodePacket DeserializePacket(NodePacketType packetType, ITranslator translator)
{
return _packetFactory.DeserializePacket(packetType, translator);
}
/// <summary>
/// Routes the specified packet
/// </summary>
/// <param name="nodeId">The node from which the packet was received.</param>
/// <param name="packet">The packet to route.</param>
public void RoutePacket(int nodeId, INodePacket packet)
{
_packetFactory.RoutePacket(nodeId, packet);
}
#endregion // INodePacketFactory Members
#region INodePacketHandler Members
/// <summary>
/// This method is invoked by the NodePacketRouter when a packet is received and is intended for
/// this recipient.
/// </summary>
/// <param name="node">The node from which the packet was received.</param>
/// <param name="packet">The packet.</param>
public void PacketReceived(int node, INodePacket packet)
{
lock (_receivedPackets)
{
_receivedPackets.Enqueue(packet);
_packetReceivedEvent.Set();
}
}
#endregion // INodePacketHandler Members
#region INode Members
/// <summary>
/// Starts up the node and processes messages until the node is requested to shut down.
/// </summary>
/// <param name="shutdownException">The exception which caused shutdown, if any.</param>
/// <returns>The reason for shutting down.</returns>
public NodeEngineShutdownReason Run(out Exception shutdownException, bool nodeReuse = false, byte parentPacketVersion = 1)
{
_registeredTaskObjectCache = new RegisteredTaskObjectCacheBase();
_parentPacketVersion = parentPacketVersion;
shutdownException = null;
// Snapshot the current environment
_savedEnvironment = CommunicationsUtilities.GetEnvironmentVariables();
_nodeReuse = nodeReuse;
_nodeEndpoint = new NodeEndpointOutOfProcTaskHost(nodeReuse, parentPacketVersion);
_nodeEndpoint.OnLinkStatusChanged += new LinkStatusChangedDelegate(OnLinkStatusChanged);
_nodeEndpoint.Listen(this);
WaitHandle[] waitHandles = [_shutdownEvent, _packetReceivedEvent, _taskCompleteEvent, _taskCancelledEvent];
while (true)
{
int index = WaitHandle.WaitAny(waitHandles);
switch (index)
{
case 0: // shutdownEvent
NodeEngineShutdownReason shutdownReason = HandleShutdown();
return shutdownReason;
case 1: // packetReceivedEvent
INodePacket packet = null;
int packetCount = _receivedPackets.Count;
while (packetCount > 0)
{
lock (_receivedPackets)
{
if (_receivedPackets.Count > 0)
{
packet = _receivedPackets.Dequeue();
}
else
{
break;
}
}
if (packet != null)
{
HandlePacket(packet);
}
}
break;
case 2: // taskCompleteEvent
CompleteTask();
break;
case 3: // taskCancelledEvent
CancelTask();
break;
}
}
// UNREACHABLE
}
#endregion
/// <summary>
/// Dispatches the packet to the correct handler.
/// </summary>
private void HandlePacket(INodePacket packet)
{
switch (packet.Type)
{
case NodePacketType.TaskHostConfiguration:
HandleTaskHostConfiguration(packet as TaskHostConfiguration);
break;
case NodePacketType.TaskHostTaskCancelled:
_taskCancelledEvent.Set();
break;
case NodePacketType.NodeBuildComplete:
HandleNodeBuildComplete(packet as NodeBuildComplete);
break;
case NodePacketType.TaskHostConsoleConfiguration:
InitializeConsoleRedirection();
break;
// Callback response packets - route to pending request
case NodePacketType.TaskHostIsRunningMultipleNodesResponse:
case NodePacketType.TaskHostCoresResponse:
case NodePacketType.TaskHostBuildResponse:
HandleCallbackResponse(packet);
break;
}
}
/// <summary>
/// Handles a callback response packet by completing the pending request's TaskCompletionSource.
/// This is called on the main thread and unblocks the task thread waiting for the response.
/// </summary>
private void HandleCallbackResponse(INodePacket packet)
{
if (packet is not ITaskHostCallbackPacket callbackPacket)
{
InternalError.Throw($"HandleCallbackResponse called with non-callback packet type: {packet.GetType().Name}");
return;