-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
TaskHost.cs
1182 lines (1021 loc) · 52.3 KB
/
TaskHost.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
// 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;
using System.Collections.Generic;
using System.Globalization;
#if FEATURE_APPDOMAIN
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting;
#endif
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Execution;
using System.Diagnostics;
using Microsoft.Build.Collections;
using ElementLocation = Microsoft.Build.Construction.ElementLocation;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using TaskLoggingContext = Microsoft.Build.BackEnd.Logging.TaskLoggingContext;
using System.Threading.Tasks;
using Microsoft.Build.BackEnd.Components.Caching;
using System.Reflection;
using Microsoft.Build.Eventing;
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// The task host object which allows tasks to interface with the rest of the build system.
/// Implementation of IBuildEngineX is thread-safe, so, for example, tasks can log concurrently on multiple threads.
/// </summary>
internal class TaskHost :
#if FEATURE_APPDOMAIN
MarshalByRefObject,
#endif
IBuildEngine9
{
/// <summary>
/// True if the "secret" environment variable MSBUILDNOINPROCNODE is set.
/// </summary>
private static bool s_onlyUseOutOfProcNodes = Environment.GetEnvironmentVariable("MSBUILDNOINPROCNODE") == "1";
/// <summary>
/// Help diagnose tasks that log after they return.
/// </summary>
private static bool s_breakOnLogAfterTaskReturns = Environment.GetEnvironmentVariable("MSBUILDBREAKONLOGAFTERTASKRETURNS") == "1";
/// <summary>
/// The build component host
/// </summary>
private IBuildComponentHost _host;
/// <summary>
/// The build request entry
/// </summary>
private BuildRequestEntry _requestEntry;
/// <summary>
/// Location of the task node in the original file
/// </summary>
private ElementLocation _taskLocation;
/// <summary>
/// The task logging context
/// </summary>
private TaskLoggingContext _taskLoggingContext;
/// <summary>
/// True if the task connected to this proxy is alive
/// </summary>
private bool _activeProxy;
/// <summary>
/// The callback used to invoke the target builder.
/// </summary>
private ITargetBuilderCallback _targetBuilderCallback;
/// <summary>
/// This reference type is used to block access to a single entry methods of the interface
/// </summary>
private object _callbackMonitor;
#if FEATURE_APPDOMAIN
/// <summary>
/// A client sponsor is a class
/// which will respond to a lease renewal request and will
/// increase the lease time allowing the object to stay in memory
/// </summary>
private ClientSponsor _sponsor;
#endif
/// <summary>
/// Legacy continue on error value per batch exposed via IBuildEngine
/// </summary>
private bool _continueOnError;
/// <summary>
/// Flag indicating if errors should be converted to warnings.
/// </summary>
private bool _convertErrorsToWarnings;
/// <summary>
/// The thread on which we yielded.
/// </summary>
private int _yieldThreadId = -1;
/// <summary>
/// Constructor
/// </summary>
/// <param name="host">The component host</param>
/// <param name="requestEntry">The build request entry</param>
/// <param name="taskLocation">The <see cref="ElementLocation"/> of the task.</param>
/// <param name="targetBuilderCallback">An <see cref="ITargetBuilderCallback"/> to use to invoke targets and build projects.</param>
public TaskHost(IBuildComponentHost host, BuildRequestEntry requestEntry, ElementLocation taskLocation, ITargetBuilderCallback targetBuilderCallback)
{
ErrorUtilities.VerifyThrowArgumentNull(host, nameof(host));
ErrorUtilities.VerifyThrowArgumentNull(requestEntry, nameof(requestEntry));
ErrorUtilities.VerifyThrowInternalNull(taskLocation, nameof(taskLocation));
_host = host;
_requestEntry = requestEntry;
_taskLocation = taskLocation;
_targetBuilderCallback = targetBuilderCallback;
_continueOnError = false;
_activeProxy = true;
_callbackMonitor = new Object();
}
/// <summary>
/// Returns true in the multiproc case
/// </summary>
/// <comment>
/// If MSBUILDNOINPROCNODE is set, then even if there's only one node in the buildparameters, it will be an out-of-proc node.
/// </comment>
public bool IsRunningMultipleNodes
{
get
{
VerifyActiveProxy();
return _host.BuildParameters.MaxNodeCount > 1 || s_onlyUseOutOfProcNodes;
}
}
/// <summary>
/// Reflects the value of the ContinueOnError attribute.
/// </summary>
public bool ContinueOnError
{
get
{
VerifyActiveProxy();
return _continueOnError;
}
internal set
{
_continueOnError = value;
}
}
/// <summary>
/// The line number this task is on
/// </summary>
public int LineNumberOfTaskNode
{
get
{
return _taskLocation.Line;
}
}
/// <summary>
/// The column number this task is on
/// </summary>
public int ColumnNumberOfTaskNode
{
get
{
return _taskLocation.Column;
}
}
/// <summary>
/// The project file this task is in.
/// Typically this is an imported .targets file.
/// Unfortunately the interface has shipped with a poor name, so we cannot change it.
/// </summary>
public string ProjectFileOfTaskNode
{
get
{
return _taskLocation.File;
}
}
/// <summary>
/// Indicates whether or not errors should be converted to warnings.
/// </summary>
internal bool ConvertErrorsToWarnings
{
get { return _convertErrorsToWarnings; }
set { _convertErrorsToWarnings = value; }
}
/// <summary>
/// Sets or retrieves the logging context
/// </summary>
internal TaskLoggingContext LoggingContext
{
[DebuggerStepThrough]
get
{ return _taskLoggingContext; }
[DebuggerStepThrough]
set
{ _taskLoggingContext = value; }
}
#if FEATURE_APPDOMAIN
/// <summary>
/// For configuring child AppDomains.
/// </summary>
internal AppDomainSetup AppDomainSetup
{
get
{
return _host.BuildParameters.AppDomainSetup;
}
}
#endif
/// <summary>
/// Whether or not this is out of proc.
/// </summary>
internal bool IsOutOfProc
{
get
{
return _host.BuildParameters.IsOutOfProc;
}
}
public bool BuildRequestsSucceeded { get; private set; } = true;
#region IBuildEngine2 Members
/// <summary>
/// Builds a single project file
/// Thread safe.
/// </summary>
/// <param name="projectFileName">The project file</param>
/// <param name="targetNames">The list of targets to build</param>
/// <param name="globalProperties">The global properties to use</param>
/// <param name="targetOutputs">The outputs from the targets</param>
/// <param name="toolsVersion">The tools version to use</param>
/// <returns>True on success, false otherwise.</returns>
public bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs, string toolsVersion)
{
VerifyActiveProxy();
return BuildProjectFilesInParallel
(
new string[] { projectFileName },
targetNames,
new IDictionary[] { globalProperties },
new IDictionary[] { targetOutputs },
new string[] { toolsVersion },
true,
false
);
}
/// <summary>
/// Builds multiple project files in parallel. This is the method the old MSBuild task invokes.
/// Thread safe.
/// </summary>
/// <param name="projectFileNames">The list of projects to build</param>
/// <param name="targetNames">The set of targets to build</param>
/// <param name="globalProperties">The global properties to use for each project</param>
/// <param name="targetOutputsPerProject">The outputs for each target on each project</param>
/// <param name="toolsVersion">The tools versions to use</param>
/// <param name="useResultsCache">Whether to use the results cache</param>
/// <param name="unloadProjectsOnCompletion">Whether to unload projects when we are done.</param>
/// <returns>True on success, false otherwise.</returns>
public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion)
{
bool includeTargetOutputs = (targetOutputsPerProject != null);
// If the caller supplies an array to put the target outputs in, it must have the same length as the array of project file names they provided, too.
// "MSB3094: "{2}" refers to {0} item(s), and "{3}" refers to {1} item(s). They must have the same number of items."
ErrorUtilities.VerifyThrowArgument((targetOutputsPerProject == null) || (projectFileNames.Length == targetOutputsPerProject.Length), "General.TwoVectorsMustHaveSameLength", projectFileNames.Length, targetOutputsPerProject?.Length ?? 0, "projectFileNames", "targetOutputsPerProject");
BuildEngineResult result = BuildProjectFilesInParallel(projectFileNames, targetNames, globalProperties, new List<String>[projectFileNames.Length], toolsVersion, includeTargetOutputs);
if (includeTargetOutputs)
{
// Copy results from result.TargetOutputsPerProject to targetOutputsPerProject
// We should always have the same number of entries - although an entry might be empty if a project failed.
ErrorUtilities.VerifyThrow(targetOutputsPerProject.Length == result.TargetOutputsPerProject.Count, "{0} != {1}", targetOutputsPerProject.Length, result.TargetOutputsPerProject.Count);
for (int i = 0; i < targetOutputsPerProject.Length; i++)
{
if (targetOutputsPerProject[i] != null)
{
foreach (KeyValuePair<string, ITaskItem[]> output in result.TargetOutputsPerProject[i])
{
targetOutputsPerProject[i].Add(output.Key, output.Value);
}
}
}
}
BuildRequestsSucceeded = result.Result;
return result.Result;
}
#endregion
#region IBuildEngine3 Members
/// <summary>
/// Builds multiple project files in parallel.
/// Thread safe.
/// </summary>
/// <param name="projectFileNames">The list of projects to build</param>
/// <param name="targetNames">The set of targets to build</param>
/// <param name="globalProperties">The global properties to use for each project</param>
/// <param name="undefineProperties">The list of global properties to undefine</param>
/// <param name="toolsVersion">The tools versions to use</param>
/// <param name="returnTargetOutputs">Should the target outputs be returned in the BuildEngineResult</param>
/// <returns>A structure containing the result of the build, success or failure and the list of target outputs per project</returns>
public BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, IList<String>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs)
{
lock (_callbackMonitor)
{
return BuildProjectFilesInParallelAsync(projectFileNames, targetNames, globalProperties, undefineProperties, toolsVersion, returnTargetOutputs).Result;
}
}
/// <summary>
/// Requests to yield the node.
/// Thread safe, however Yield cannot be called unless the
/// last call to Yield or Reacquire was Reacquire.
/// </summary>
public void Yield()
{
lock (_callbackMonitor)
{
IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback;
ErrorUtilities.VerifyThrow(_yieldThreadId == -1, "Cannot call Yield() while yielding.");
_yieldThreadId = Thread.CurrentThread.ManagedThreadId;
MSBuildEventSource.Log.ExecuteTaskYieldStart(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId);
builderCallback.Yield();
}
}
/// <summary>
/// Requests to reacquire the node.
/// Thread safe, however Reacquire cannot be called unless the
/// last call to Yield or Reacquire was Yield.
/// </summary>
public void Reacquire()
{
// Release all cores on reacquire. The assumption here is that the task is done with CPU intensive work at this point and forgetting
// to release explicitly granted cores when reacquiring the node may lead to deadlocks.
ReleaseAllCores();
lock (_callbackMonitor)
{
IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback;
ErrorUtilities.VerifyThrow(_yieldThreadId != -1, "Cannot call Reacquire() before Yield().");
ErrorUtilities.VerifyThrow(_yieldThreadId == Thread.CurrentThread.ManagedThreadId, "Cannot call Reacquire() on thread {0} when Yield() was called on thread {1}", Thread.CurrentThread.ManagedThreadId, _yieldThreadId);
MSBuildEventSource.Log.ExecuteTaskYieldStop(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId);
MSBuildEventSource.Log.ExecuteTaskReacquireStart(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId);
builderCallback.Reacquire();
MSBuildEventSource.Log.ExecuteTaskReacquireStop(_taskLoggingContext.TaskName, _taskLoggingContext.BuildEventContext.TaskId);
_yieldThreadId = -1;
}
}
#endregion
#region IBuildEngine Members
/// <summary>
/// Logs an error event for the current task
/// Thread safe.
/// </summary>
/// <param name="e">The event args</param>
public void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e)
{
lock (_callbackMonitor)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
if (!_activeProxy)
{
// The task has been logging on another thread, typically
// because of logging a spawned process's output, and has
// not terminated this logging before it returned. This is common
// enough that we don't want to crash and break the entire build. But
// we don't have any good way to log it any more, as not only has this task
// finished, the whole build might have finished! The task author will
// just have to figure out that their task has a bug by themselves.
if (s_breakOnLogAfterTaskReturns)
{
Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message));
}
return;
}
// If we are in building across process we need the events to be serializable. This method will
// check to see if we are building with multiple process and if the event is serializable. It will
// also log a warning if the event is not serializable and drop the logging message.
if (IsRunningMultipleNodes && !IsEventSerializable(e))
{
return;
}
if (_convertErrorsToWarnings)
{
// Convert the error into a warning. We do this because the whole point of
// ContinueOnError is that a project author expects that the task might fail,
// but wants to ignore the failures. This implies that we shouldn't be logging
// errors either, because you should never have a successful build with errors.
BuildWarningEventArgs warningEvent = new BuildWarningEventArgs
(
e.Subcategory,
e.Code,
e.File,
e.LineNumber,
e.ColumnNumber,
e.EndLineNumber,
e.EndColumnNumber,
e.Message,
e.HelpKeyword,
e.SenderName
);
warningEvent.BuildEventContext = _taskLoggingContext.BuildEventContext;
_taskLoggingContext.LoggingService.LogBuildEvent(warningEvent);
// Log a message explaining why we converted the previous error into a warning.
_taskLoggingContext.LoggingService.LogComment(_taskLoggingContext.BuildEventContext, MessageImportance.Normal, "ErrorConvertedIntoWarning");
}
else
{
e.BuildEventContext = _taskLoggingContext.BuildEventContext;
_taskLoggingContext.LoggingService.LogBuildEvent(e);
_taskLoggingContext.HasLoggedErrors = true;
}
}
}
/// <summary>
/// Logs a warning event for the current task
/// Thread safe.
/// </summary>
/// <param name="e">The event args</param>
public void LogWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs e)
{
lock (_callbackMonitor)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
if (!_activeProxy)
{
// The task has been logging on another thread, typically
// because of logging a spawned process's output, and has
// not terminated this logging before it returned. This is common
// enough that we don't want to crash and break the entire build. But
// we don't have any good way to log it any more, as not only has this task
// finished, the whole build might have finished! The task author will
// just have to figure out that their task has a bug by themselves.
if (s_breakOnLogAfterTaskReturns)
{
Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message));
}
return;
}
// If we are in building across process we need the events to be serializable. This method will
// check to see if we are building with multiple process and if the event is serializable. It will
// also log a warning if the event is not serializable and drop the logging message.
if (IsRunningMultipleNodes && !IsEventSerializable(e))
{
return;
}
e.BuildEventContext = _taskLoggingContext.BuildEventContext;
_taskLoggingContext.LoggingService.LogBuildEvent(e);
}
}
/// <summary>
/// Logs a message event for the current task
/// Thread safe.
/// </summary>
/// <param name="e">The event args</param>
public void LogMessageEvent(Microsoft.Build.Framework.BuildMessageEventArgs e)
{
lock (_callbackMonitor)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
if (!_activeProxy)
{
// The task has been logging on another thread, typically
// because of logging a spawned process's output, and has
// not terminated this logging before it returned. This is common
// enough that we don't want to crash and break the entire build. But
// we don't have any good way to log it any more, as not only has this task
// finished, the whole build might have finished! The task author will
// just have to figure out that their task has a bug by themselves.
if (s_breakOnLogAfterTaskReturns)
{
Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message));
}
return;
}
// If we are in building across process we need the events to be serializable. This method will
// check to see if we are building with multiple process and if the event is serializable. It will
// also log a warning if the event is not serializable and drop the logging message.
if (IsRunningMultipleNodes && !IsEventSerializable(e))
{
return;
}
e.BuildEventContext = _taskLoggingContext.BuildEventContext;
_taskLoggingContext.LoggingService.LogBuildEvent(e);
}
}
/// <summary>
/// Logs a custom event for the current task
/// Thread safe.
/// </summary>
/// <param name="e">The event args</param>
public void LogCustomEvent(Microsoft.Build.Framework.CustomBuildEventArgs e)
{
lock (_callbackMonitor)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
if (!_activeProxy)
{
// The task has been logging on another thread, typically
// because of logging a spawned process's output, and has
// not terminated this logging before it returned. This is common
// enough that we don't want to crash and break the entire build. But
// we don't have any good way to log it any more, as not only has this task
// finished, the whole build might have finished! The task author will
// just have to figure out that their task has a bug by themselves.
if (s_breakOnLogAfterTaskReturns)
{
Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log '{1}'", _taskLocation.ToString(), e.Message));
}
return;
}
// If we are in building across process we need the events to be serializable. This method will
// check to see if we are building with multiple process and if the event is serializable. It will
// also log a warning if the event is not serializable and drop the logging message.
if (IsRunningMultipleNodes && !IsEventSerializable(e))
{
return;
}
e.BuildEventContext = _taskLoggingContext.BuildEventContext;
_taskLoggingContext.LoggingService.LogBuildEvent(e);
}
}
/// <summary>
/// Builds a single project file
/// Thread safe.
/// </summary>
/// <param name="projectFileName">The project file name</param>
/// <param name="targetNames">The set of targets to build.</param>
/// <param name="globalProperties">The global properties to use</param>
/// <param name="targetOutputs">The outputs from the targets</param>
/// <returns>True on success, false otherwise.</returns>
public bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs)
{
VerifyActiveProxy();
return BuildProjectFile(projectFileName, targetNames, globalProperties, targetOutputs, null);
}
#endregion
#region IBuildEngine4 Members
/// <summary>
/// Disposes of all of the objects with the specified lifetime.
/// </summary>
public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
{
var objectCache = (IRegisteredTaskObjectCache)_host.GetComponent(BuildComponentType.RegisteredTaskObjectCache);
objectCache.RegisterTaskObject(key, obj, lifetime, allowEarlyCollection);
}
/// <summary>
/// Gets a previously registered task object.
/// </summary>
public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime)
{
var objectCache = (IRegisteredTaskObjectCache)_host.GetComponent(BuildComponentType.RegisteredTaskObjectCache);
return objectCache.GetRegisteredTaskObject(key, lifetime);
}
/// <summary>
/// Unregisters a task object.
/// </summary>
public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime)
{
var objectCache = (IRegisteredTaskObjectCache)_host.GetComponent(BuildComponentType.RegisteredTaskObjectCache);
return objectCache.UnregisterTaskObject(key, lifetime);
}
#endregion
#region BuildEngine5 Members
/// <summary>
/// Logs a telemetry event for the current task.
/// </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)
{
lock (_callbackMonitor)
{
ErrorUtilities.VerifyThrowArgumentNull(eventName, nameof(eventName));
if (!_activeProxy)
{
// The task has been logging on another thread, typically
// because of logging a spawned process's output, and has
// not terminated this logging before it returned. This is common
// enough that we don't want to crash and break the entire build. But
// we don't have any good way to log it any more, as not only has this task
// finished, the whole build might have finished! The task author will
// just have to figure out that their task has a bug by themselves.
if (s_breakOnLogAfterTaskReturns)
{
Trace.Fail(String.Format(CultureInfo.CurrentUICulture, "Task at {0}, after already returning, attempted to log telemetry event '{1}'", _taskLocation.ToString(), eventName));
}
return;
}
_taskLoggingContext.LoggingService.LogTelemetry(_taskLoggingContext.BuildEventContext, eventName, properties);
}
}
#endregion
#region IBuildEngine6 Members
/// <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 _requestEntry.RequestConfiguration.GlobalProperties.ToDictionary();
}
#endregion
#region IBuildEngine7 Members
/// <summary>
/// Enables or disables emitting a default error when a task fails without logging errors
/// </summary>
public bool AllowFailureWithoutError { get; set; } = false;
#endregion
#region IBuildEngine8 Members
private ICollection<string> _warningsAsErrors;
/// <summary>
/// Contains all warnings that should be logged as errors.
/// Non-null empty set when all warnings should be treated as errors.
/// </summary>
private ICollection<string> WarningsAsErrors
{
get
{
// Test compatibility
if(_taskLoggingContext == null)
{
return null;
}
return _warningsAsErrors ??= _taskLoggingContext.GetWarningsAsErrors();
}
}
private ICollection<string> _warningsAsMessages;
/// <summary>
/// Contains all warnings that should be logged as errors.
/// Non-null empty set when all warnings should be treated as errors.
/// </summary>
private ICollection<string> WarningsAsMessages
{
get
{
// Test compatibility
if (_taskLoggingContext == null)
{
return null;
}
return _warningsAsMessages ??= _taskLoggingContext.GetWarningsAsMessages();
}
}
/// <summary>
/// Determines if the given warning should be treated as an error.
/// </summary>
/// <param name="warningCode"></param>
/// <returns>True if the warning should not be treated as a message and WarningsAsErrors is an empty set or contains the given warning code.</returns>
public bool ShouldTreatWarningAsError(string warningCode)
{
// Warnings as messages overrides warnings as errors.
if (WarningsAsErrors == null || WarningsAsMessages?.Contains(warningCode) == true)
{
return false;
}
// An empty set means all warnings are errors.
return WarningsAsErrors.Count == 0 || WarningsAsErrors.Contains(warningCode);
}
#endregion
#region IBuildEngine9 Members
/// <summary>
/// Additional cores granted to the task by the scheduler. Does not include the one implicit core automatically granted to all tasks.
/// </summary>
private int _additionalAcquiredCores = 0;
/// <summary>
/// True if the one implicit core has been allocated by <see cref="RequestCores"/>, false otherwise.
/// </summary>
private bool _isImplicitCoreUsed = false;
/// <summary>
/// Total number of cores granted to the task, including the one implicit core.
/// </summary>
private int TotalAcquiredCores => _additionalAcquiredCores + (_isImplicitCoreUsed ? 1 : 0);
/// <summary>
/// Allocates shared CPU resources. Called by a task when it's about to do potentially multi-threaded/multi-process work.
/// </summary>
/// <param name="requestedCores">The number of cores the task wants to use.</param>
/// <returns>The number of cores the task is allowed to use given the current state of the build. This number is always between
/// 1 and <paramref name="requestedCores"/>. If the task has allocated its one implicit core, this call may block, waiting for
/// at least one core to become available.</returns>
public int RequestCores(int requestedCores)
{
ErrorUtilities.VerifyThrowArgumentOutOfRange(requestedCores > 0, nameof(requestedCores));
lock (_callbackMonitor)
{
IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback;
int coresAcquired = 0;
bool allocatingImplicitCore = false;
if (_isImplicitCoreUsed)
{
coresAcquired = builderCallback.RequestCores(_callbackMonitor, requestedCores, waitForCores: true);
}
else
{
_isImplicitCoreUsed = true;
allocatingImplicitCore = true;
if (requestedCores > 1)
{
coresAcquired = builderCallback.RequestCores(_callbackMonitor, requestedCores - 1, waitForCores: false);
}
}
_additionalAcquiredCores += coresAcquired;
if (allocatingImplicitCore)
{
// Pad the result with the one implicit core if it was still available.
// This ensures that first call never blocks and always returns >= 1.
coresAcquired++;
}
Debug.Assert(coresAcquired >= 1);
if (LoggingContext.IsValid)
{
LoggingContext.LogComment(MessageImportance.Low, "TaskAcquiredCores", _taskLoggingContext.TaskName,
requestedCores, coresAcquired, TotalAcquiredCores);
}
return coresAcquired;
}
}
/// <summary>
/// Frees shared CPU resources. Called by a task when it's finished doing multi-threaded/multi-process work.
/// </summary>
/// <param name="coresToRelease">The number of cores the task wants to return. This number must be between 0 and the number of cores
/// granted and not yet released.</param>
public void ReleaseCores(int coresToRelease)
{
ErrorUtilities.VerifyThrowArgumentOutOfRange(coresToRelease > 0, nameof(coresToRelease));
lock (_callbackMonitor)
{
int coresBeingReleased = coresToRelease;
int previousTotalAcquiredCores = TotalAcquiredCores;
if (_isImplicitCoreUsed && coresBeingReleased > _additionalAcquiredCores)
{
// Release the implicit core last, i.e. only if we're asked to release everything.
coresBeingReleased -= 1;
_isImplicitCoreUsed = false;
}
coresBeingReleased = Math.Min(coresBeingReleased, _additionalAcquiredCores);
if (coresBeingReleased >= 1)
{
IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback;
builderCallback.ReleaseCores(coresBeingReleased);
_additionalAcquiredCores -= coresBeingReleased;
}
if (LoggingContext.IsValid)
{
if (TotalAcquiredCores == previousTotalAcquiredCores - coresToRelease)
{
LoggingContext.LogComment(MessageImportance.Low, "TaskReleasedCores", _taskLoggingContext.TaskName,
coresToRelease, TotalAcquiredCores);
}
else
{
LoggingContext.LogComment(MessageImportance.Low, "TaskReleasedCoresWarning", _taskLoggingContext.TaskName,
coresToRelease, previousTotalAcquiredCores, TotalAcquiredCores);
}
}
}
}
/// <summary>
/// Frees all CPU resources granted so far.
/// </summary>
internal void ReleaseAllCores()
{
int coresToRelease = TotalAcquiredCores;
if (coresToRelease > 0)
{
ReleaseCores(coresToRelease);
}
}
#endregion
/// <summary>
/// Called by the internal MSBuild task.
/// Does not take the lock because it is called by another request builder thread.
/// </summary>
public async Task<BuildEngineResult> InternalBuildProjects(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<String>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs, bool skipNonexistentTargets = false)
{
ErrorUtilities.VerifyThrowArgumentNull(projectFileNames, nameof(projectFileNames));
ErrorUtilities.VerifyThrowArgumentNull(globalProperties, nameof(globalProperties));
VerifyActiveProxy();
BuildEngineResult result;
if (projectFileNames.Length == 1 && projectFileNames[0] == null && globalProperties[0] == null && (undefineProperties == null || undefineProperties[0] == null) && toolsVersion[0] == null)
{
bool overallSuccess = true;
List<IDictionary<string, ITaskItem[]>> targetOutputsPerProject = null;
// This is really a legacy CallTarget invocation
ITargetResult[] results = await _targetBuilderCallback.LegacyCallTarget(targetNames, ContinueOnError, _taskLocation);
if (returnTargetOutputs)
{
targetOutputsPerProject = new List<IDictionary<string, ITaskItem[]>>(1);
targetOutputsPerProject.Add(new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase));
}
for (int i = 0; i < targetNames.Length; i++)
{
targetOutputsPerProject[0][targetNames[i]] = results[i].Items;
if (results[i].ResultCode == TargetResultCode.Failure)
{
overallSuccess = false;
}
}
result = new BuildEngineResult(overallSuccess, targetOutputsPerProject);
BuildRequestsSucceeded = overallSuccess;
}
else
{
// Post the request, then yield up the thread.
result = await BuildProjectFilesInParallelAsync(projectFileNames, targetNames, globalProperties, undefineProperties, toolsVersion, true /* ask that target outputs are returned in the buildengineresult */, skipNonexistentTargets);
}
return result;
}
#if FEATURE_APPDOMAIN
/// <inheritdoc />
/// <summary>
/// InitializeLifetimeService is called when the remote object is activated.
/// This method will determine how long the lifetime for the object will be.
/// </summary>
/// <returns>The lease object to control this object's lifetime.</returns>
public override object InitializeLifetimeService()
{
lock (_callbackMonitor)
{
VerifyActiveProxy();
// Each MarshalByRef object has a reference to the service which
// controls how long the remote object will stay around
ILease lease = (ILease)base.InitializeLifetimeService();
// Set how long a lease should be initially. Once a lease expires
// the remote object will be disconnected and it will be marked as being availiable
// for garbage collection
int initialLeaseTime = 1;
string initialLeaseTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYINITIALLEASETIME");
if (!String.IsNullOrEmpty(initialLeaseTimeFromEnvironment))
{
int leaseTimeFromEnvironment;
if (int.TryParse(initialLeaseTimeFromEnvironment, out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0)
{
initialLeaseTime = leaseTimeFromEnvironment;
}
}
lease.InitialLeaseTime = TimeSpan.FromMinutes(initialLeaseTime);
// Make a new client sponsor. A client sponsor is a class
// which will respond to a lease renewal request and will
// increase the lease time allowing the object to stay in memory
_sponsor = new ClientSponsor();
// When a new lease is requested lets make it last 1 minutes longer.
int leaseExtensionTime = 1;
string leaseExtensionTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYLEASEEXTENSIONTIME");
if (!String.IsNullOrEmpty(leaseExtensionTimeFromEnvironment))
{
int leaseExtensionFromEnvironment;
if (int.TryParse(leaseExtensionTimeFromEnvironment, out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0)
{
leaseExtensionTime = leaseExtensionFromEnvironment;
}
}
_sponsor.RenewalTime = TimeSpan.FromMinutes(leaseExtensionTime);
// Register the sponsor which will increase lease timeouts when the lease expires
lease.Register(_sponsor);
return lease;
}
}
#endif
/// <summary>
/// Indicates to the TaskHost that it is no longer needed.
/// Called by TaskBuilder when the task using the EngineProxy is done.
/// </summary>
internal void MarkAsInactive()
{
lock (_callbackMonitor)
{
VerifyActiveProxy();
_activeProxy = false;
ReleaseAllCores();
// Since the task has a pointer to this class it may store it in a static field. Null out
// internal data so the leak of this object doesn't lead to a major memory leak.
_host = null;
_requestEntry = null;
// Don't bother clearing the tiny task location
_taskLoggingContext = null;
_targetBuilderCallback = null;