-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathTaskHostTask.cs
More file actions
727 lines (643 loc) · 29.8 KB
/
Copy pathTaskHostTask.cs
File metadata and controls
727 lines (643 loc) · 29.8 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
// 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.Diagnostics;
using System.Reflection;
using System.Threading;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
#if FEATURE_REPORTFILEACCESSES
using Microsoft.Build.Experimental.FileAccess;
using Microsoft.Build.FileAccesses;
#endif
#nullable disable
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// The wrapper task for tasks that wish to take advantage of the
/// task host factory feature. Generated by AssemblyTaskFactory
/// when it wants to run the loaded task in the task host.
/// </summary>
internal class TaskHostTask : IGeneratedTask, ICancelableTask, INodePacketFactory, INodePacketHandler
{
/// <summary>
/// The IBuildEngine callback object.
/// </summary>
private IBuildEngine _buildEngine;
/// <summary>
/// The host object that can be passed to this task.
/// </summary>
private ITaskHost _hostObject;
/// <summary>
/// Logging context for logging errors / issues
/// encountered in the TaskHostTask itself.
/// </summary>
private TaskLoggingContext _taskLoggingContext;
/// <summary>
/// Location of the task in the project file.
/// </summary>
private IElementLocation _taskLocation;
/// <summary>
/// The provider for the task host nodes.
/// </summary>
private IBuildComponentHost _buildComponentHost;
/// <summary>
/// The packet factory.
/// </summary>
private NodePacketFactory _packetFactory;
/// <summary>
/// The event which is set when we receive packets.
/// </summary>
private AutoResetEvent _packetReceivedEvent;
/// <summary>
/// The packet that is the end result of the task host task execution process
/// </summary>
private ConcurrentQueue<INodePacket> _receivedPackets;
/// <summary>
/// The set of parameters used to decide which host to launch.
/// </summary>
private TaskHostParameters _taskHostParameters;
/// <summary>
/// The type of the task that we are wrapping.
/// </summary>
private LoadedType _taskType;
#if FEATURE_APPDOMAIN
/// <summary>
/// The AppDomainSetup we'll want to apply to the AppDomain that we may
/// want to load the OOP task into.
/// </summary>
private AppDomainSetup _appDomainSetup;
#endif
/// <summary>
/// The task host context of the task host we're launching -- used to
/// communicate with the task host.
/// </summary>
private HandshakeOptions _requiredContext = HandshakeOptions.None;
/// <summary>
/// The task host node key identifying the task host we're launching.
/// </summary>
private TaskHostNodeKey _taskHostNodeKey;
/// <summary>
/// The ID of the node on which this task is scheduled to run.
/// </summary>
private readonly int _scheduledNodeId;
/// <summary>
/// True if currently connected to the task host; false otherwise.
/// </summary>
private bool _connectedToTaskHost = false;
/// <summary>
/// The provider for task host nodes.
/// </summary>
private NodeProviderOutOfProcTaskHost _taskHostProvider;
/// <summary>
/// Lock object to serialize access to the task host.
/// </summary>
private LockType _taskHostLock;
/// <summary>
/// Keeps track of whether the wrapped task has had cancel called against it.
/// </summary>
private bool _taskCancelled;
/// <summary>
/// The set of parameters that has been set to this wrapped task -- save them
/// here so that we can forward them on to the task host.
/// </summary>
private IDictionary<string, object> _setParameters;
/// <summary>
/// Did the task succeed?
/// </summary>
private bool _taskExecutionSucceeded = false;
/// <summary>
/// If true TaskHostFactory expects the TaskHost not will NOT expire after build (until it timeouts or is killed).
/// This is relevant for the next cases:
/// 1) TaskHostFactory is NOT explicitly requested (we always disable node reuse due to the transient nature of task host factory hosts).
/// 2) Runtime="NET" is specified in UsingTask.
/// 3) Environment variable MSBUILDFORCEALLTASKSOUTOFPROC is set.
/// </summary>
private bool _useSidecarTaskHost = false;
#if !NET35
private readonly HostServices _hostServices;
#endif
/// <summary>
/// The project file path that requests task execution.
/// </summary>
private string _projectFile;
/// <summary>
/// The task environment for virtualized environment operations.
/// </summary>
private readonly TaskEnvironment _taskEnvironment;
/// <summary>
/// Constructor.
/// </summary>
public TaskHostTask(
IElementLocation taskLocation,
TaskLoggingContext taskLoggingContext,
IBuildComponentHost buildComponentHost,
TaskHostParameters taskHostParameters,
LoadedType taskType,
bool useSidecarTaskHost,
string projectFile,
#if FEATURE_APPDOMAIN
AppDomainSetup appDomainSetup,
#endif
#if !NET35
HostServices hostServices,
#endif
int scheduledNodeId,
TaskEnvironment taskEnvironment)
{
ErrorUtilities.VerifyThrowInternalNull(taskType);
ErrorUtilities.VerifyThrowInternalNull(taskEnvironment);
_scheduledNodeId = scheduledNodeId;
_taskLocation = taskLocation;
_taskLoggingContext = taskLoggingContext;
_buildComponentHost = buildComponentHost;
_taskType = taskType;
#if FEATURE_APPDOMAIN
_appDomainSetup = appDomainSetup;
#endif
#if !NET35
_hostServices = hostServices;
#endif
_projectFile = projectFile;
_taskHostParameters = taskHostParameters;
_useSidecarTaskHost = useSidecarTaskHost;
_taskEnvironment = taskEnvironment;
_packetFactory = new NodePacketFactory();
(this as INodePacketFactory).RegisterPacketHandler(NodePacketType.LogMessage, LogMessagePacket.FactoryForDeserialization, this);
(this as INodePacketFactory).RegisterPacketHandler(NodePacketType.TaskHostTaskComplete, TaskHostTaskComplete.FactoryForDeserialization, this);
(this as INodePacketFactory).RegisterPacketHandler(NodePacketType.NodeShutdown, NodeShutdown.FactoryForDeserialization, this);
(this as INodePacketFactory).RegisterPacketHandler(NodePacketType.TaskHostIsRunningMultipleNodesRequest, TaskHostIsRunningMultipleNodesRequest.FactoryForDeserialization, this);
(this as INodePacketFactory).RegisterPacketHandler(NodePacketType.TaskHostCoresRequest, TaskHostCoresRequest.FactoryForDeserialization, this);
_packetReceivedEvent = new AutoResetEvent(false);
_receivedPackets = new ConcurrentQueue<INodePacket>();
_taskHostLock = new();
_setParameters = new Dictionary<string, object>();
}
/// <summary>
/// THe IBuildEngine callback object
/// </summary>
public IBuildEngine BuildEngine
{
get
{
return _buildEngine;
}
set
{
_buildEngine = value;
}
}
/// <summary>
/// The host object that can be passed to this task.
/// </summary>
public ITaskHost HostObject
{
get
{
return _hostObject;
}
set
{
_hostObject = value;
}
}
/// <summary>
/// Gets information about the assembly from which the task type was loaded.
/// </summary>
public AssemblyLoadInfo LoadedTaskAssemblyInfo => _taskType.Assembly;
/// <summary>
/// Sets the requested task parameter to the requested value.
/// </summary>
public void SetPropertyValue(TaskPropertyInfo property, object value)
{
_setParameters[property.Name] = value;
}
/// <summary>
/// Returns the value of the requested task parameter
/// </summary>
public object GetPropertyValue(TaskPropertyInfo property)
{
if (_setParameters.TryGetValue(property.Name, out object value))
{
// If we returned an exception, then we want to throw it when we
// do the get.
if (value is Exception ex)
{
throw ex;
}
return value;
}
else
{
PropertyInfo parameter = _taskType.Type.GetProperty(property.Name, BindingFlags.Instance | BindingFlags.Public);
return parameter.GetValue(this, null);
}
}
/// <summary>
/// Cancels the currently executing task
/// </summary>
public void Cancel()
{
if (!_taskCancelled)
{
lock (_taskHostLock)
{
if (_taskHostProvider != null && _connectedToTaskHost)
{
_taskHostProvider.SendData(_taskHostNodeKey, new TaskHostTaskCancelled());
}
}
_taskCancelled = true;
}
}
/// <summary>
/// Executes the task.
/// </summary>
public bool Execute()
{
_taskLoggingContext.LogComment(
MessageImportance.Low,
"ExecutingTaskInTaskHost",
_taskType.Type.Name,
_taskType.Assembly.AssemblyLocation,
_taskHostParameters.Runtime,
_taskHostParameters.Architecture);
// set up the node
lock (_taskHostLock)
{
_taskHostProvider = (NodeProviderOutOfProcTaskHost)_buildComponentHost.GetComponent(BuildComponentType.OutOfProcTaskHostNodeProvider);
ErrorUtilities.VerifyThrowInternalNull(_taskHostProvider, "taskHostProvider");
}
string taskLocation = AssemblyUtilities.GetAssemblyLocation(_taskType.Type.GetTypeInfo().Assembly);
if (string.IsNullOrEmpty(taskLocation))
{
// fall back to the AssemblyLoadInfo location for inline tasks loaded from bytes
taskLocation = _taskType?.Assembly?.AssemblyLocation ?? string.Empty;
}
TaskHostConfiguration hostConfiguration =
new TaskHostConfiguration(
_buildComponentHost.BuildParameters.NodeId,
_taskEnvironment.ProjectDirectory,
(IDictionary<string, string>)_taskEnvironment.GetEnvironmentVariables(),
_buildComponentHost.BuildParameters.Culture,
_buildComponentHost.BuildParameters.UICulture,
#if !NET35
_hostServices,
#endif
#if FEATURE_APPDOMAIN
_appDomainSetup,
#endif
BuildEngine.LineNumberOfTaskNode,
BuildEngine.ColumnNumberOfTaskNode,
BuildEngine.ProjectFileOfTaskNode,
BuildEngine.ContinueOnError,
_taskType.Type.FullName,
taskLocation,
_taskLoggingContext?.TargetLoggingContext?.Target?.Name,
_projectFile,
_buildComponentHost.BuildParameters.LogTaskInputs,
_setParameters,
new Dictionary<string, string>(_buildComponentHost.BuildParameters.GlobalProperties),
_taskLoggingContext.GetWarningsAsErrors(),
_taskLoggingContext.GetWarningsNotAsErrors(),
_taskLoggingContext.GetWarningsAsMessages());
try
{
lock (_taskHostLock)
{
_requiredContext = CommunicationsUtilities.GetHandshakeOptions(
taskHost: true,
// Determine if we should use node reuse based on build parameters or user preferences (comes from UsingTask element).
nodeReuse: _buildComponentHost.BuildParameters.EnableNodeReuse && _useSidecarTaskHost,
taskHostParameters: _taskHostParameters);
_taskHostNodeKey = new TaskHostNodeKey(_requiredContext, _scheduledNodeId);
_connectedToTaskHost = _taskHostProvider.AcquireAndSetUpHost(_taskHostNodeKey, this, this, hostConfiguration, _taskHostParameters);
}
if (_connectedToTaskHost)
{
try
{
bool taskFinished = false;
while (!taskFinished)
{
_packetReceivedEvent.WaitOne();
INodePacket packet = null;
// Handle the packet that's coming in
while (_receivedPackets.TryDequeue(out packet))
{
if (packet != null)
{
HandlePacket(packet, out taskFinished);
}
}
}
}
finally
{
lock (_taskHostLock)
{
_taskHostProvider.DisconnectFromHost(_taskHostNodeKey);
_connectedToTaskHost = false;
}
}
}
else
{
LogErrorUnableToCreateTaskHost(_requiredContext, _taskHostParameters.Runtime, _taskHostParameters.Architecture, null);
}
}
catch (BuildAbortedException)
{
LogErrorUnableToCreateTaskHost(_requiredContext, _taskHostParameters.Runtime, _taskHostParameters.Architecture, null);
}
catch (NodeFailedToLaunchException e)
{
LogErrorUnableToCreateTaskHost(_requiredContext, _taskHostParameters.Runtime, _taskHostParameters.Architecture, e);
}
return _taskExecutionSucceeded;
}
/// <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);
}
/// <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)
{
_receivedPackets.Enqueue(packet);
_packetReceivedEvent.Set();
}
/// <summary>
/// Called by TaskHostFactory to let the task know that if it needs to do any additional cleanup steps,
/// now would be the time.
/// </summary>
internal void Cleanup()
{
// for now, do nothing.
}
/// <summary>
/// Handles the packets received from the task host.
/// </summary>
private void HandlePacket(INodePacket packet, out bool taskFinished)
{
Debug.WriteLine("[TaskHostTask] Handling packet {0} at {1}", packet.Type, DateTime.Now);
taskFinished = false;
switch (packet.Type)
{
case NodePacketType.TaskHostTaskComplete:
HandleTaskHostTaskComplete(packet as TaskHostTaskComplete);
taskFinished = true;
break;
case NodePacketType.NodeShutdown:
HandleNodeShutdown(packet as NodeShutdown);
taskFinished = true;
break;
case NodePacketType.LogMessage:
HandleLoggedMessage(packet as LogMessagePacket);
break;
case NodePacketType.TaskHostIsRunningMultipleNodesRequest:
HandleIsRunningMultipleNodesRequest(packet as TaskHostIsRunningMultipleNodesRequest);
break;
case NodePacketType.TaskHostCoresRequest:
HandleCoresRequest(packet as TaskHostCoresRequest);
break;
default:
ErrorUtilities.ThrowInternalErrorUnreachable();
break;
}
}
/// <summary>
/// Task completed executing in the task host
/// </summary>
private void HandleTaskHostTaskComplete(TaskHostTaskComplete taskHostTaskComplete)
{
#if FEATURE_REPORTFILEACCESSES
if (taskHostTaskComplete.FileAccessData?.Count > 0)
{
IFileAccessManager fileAccessManager = ((IFileAccessManager)_buildComponentHost.GetComponent(BuildComponentType.FileAccessManager));
foreach (FileAccessData fileAccessData in taskHostTaskComplete.FileAccessData)
{
fileAccessManager.ReportFileAccess(fileAccessData, _buildComponentHost.BuildParameters.NodeId);
}
}
#endif
// If it crashed, or if it failed, it didn't succeed.
_taskExecutionSucceeded = taskHostTaskComplete.TaskResult == TaskCompleteType.Success ? true : false;
// Update the task environment with the environment changes from the task host execution
_taskEnvironment.SetEnvironment(taskHostTaskComplete.BuildProcessEnvironment);
// If it crashed during the execution phase, then we can effectively replicate the inproc task execution
// behaviour by just throwing here and letting the taskbuilder code take care of it the way it would
// have normally.
// We will also replicate the same behaviour if the TaskHost caught some exceptions after execution of the task.
if ((taskHostTaskComplete.TaskResult == TaskCompleteType.CrashedDuringExecution) ||
(taskHostTaskComplete.TaskResult == TaskCompleteType.CrashedAfterExecution))
{
throw new TargetInvocationException(taskHostTaskComplete.TaskException);
}
// On the other hand, if it crashed during initialization, there's not really a way to effectively replicate
// the inproc behavior -- in the inproc case, the task would have failed to load and crashed long before now.
// Furthermore, if we were just to throw here like in the execution case, we'd lose the ability to log
// different messages based on the circumstances of the initialization failure -- whether it was a setter failure,
// the task just could not be loaded, etc.
// So instead, when we catch the exception in the task host, we'll also record what message we want it to use
// when the error is logged; and given that information, log that error here. This has the effect of differing
// from the inproc case insofar as ContinueOnError is now respected, instead of forcing a stop here.
if (taskHostTaskComplete.TaskResult == TaskCompleteType.CrashedDuringInitialization)
{
string exceptionMessage;
string[] exceptionMessageArgs;
if (taskHostTaskComplete.TaskExceptionMessage != null)
{
exceptionMessage = taskHostTaskComplete.TaskExceptionMessage;
exceptionMessageArgs = taskHostTaskComplete.TaskExceptionMessageArgs;
}
else
{
exceptionMessageArgs = [_taskType.Type.Name,
AssemblyUtilities.GetAssemblyLocation(_taskType.Type.GetTypeInfo().Assembly),
string.Empty];
}
_taskLoggingContext.LogFatalError(taskHostTaskComplete.TaskException, new BuildEventFileInfo(_taskLocation), taskHostTaskComplete.TaskExceptionMessage, taskHostTaskComplete.TaskExceptionMessageArgs);
}
// Set the output parameters for later
foreach (KeyValuePair<string, TaskParameter> outputParam in taskHostTaskComplete.TaskOutputParameters)
{
_setParameters[outputParam.Key] = outputParam.Value?.WrappedParameter;
}
}
/// <summary>
/// The task host node failed for some reason
/// </summary>
private void HandleNodeShutdown(NodeShutdown nodeShutdown)
{
// if the task was canceled, it may send the shutdown packet before the task itself has exited --
// in this case, the shutdown is expected, so don't log errors. Also don't update taskExecutionSucceeded,
// as it has already been set properly (likely also to false) when we dealt with the TaskComplete
// packet that was sent immediately prior to this.
if (!_taskCancelled)
{
// nothing much else to say.
_taskExecutionSucceeded = false;
_taskLoggingContext.LogError(new BuildEventFileInfo(_taskLocation), "TaskHostExitedPrematurely", (nodeShutdown.Exception == null) ? String.Empty : nodeShutdown.Exception.ToString());
}
}
/// <summary>
/// Handle logged messages from the task host.
/// </summary>
private void HandleLoggedMessage(LogMessagePacket logMessagePacket)
{
switch (logMessagePacket.EventType)
{
case LoggingEventType.BuildErrorEvent:
this.BuildEngine.LogErrorEvent((BuildErrorEventArgs)logMessagePacket.NodeBuildEvent.Value.Value);
break;
case LoggingEventType.BuildWarningEvent:
this.BuildEngine.LogWarningEvent((BuildWarningEventArgs)logMessagePacket.NodeBuildEvent.Value.Value);
break;
case LoggingEventType.TaskCommandLineEvent:
case LoggingEventType.BuildMessageEvent:
this.BuildEngine.LogMessageEvent((BuildMessageEventArgs)logMessagePacket.NodeBuildEvent.Value.Value);
break;
case LoggingEventType.CustomEvent:
BuildEventArgs buildEvent = logMessagePacket.NodeBuildEvent.Value.Value;
// "Custom events" in terms of the communications infrastructure can also be, e.g. custom error events,
// in which case they need to be dealt with in the same way as their base type of event.
if (buildEvent is BuildErrorEventArgs buildErrorEventArgs)
{
this.BuildEngine.LogErrorEvent(buildErrorEventArgs);
}
else if (buildEvent is BuildWarningEventArgs buildWarningEventArgs)
{
this.BuildEngine.LogWarningEvent(buildWarningEventArgs);
}
else if (buildEvent is BuildMessageEventArgs buildMessageEventArgs)
{
this.BuildEngine.LogMessageEvent(buildMessageEventArgs);
}
else if (buildEvent is CustomBuildEventArgs customBuildEventArgs)
{
this.BuildEngine.LogCustomEvent(customBuildEventArgs);
}
else
{
ErrorUtilities.ThrowInternalError("Unknown event args type.");
}
break;
}
}
/// <summary>
/// Handle IsRunningMultipleNodes request from the TaskHost.
/// </summary>
private void HandleIsRunningMultipleNodesRequest(TaskHostIsRunningMultipleNodesRequest request)
{
bool result = _buildEngine is IBuildEngine2 engine2 && engine2.IsRunningMultipleNodes;
var response = new TaskHostIsRunningMultipleNodesResponse(request.RequestId, result);
_taskHostProvider.SendData(_taskHostNodeKey, response);
}
/// <summary>
/// Handle RequestCores/ReleaseCores request from the TaskHost.
/// Forwards the call to the in-process TaskHost's IBuildEngine9 implementation,
/// which handles implicit core accounting and scheduler communication.
/// </summary>
private void HandleCoresRequest(TaskHostCoresRequest request)
{
int grantedCores = 0;
if (request.IsRelease)
{
if (_buildEngine is IBuildEngine9 engine9)
{
engine9.ReleaseCores(request.RequestedCores);
}
}
else
{
if (_buildEngine is IBuildEngine9 engine9)
{
grantedCores = engine9.RequestCores(request.RequestedCores);
}
}
var response = new TaskHostCoresResponse(request.RequestId, grantedCores);
_taskHostProvider.SendData(_taskHostNodeKey, response);
}
/// <summary>
/// Since we log that we weren't able to connect to the task host in a couple of different places,
/// extract it out into a separate method.
/// </summary>
private void LogErrorUnableToCreateTaskHost(HandshakeOptions requiredContext, string runtime, string architecture, NodeFailedToLaunchException e)
{
string taskHostLocation = NodeProviderOutOfProcTaskHost.GetMSBuildExecutablePathForNonNETRuntimes(requiredContext);
#if NETFRAMEWORK
if (Handshake.IsHandshakeOptionEnabled(requiredContext, HandshakeOptions.NET))
{
taskHostLocation = NodeProviderOutOfProcTaskHost.GetMSBuildLocationForNETRuntime(requiredContext, _taskHostParameters).MSBuildAssemblyPath;
}
#endif
string msbuildLocation = taskHostLocation ??
// We don't know the path -- probably we're trying to get a 64-bit assembly on a
// 32-bit machine. At least give them the exe name to look for, though ...
((requiredContext & HandshakeOptions.CLR2) == HandshakeOptions.CLR2
? "MSBuildTaskHost.exe"
: NodeProviderOutOfProcTaskHost.GetTaskHostNameFromHostContext(requiredContext));
if (e == null)
{
_taskLoggingContext.LogError(new BuildEventFileInfo(_taskLocation), "TaskHostAcquireFailed", _taskType.Type.Name, runtime, architecture, msbuildLocation);
}
else
{
_taskLoggingContext.LogError(new BuildEventFileInfo(_taskLocation), "TaskHostNodeFailedToLaunch", _taskType.Type.Name, runtime, architecture, msbuildLocation, e.ErrorCode, e.Message);
}
}
}
}