forked from dotnet/msbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInProcNode.cs
More file actions
530 lines (449 loc) · 19.3 KB
/
Copy pathInProcNode.cs
File metadata and controls
530 lines (449 loc) · 19.3 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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Globalization;
using System.Threading;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using NodeLoggingContext = Microsoft.Build.BackEnd.Logging.NodeLoggingContext;
using Microsoft.Build.BackEnd.Components.Caching;
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// This class represents an implementation of INode for in-proc nodes.
/// </summary>
internal class InProcNode : INode, INodePacketFactory
{
/// <summary>
/// The build component host.
/// </summary>
private readonly IBuildComponentHost _componentHost;
/// <summary>
/// The environment at the time the build is started.
/// </summary>
private IDictionary<string, string> _savedEnvironment;
/// <summary>
/// The current directory at the time the build is started.
/// </summary>
private string _savedCurrentDirectory;
/// <summary>
/// The node logging context.
/// </summary>
private NodeLoggingContext _loggingContext;
/// <summary>
/// The build request engine.
/// </summary>
private readonly IBuildRequestEngine _buildRequestEngine;
/// <summary>
/// The queue of packets we have received but which have not yet been processed.
/// </summary>
private readonly ConcurrentQueue<INodePacket> _receivedPackets;
/// <summary>
/// The event which is set when we receive packets.
/// </summary>
private readonly AutoResetEvent _packetReceivedEvent;
/// <summary>
/// The event which is set when we should shut down.
/// </summary>
private readonly AutoResetEvent _shutdownEvent;
/// <summary>
/// The reason we are shutting down.
/// </summary>
private NodeEngineShutdownReason _shutdownReason;
/// <summary>
/// The exception, if any, which caused shutdown.
/// </summary>
private Exception _shutdownException;
/// <summary>
/// The node endpoint
/// </summary>
private readonly INodeEndpoint _nodeEndpoint;
/// <summary>
/// Handler for engine exceptions.
/// </summary>
private readonly EngineExceptionDelegate _engineExceptionEventHandler;
/// <summary>
/// Handler for new configuration requests.
/// </summary>
private readonly NewConfigurationRequestDelegate _newConfigurationRequestEventHandler;
/// <summary>
/// Handler for blocked request events.
/// </summary>
private readonly RequestBlockedDelegate _requestBlockedEventHandler;
/// <summary>
/// Handler for request completed events.
/// </summary>
private readonly RequestCompleteDelegate _requestCompleteEventHandler;
/// <summary>
/// Handler for resource request events.
/// </summary>
private readonly ResourceRequestDelegate _resourceRequestHandler;
/// <summary>
/// Constructor.
/// </summary>
public InProcNode(IBuildComponentHost componentHost, INodeEndpoint inProcNodeEndpoint)
{
_componentHost = componentHost;
_nodeEndpoint = inProcNodeEndpoint;
_receivedPackets = new ConcurrentQueue<INodePacket>();
_packetReceivedEvent = new AutoResetEvent(false);
_shutdownEvent = new AutoResetEvent(false);
_buildRequestEngine = componentHost.GetComponent(BuildComponentType.RequestEngine) as IBuildRequestEngine;
_engineExceptionEventHandler = OnEngineException;
_newConfigurationRequestEventHandler = OnNewConfigurationRequest;
_requestBlockedEventHandler = OnNewRequest;
_requestCompleteEventHandler = OnRequestComplete;
_resourceRequestHandler = OnResourceRequest;
}
#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)
{
try
{
_nodeEndpoint.OnLinkStatusChanged += OnLinkStatusChanged;
_nodeEndpoint.Listen(this);
var waitHandles = new WaitHandle[] { _shutdownEvent, _packetReceivedEvent };
// Get the current directory before doing work. We need this so we can restore the directory when the node shuts down.
_savedCurrentDirectory = NativeMethodsShared.GetCurrentDirectory();
while (true)
{
int index = WaitHandle.WaitAny(waitHandles);
switch (index)
{
case 0:
{
NodeEngineShutdownReason shutdownReason = HandleShutdown(out shutdownException);
if (_componentHost.BuildParameters.ShutdownInProcNodeOnBuildFinish)
{
return shutdownReason;
}
break;
}
case 1:
while (_receivedPackets.TryDequeue(out INodePacket packet))
{
if (packet != null)
{
HandlePacket(packet);
}
}
break;
}
}
}
catch (ThreadAbortException)
{
// Do nothing. This will happen when the thread is forcibly terminated because we are shutting down, for example
// when the unit test framework terminates.
throw;
}
catch (Exception e)
{
// Dump all engine exceptions to a temp file
// so that we have something to go on in the
// event of a failure
ExceptionHandling.DumpExceptionToFile(e);
// This is fatal: process will terminate: make sure the
// debugger launches
ErrorUtilities.ThrowInternalError(e.Message, e);
throw;
}
// UNREACHABLE
}
#endregion
#region INodePacketFactory Members
/// <summary>
/// Not necessary for in-proc node - we don't serialize.
/// </summary>
public void RegisterPacketHandler(NodePacketType packetType, NodePacketFactoryMethod factory, INodePacketHandler handler)
{
// The in-proc node doesn't need to do this.
}
/// <summary>
/// Not necessary for in-proc node - we don't serialize.
/// </summary>
public void UnregisterPacketHandler(NodePacketType packetType)
{
// The in-proc node doesn't need to do this.
}
/// <summary>
/// Not necessary for in-proc node - we don't serialize.
/// </summary>
public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator)
{
// The in-proc endpoint shouldn't be serializing, just routing.
ErrorUtilities.ThrowInternalError("Unexpected call to DeserializeAndRoutePacket on the in-proc node.");
}
/// <summary>
/// Routes the packet to the appropriate handler.
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <param name="packet">The packet.</param>
public void RoutePacket(int nodeId, INodePacket packet)
{
_receivedPackets.Enqueue(packet);
_packetReceivedEvent.Set();
}
#endregion
/// <summary>
/// Event handler for the BuildEngine's OnRequestComplete event.
/// </summary>
private void OnRequestComplete(BuildRequest request, BuildResult result)
{
if (_nodeEndpoint.LinkStatus == LinkStatus.Active)
{
_nodeEndpoint.SendData(result);
}
}
/// <summary>
/// Event handler for the BuildEngine's OnNewRequest event.
/// </summary>
private void OnNewRequest(BuildRequestBlocker blocker)
{
if (_nodeEndpoint.LinkStatus == LinkStatus.Active)
{
_nodeEndpoint.SendData(blocker);
}
}
/// <summary>
/// Event handler for the BuildEngine's OnNewConfigurationRequest event.
/// </summary>
private void OnNewConfigurationRequest(BuildRequestConfiguration config)
{
if (_nodeEndpoint.LinkStatus == LinkStatus.Active)
{
_nodeEndpoint.SendData(config);
}
}
/// <summary>
/// Event handler for the BuildEngine's OnResourceRequest event.
/// </summary>
private void OnResourceRequest(ResourceRequest request)
{
if (_nodeEndpoint.LinkStatus == LinkStatus.Active)
{
_nodeEndpoint.SendData(request);
}
}
/// <summary>
/// Event handler for the LoggingService's OnLoggingThreadException event.
/// </summary>
private void OnLoggingThreadException(Exception e)
{
OnEngineException(e);
}
/// <summary>
/// Event handler for the BuildEngine's OnEngineException event.
/// </summary>
private void OnEngineException(Exception e)
{
_shutdownException = e;
_shutdownReason = NodeEngineShutdownReason.Error;
_shutdownEvent.Set();
}
/// <summary>
/// Perform necessary actions to shut down the node.
/// </summary>
private NodeEngineShutdownReason HandleShutdown(out Exception exception)
{
// Console.WriteLine("Node shutting down with reason {0} and exception: {1}", shutdownReason, shutdownException);
try
{
// Clean up the engine
if (_buildRequestEngine != null && _buildRequestEngine.Status != BuildRequestEngineStatus.Uninitialized)
{
_buildRequestEngine.CleanupForBuild();
}
}
catch (Exception ex) when (!ExceptionHandling.IsCriticalException(ex))
{
// If we had some issue shutting down, don't reuse the node because we may be in some weird state.
if (_shutdownReason == NodeEngineShutdownReason.BuildCompleteReuse)
{
_shutdownReason = NodeEngineShutdownReason.BuildComplete;
}
}
// Dispose of any build registered objects
IRegisteredTaskObjectCache objectCache = (IRegisteredTaskObjectCache)(_componentHost.GetComponent(BuildComponentType.RegisteredTaskObjectCache));
objectCache.DisposeCacheObjects(RegisteredTaskObjectLifetime.Build);
if (_shutdownReason != NodeEngineShutdownReason.BuildCompleteReuse)
{
// Dispose of any node registered objects.
((IBuildComponent)objectCache).ShutdownComponent();
}
if (_componentHost.BuildParameters.SaveOperatingEnvironment)
{
// Restore the original current directory.
NativeMethodsShared.SetCurrentDirectory(_savedCurrentDirectory);
// Restore the original environment.
foreach (KeyValuePair<string, string> entry in CommunicationsUtilities.GetEnvironmentVariables())
{
if (!_savedEnvironment.ContainsKey(entry.Key))
{
Environment.SetEnvironmentVariable(entry.Key, null);
}
}
foreach (KeyValuePair<string, string> entry in _savedEnvironment)
{
Environment.SetEnvironmentVariable(entry.Key, entry.Value);
}
}
exception = _shutdownException;
if (_loggingContext != null)
{
_loggingContext.LoggingService.OnLoggingThreadException -= OnLoggingThreadException;
_loggingContext = null;
}
// Notify the BuildManager that we are done.
if (_nodeEndpoint.LinkStatus == LinkStatus.Active)
{
_nodeEndpoint.SendData(new NodeShutdown(_shutdownReason == NodeEngineShutdownReason.Error ? NodeShutdownReason.Error : NodeShutdownReason.Requested, exception));
}
_buildRequestEngine.OnEngineException -= _engineExceptionEventHandler;
_buildRequestEngine.OnNewConfigurationRequest -= _newConfigurationRequestEventHandler;
_buildRequestEngine.OnRequestBlocked -= _requestBlockedEventHandler;
_buildRequestEngine.OnRequestComplete -= _requestCompleteEventHandler;
_buildRequestEngine.OnResourceRequest -= _resourceRequestHandler;
return _shutdownReason;
}
/// <summary>
/// Dispatches the packet to the correct handler.
/// </summary>
private void HandlePacket(INodePacket packet)
{
switch (packet.Type)
{
case NodePacketType.BuildRequest:
HandleBuildRequest(packet as BuildRequest);
break;
case NodePacketType.BuildRequestConfiguration:
HandleBuildRequestConfiguration();
break;
case NodePacketType.BuildRequestConfigurationResponse:
HandleBuildRequestConfigurationResponse(packet as BuildRequestConfigurationResponse);
break;
case NodePacketType.BuildRequestUnblocker:
HandleBuildResult(packet as BuildRequestUnblocker);
break;
case NodePacketType.NodeConfiguration:
HandleNodeConfiguration(packet as NodeConfiguration);
break;
case NodePacketType.NodeBuildComplete:
HandleNodeBuildComplete(packet as NodeBuildComplete);
break;
case NodePacketType.ResourceResponse:
HandleResourceResponse(packet as ResourceResponse);
break;
}
}
/// <summary>
/// Event handler for the node endpoint's LinkStatusChanged event.
/// </summary>
private void OnLinkStatusChanged(INodeEndpoint endpoint, LinkStatus status)
{
switch (status)
{
case LinkStatus.ConnectionFailed:
case LinkStatus.Failed:
_shutdownReason = NodeEngineShutdownReason.ConnectionFailed;
_shutdownEvent.Set();
break;
case LinkStatus.Inactive:
break;
default:
break;
}
}
/// <summary>
/// Handles the BuildRequest packet.
/// </summary>
private void HandleBuildRequest(BuildRequest request)
{
_buildRequestEngine.SubmitBuildRequest(request);
}
/// <summary>
/// Handles the BuildRequestConfiguration packet.
/// </summary>
private static void HandleBuildRequestConfiguration()
{
// Configurations are already in the cache, which we share with the BuildManager.
}
/// <summary>
/// Handles the BuildRequestConfigurationResponse packet.
/// </summary>
private void HandleBuildRequestConfigurationResponse(BuildRequestConfigurationResponse response)
{
_buildRequestEngine.ReportConfigurationResponse(response);
}
/// <summary>
/// Handles the BuildResult packet.
/// </summary>
private void HandleBuildResult(BuildRequestUnblocker unblocker)
{
_buildRequestEngine.UnblockBuildRequest(unblocker);
}
/// <summary>
/// Handles the NodeConfiguration packet.
/// </summary>
private void HandleNodeConfiguration(NodeConfiguration configuration)
{
// Set the culture.
CultureInfo.CurrentCulture = configuration.BuildParameters.Culture;
CultureInfo.CurrentUICulture = configuration.BuildParameters.UICulture;
// Snapshot the initial environment.
_savedEnvironment = CommunicationsUtilities.GetEnvironmentVariables();
// Save the current directory.
_savedCurrentDirectory = NativeMethodsShared.GetCurrentDirectory();
// Set the node id.
_componentHost.BuildParameters.NodeId = configuration.NodeId;
_shutdownException = null;
#if FEATURE_APPDOMAIN
// And the AppDomainSetup
_componentHost.BuildParameters.AppDomainSetup = configuration.AppDomainSetup;
#endif
// Declare in-proc
_componentHost.BuildParameters.IsOutOfProc = false;
// Set the logging exception handler
ILoggingService loggingService = _componentHost.LoggingService;
loggingService.OnLoggingThreadException += OnLoggingThreadException;
// Now prep the buildRequestEngine for the build.
_loggingContext = new NodeLoggingContext(loggingService, configuration.NodeId, true /* inProcNode */);
_buildRequestEngine.OnEngineException += _engineExceptionEventHandler;
_buildRequestEngine.OnNewConfigurationRequest += _newConfigurationRequestEventHandler;
_buildRequestEngine.OnRequestBlocked += _requestBlockedEventHandler;
_buildRequestEngine.OnRequestComplete += _requestCompleteEventHandler;
_buildRequestEngine.OnResourceRequest += _resourceRequestHandler;
if (_shutdownException != null)
{
HandleShutdown(out Exception exception);
throw exception;
}
_buildRequestEngine.InitializeForBuild(_loggingContext);
}
/// <summary>
/// Handles the NodeBuildComplete packet.
/// </summary>
private void HandleNodeBuildComplete(NodeBuildComplete buildComplete)
{
_shutdownReason = buildComplete.PrepareForReuse ? NodeEngineShutdownReason.BuildCompleteReuse : NodeEngineShutdownReason.BuildComplete;
_shutdownEvent.Set();
}
/// <summary>
/// Handles the ResourceResponse packet.
/// </summary>
private void HandleResourceResponse(ResourceResponse response)
{
_buildRequestEngine.GrantResources(response);
}
}
}