-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathScheduler.cs
2839 lines (2495 loc) · 141 KB
/
Scheduler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Execution;
using Microsoft.Build.Experimental.ProjectCache;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.Debugging;
using BuildAbortedException = Microsoft.Build.Exceptions.BuildAbortedException;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using NodeLoggingContext = Microsoft.Build.BackEnd.Logging.NodeLoggingContext;
#nullable disable
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// The MSBuild Scheduler
/// </summary>
internal class Scheduler : IScheduler
{
/// <summary>
/// The invalid node id
/// </summary>
internal const int InvalidNodeId = -1;
/// <summary>
/// ID used to indicate that the results for a particular configuration may at one point
/// have resided on this node, but currently do not and will need to be transferred back
/// in order to be used.
/// </summary>
internal const int ResultsTransferredId = -2;
/// <summary>
/// The in-proc node id
/// </summary>
internal const int InProcNodeId = 1;
/// <summary>
/// The virtual node, used when a request is initially given to the scheduler.
/// </summary>
internal const int VirtualNode = 0;
/// <summary>
/// If MSBUILDCUSTOMSCHEDULER = CustomSchedulerForSQL, the default multiplier for the amount by which
/// the count of configurations on any one node can exceed the average configuration count is 1.1 --
/// + 10%.
/// </summary>
private const double DefaultCustomSchedulerForSQLConfigurationLimitMultiplier = 1.1;
#region Scheduler Data
/// <summary>
/// Content of the environment variable MSBUILDSCHEDULINGUNLIMITED
/// </summary>
private string _schedulingUnlimitedVariable;
/// <summary>
/// If MSBUILDSCHEDULINGUNLIMITED is set, this flag will make AtSchedulingLimit() always return false
/// </summary>
private bool _schedulingUnlimited;
/// <summary>
/// If MSBUILDNODELIMITOFFSET is set, this will add an offset to the limit used in AtSchedulingLimit()
/// </summary>
private int _nodeLimitOffset;
/// <summary>
/// The result of calling NativeMethodsShared.GetLogicalCoreCount() unless overriden with MSBUILDCORELIMIT.
/// </summary>
private int _coreLimit;
/// <summary>
/// The weight of busy nodes in GetAvailableCoresForExplicitRequests().
/// </summary>
private int _nodeCoreAllocationWeight;
/// <summary>
/// { nodeId -> NodeInfo }
/// A list of nodes we know about. For the non-distributed case, there will be no more nodes than the
/// maximum specified on the command-line.
/// </summary>
private Dictionary<int, NodeInfo> _availableNodes;
/// <summary>
/// The number of inproc nodes that can be created without hitting the
/// node limit.
/// </summary>
private int _currentInProcNodeCount = 0;
/// <summary>
/// The number of out-of-proc nodes that can be created without hitting the
/// node limit.
/// </summary>
private int _currentOutOfProcNodeCount = 0;
/// <summary>
/// The collection of all requests currently known to the system.
/// </summary>
private SchedulingData _schedulingData;
/// <summary>
/// A queue of RequestCores requests waiting for at least one core to become available.
/// </summary>
private Queue<TaskCompletionSource<int>> _pendingRequestCoresCallbacks;
#endregion
/// <summary>
/// The component host.
/// </summary>
private IBuildComponentHost _componentHost;
/// <summary>
/// The configuration cache.
/// </summary>
private IConfigCache _configCache;
/// <summary>
/// The results cache.
/// </summary>
private IResultsCache _resultsCache;
/// <summary>
/// The next ID to assign for a global request id.
/// </summary>
private int _nextGlobalRequestId;
/// <summary>
/// Flag indicating that we are supposed to dump the scheduler state to the disk periodically.
/// </summary>
private bool _debugDumpState;
/// <summary>
/// Flag used for debugging by forcing all scheduling to go out-of-proc.
/// </summary>
internal bool ForceAffinityOutOfProc
=> Traits.Instance.InProcNodeDisabled || _componentHost.BuildParameters.DisableInProcNode;
/// <summary>
/// The path into which debug files will be written.
/// </summary>
private string _debugDumpPath;
/// <summary>
/// If MSBUILDCUSTOMSCHEDULER = CustomSchedulerForSQL, the user may also choose to set
/// MSBUILDCUSTOMSCHEDULERFORSQLCONFIGURATIONLIMITMULTIPLIER to the value by which they want
/// the max configuration count for any one node to exceed the average configuration count.
/// If that env var is not set, or is set to an invalid value (negative, less than 1, non-numeric)
/// then we use the default value instead.
/// </summary>
private double _customSchedulerForSQLConfigurationLimitMultiplier;
/// <summary>
/// The plan.
/// </summary>
private SchedulingPlan _schedulingPlan;
/// <summary>
/// If MSBUILDCUSTOMSCHEDULER is set, contains the requested scheduling algorithm
/// </summary>
private AssignUnscheduledRequestsDelegate _customRequestSchedulingAlgorithm;
private NodeLoggingContext _inprocNodeContext;
private int _loggedWarningsForProxyBuildsOnOutOfProcNodes = 0;
/// <summary>
/// Constructor.
/// </summary>
public Scheduler()
{
// Be careful moving these to Traits, changing the timing of reading environment variables has a breaking potential.
_debugDumpState = Traits.Instance.DebugScheduler;
_debugDumpPath = DebugUtils.DebugPath;
_schedulingUnlimitedVariable = Environment.GetEnvironmentVariable("MSBUILDSCHEDULINGUNLIMITED");
_nodeLimitOffset = 0;
if (!String.IsNullOrEmpty(_schedulingUnlimitedVariable))
{
_schedulingUnlimited = true;
}
else
{
_schedulingUnlimited = false;
string strNodeLimitOffset = Environment.GetEnvironmentVariable("MSBUILDNODELIMITOFFSET");
if (!String.IsNullOrEmpty(strNodeLimitOffset))
{
_nodeLimitOffset = Int16.Parse(strNodeLimitOffset, CultureInfo.InvariantCulture);
if (_nodeLimitOffset < 0)
{
_nodeLimitOffset = 0;
}
}
}
// Resource management tuning knobs:
// 1) MSBUILDCORELIMIT is the maximum number of cores we hand out via IBuildEngine9.RequestCores.
// Note that it is independent of build parallelism as given by /m on the command line.
if (!int.TryParse(Environment.GetEnvironmentVariable("MSBUILDCORELIMIT"), out _coreLimit) || _coreLimit <= 0)
{
_coreLimit = NativeMethodsShared.GetLogicalCoreCount();
}
// 1) MSBUILDNODECOREALLOCATIONWEIGHT is the weight with which executing nodes reduce the number of available cores.
// Example: If the weight is 50, _coreLimit is 8, and there are 4 nodes that are busy executing build requests,
// then the number of cores available via IBuildEngine9.RequestCores is 8 - (0.5 * 4) = 6.
if (!int.TryParse(Environment.GetEnvironmentVariable("MSBUILDNODECOREALLOCATIONWEIGHT"), out _nodeCoreAllocationWeight)
|| _nodeCoreAllocationWeight <= 0
|| _nodeCoreAllocationWeight > 100)
{
_nodeCoreAllocationWeight = 0;
}
if (String.IsNullOrEmpty(_debugDumpPath))
{
_debugDumpPath = FileUtilities.TempFileDirectory;
}
Reset();
}
#region Delegates
/// <summary>
/// In the circumstance where we want to specify the scheduling algorithm via the secret environment variable
/// MSBUILDCUSTOMSCHEDULING, the scheduling algorithm used will be assigned to a delegate of this type.
/// </summary>
internal delegate void AssignUnscheduledRequestsDelegate(List<ScheduleResponse> responses, HashSet<int> idleNodes);
#endregion
#region IScheduler Members
/// <summary>
/// Retrieves the minimum configuration id which can be assigned that won't conflict with those in the scheduling plan.
/// </summary>
public int MinimumAssignableConfigurationId
{
get
{
if (_schedulingPlan == null)
{
return 1;
}
return _schedulingPlan.MaximumConfigurationId + 1;
}
}
/// <summary>
/// Returns true if the specified configuration is currently in the scheduler.
/// </summary>
/// <param name="configurationId">The configuration id</param>
/// <returns>True if the specified configuration is already building.</returns>
public bool IsCurrentlyBuildingConfiguration(int configurationId)
{
return _schedulingData.GetRequestsAssignedToConfigurationCount(configurationId) > 0;
}
/// <summary>
/// Gets a configuration id from the plan which matches the specified path.
/// </summary>
/// <param name="configPath">The path.</param>
/// <returns>The configuration id which has been assigned to this path.</returns>
public int GetConfigurationIdFromPlan(string configPath)
{
if (_schedulingPlan == null)
{
return BuildRequestConfiguration.InvalidConfigurationId;
}
return _schedulingPlan.GetConfigIdForPath(configPath);
}
/// <summary>
/// Retrieves the request executing on a node.
/// </summary>
public BuildRequest GetExecutingRequestByNode(int nodeId)
{
if (!_schedulingData.IsNodeWorking(nodeId))
{
return null;
}
SchedulableRequest request = _schedulingData.GetExecutingRequestByNode(nodeId);
return request.BuildRequest;
}
/// <summary>
/// Reports that the specified request has become blocked and cannot proceed.
/// </summary>
public IEnumerable<ScheduleResponse> ReportRequestBlocked(int nodeId, BuildRequestBlocker blocker)
{
_schedulingData.EventTime = DateTime.UtcNow;
List<ScheduleResponse> responses = new List<ScheduleResponse>();
// Get the parent, if any
SchedulableRequest parentRequest = null;
if (blocker.BlockedRequestId != BuildRequest.InvalidGlobalRequestId)
{
if (blocker.YieldAction == YieldAction.Reacquire)
{
parentRequest = _schedulingData.GetYieldingRequest(blocker.BlockedRequestId);
}
else
{
parentRequest = _schedulingData.GetExecutingRequest(blocker.BlockedRequestId);
}
}
try
{
// We are blocked either on new requests (top-level or MSBuild task) or on an in-progress request that is
// building a target we want to build.
if (blocker.YieldAction != YieldAction.None)
{
TraceScheduler("Request {0} on node {1} is performing yield action {2}.", blocker.BlockedRequestId, nodeId, blocker.YieldAction);
ErrorUtilities.VerifyThrow(string.IsNullOrEmpty(blocker.BlockingTarget), "Blocking target should be null because this is not a request blocking on a target");
HandleYieldAction(parentRequest, blocker);
}
else if ((blocker.BlockingRequestId == blocker.BlockedRequestId) && blocker.BlockingRequestId != BuildRequest.InvalidGlobalRequestId)
{
ErrorUtilities.VerifyThrow(string.IsNullOrEmpty(blocker.BlockingTarget), "Blocking target should be null because this is not a request blocking on a target");
// We are blocked waiting for a transfer of results.
HandleRequestBlockedOnResultsTransfer(parentRequest, responses);
}
else if (blocker.BlockingRequestId != BuildRequest.InvalidGlobalRequestId)
{
// We are blocked by a request executing a target for which we need results.
try
{
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(blocker.BlockingTarget), "Blocking target should exist");
HandleRequestBlockedOnInProgressTarget(parentRequest, blocker);
}
catch (SchedulerCircularDependencyException ex)
{
TraceScheduler("Circular dependency caused by request {0}({1}) (nr {2}), parent {3}({4}) (nr {5})", ex.Request.GlobalRequestId, ex.Request.ConfigurationId, ex.Request.NodeRequestId, parentRequest.BuildRequest.GlobalRequestId, parentRequest.BuildRequest.ConfigurationId, parentRequest.BuildRequest.NodeRequestId);
responses.Add(ScheduleResponse.CreateCircularDependencyResponse(nodeId, parentRequest.BuildRequest, ex.Request));
}
}
else
{
ErrorUtilities.VerifyThrow(string.IsNullOrEmpty(blocker.BlockingTarget), "Blocking target should be null because this is not a request blocking on a target");
// We are blocked by new requests, either top-level or MSBuild task.
HandleRequestBlockedByNewRequests(parentRequest, blocker, responses);
}
}
catch (SchedulerCircularDependencyException ex)
{
TraceScheduler("Circular dependency caused by request {0}({1}) (nr {2}), parent {3}({4}) (nr {5})", ex.Request.GlobalRequestId, ex.Request.ConfigurationId, ex.Request.NodeRequestId, parentRequest.BuildRequest.GlobalRequestId, parentRequest.BuildRequest.ConfigurationId, parentRequest.BuildRequest.NodeRequestId);
responses.Add(ScheduleResponse.CreateCircularDependencyResponse(nodeId, parentRequest.BuildRequest, ex.Request));
}
// Now see if we can schedule requests somewhere since we
// a) have a new request; and
// b) have a node which is now waiting and not doing anything.
ScheduleUnassignedRequests(responses);
return responses;
}
/// <summary>
/// Informs the scheduler of a specific result.
/// </summary>
public IEnumerable<ScheduleResponse> ReportResult(int nodeId, BuildResult result)
{
_schedulingData.EventTime = DateTime.UtcNow;
List<ScheduleResponse> responses = new List<ScheduleResponse>();
TraceScheduler("Reporting result from node {0} for request {1}, parent {2}.", nodeId, result.GlobalRequestId, result.ParentGlobalRequestId);
RecordResultToCurrentCacheIfConfigNotInOverrideCache(result);
if (result.NodeRequestId == BuildRequest.ResultsTransferNodeRequestId)
{
// We are transferring results. The node to which they should be sent has already been recorded by the
// HandleRequestBlockedOnResultsTransfer method in the configuration.
BuildRequestConfiguration config = _configCache[result.ConfigurationId];
ScheduleResponse response = ScheduleResponse.CreateReportResultResponse(config.ResultsNodeId, result);
responses.Add(response);
}
else
{
// Tell the request to which this result belongs than it is done.
SchedulableRequest request = _schedulingData.GetExecutingRequest(result.GlobalRequestId);
request.Complete(result);
// Report results to our parent, or report submission complete as necessary.
if (request.Parent != null)
{
// responses.Add(new ScheduleResponse(request.Parent.AssignedNode, new BuildRequestUnblocker(request.Parent.BuildRequest.GlobalRequestId, result)));
ErrorUtilities.VerifyThrow(result.ParentGlobalRequestId == request.Parent.BuildRequest.GlobalRequestId, "Result's parent doesn't match request's parent.");
// When adding the result to the cache we merge the result with what ever is already in the cache this may cause
// the result to have more target outputs in it than was was requested. To fix this we can ask the cache itself for the result we just added.
// When results are returned from the cache we filter them based on the targets we requested. This causes our result to only
// include the targets we requested rather than the merged result.
// Note: In this case we do not need to log that we got the results from the cache because we are only using the cache
// for filtering the targets for the result instead rather than using the cache as the location where this result came from.
ScheduleResponse response = TrySatisfyRequestFromCache(request.Parent.AssignedNode, request.BuildRequest, skippedResultsDoNotCauseCacheMiss: _componentHost.BuildParameters.SkippedResultsDoNotCauseCacheMiss());
// response may be null if the result was never added to the cache. This can happen if the result has an exception in it
// or the results could not be satisfied because the initial or default targets have been skipped. If that is the case
// we need to report the result directly since it contains an exception
if (response == null)
{
response = ScheduleResponse.CreateReportResultResponse(request.Parent.AssignedNode, result.Clone());
}
responses.Add(response);
}
else
{
// This was root request, we can report submission complete.
// responses.Add(new ScheduleResponse(result));
responses.Add(ScheduleResponse.CreateSubmissionCompleteResponse(result));
if (result.OverallResult != BuildResultCode.Failure)
{
WriteSchedulingPlan(result.SubmissionId);
}
}
// This result may apply to a number of other unscheduled requests which are blocking active requests. Report to them as well.
List<SchedulableRequest> unscheduledRequests = new List<SchedulableRequest>(_schedulingData.UnscheduledRequests);
foreach (SchedulableRequest unscheduledRequest in unscheduledRequests)
{
if (unscheduledRequest.BuildRequest.GlobalRequestId == result.GlobalRequestId)
{
TraceScheduler("Request {0} (node request {1}) also satisfied by result.", unscheduledRequest.BuildRequest.GlobalRequestId, unscheduledRequest.BuildRequest.NodeRequestId);
BuildResult newResult = new BuildResult(unscheduledRequest.BuildRequest, result, null);
// Report results to the parent.
int parentNode = (unscheduledRequest.Parent == null) ? InvalidNodeId : unscheduledRequest.Parent.AssignedNode;
// There are other requests which we can satisfy based on this result, lets pull the result out of the cache
// and satisfy those requests. Normally a skipped result would lead to the cache refusing to satisfy the
// request, because the correct response in that case would be to attempt to rebuild the target in case there
// are state changes that would cause it to now excute. At this point, however, we already know that the parent
// request has completed, and we already know that this request has the same global request ID, which means that
// its configuration and set of targets are identical -- from MSBuild's perspective, it's the same. So since
// we're not going to attempt to re-execute it, if there are skipped targets in the result, that's fine. We just
// need to know what the target results are so that we can log them.
ScheduleResponse response = TrySatisfyRequestFromCache(parentNode, unscheduledRequest.BuildRequest, skippedResultsDoNotCauseCacheMiss: true);
// If we have a response we need to tell the loggers that we satisified that request from the cache.
if (response != null)
{
LogRequestHandledFromCache(unscheduledRequest.BuildRequest, response.BuildResult);
}
else
{
// Response may be null if the result was never added to the cache. This can happen if the result has
// an exception in it. If that is the case, we should report the result directly so that the
// build manager knows that it needs to shut down logging manually.
response = GetResponseForResult(parentNode, unscheduledRequest.BuildRequest, newResult.Clone());
}
responses.Add(response);
// Mark the request as complete (and the parent is no longer blocked by this request.)
unscheduledRequest.Complete(newResult);
}
}
}
// This node may now be free, so run the scheduler.
ScheduleUnassignedRequests(responses);
return responses;
}
/// <summary>
/// Signals that a node has been created.
/// </summary>
/// <param name="nodeInfos">Information about the nodes which were created.</param>
/// <returns>A new set of scheduling actions to take.</returns>
public IEnumerable<ScheduleResponse> ReportNodesCreated(IEnumerable<NodeInfo> nodeInfos)
{
_schedulingData.EventTime = DateTime.UtcNow;
foreach (NodeInfo nodeInfo in nodeInfos)
{
_availableNodes[nodeInfo.NodeId] = nodeInfo;
TraceScheduler("Node {0} created", nodeInfo.NodeId);
switch (nodeInfo.ProviderType)
{
case NodeProviderType.InProc:
_currentInProcNodeCount++;
break;
case NodeProviderType.OutOfProc:
_currentOutOfProcNodeCount++;
break;
case NodeProviderType.Remote:
default:
// this should never happen in the current MSBuild.
ErrorUtilities.ThrowInternalErrorUnreachable();
break;
}
}
List<ScheduleResponse> responses = new List<ScheduleResponse>();
ScheduleUnassignedRequests(responses);
return responses;
}
/// <summary>
/// Signals that the build has been aborted by the specified node.
/// </summary>
/// <param name="nodeId">The node which reported the failure.</param>
public void ReportBuildAborted(int nodeId)
{
_schedulingData.EventTime = DateTime.UtcNow;
// Get the list of build requests currently assigned to the node and report aborted results for them.
TraceScheduler("Build aborted by node {0}", nodeId);
foreach (SchedulableRequest request in _schedulingData.GetScheduledRequestsByNode(nodeId))
{
MarkRequestAborted(request);
}
}
/// <summary>
/// Resets the scheduler.
/// </summary>
public void Reset()
{
DumpConfigurations();
DumpRequests();
_schedulingPlan = null;
_schedulingData = new SchedulingData();
_availableNodes = new Dictionary<int, NodeInfo>(8);
_pendingRequestCoresCallbacks = new Queue<TaskCompletionSource<int>>();
_currentInProcNodeCount = 0;
_currentOutOfProcNodeCount = 0;
_nextGlobalRequestId = 0;
_customRequestSchedulingAlgorithm = null;
}
/// <summary>
/// Writes out the detailed summary of the build.
/// </summary>
/// <param name="submissionId">The id of the submission which is at the root of the build.</param>
public void WriteDetailedSummary(int submissionId)
{
ILoggingService loggingService = _componentHost.LoggingService;
BuildEventContext context = new BuildEventContext(submissionId, 0, 0, 0, 0, 0);
loggingService.LogComment(context, MessageImportance.Normal, "DetailedSummaryHeader");
foreach (SchedulableRequest request in _schedulingData.GetRequestsByHierarchy(null))
{
if (request.BuildRequest.SubmissionId == submissionId)
{
loggingService.LogComment(context, MessageImportance.Normal, "BuildHierarchyHeader");
WriteRecursiveSummary(loggingService, context, submissionId, request, 0, false /* useConfigurations */, true /* isLastChild */);
}
}
WriteNodeUtilizationGraph(loggingService, context, false /* useConfigurations */);
}
/// <summary>
/// Requests CPU resources.
/// </summary>
public Task<int> RequestCores(int requestId, int requestedCores, bool waitForCores)
{
if (requestedCores == 0)
{
return Task.FromResult(0);
}
Func<int, int> grantCores = (availableCores) =>
{
int grantedCores = Math.Min(requestedCores, availableCores);
if (grantedCores > 0)
{
_schedulingData.GrantCoresToRequest(requestId, grantedCores);
}
return grantedCores;
};
int grantedCores = grantCores(GetAvailableCoresForExplicitRequests());
if (grantedCores > 0 || !waitForCores)
{
return Task.FromResult(grantedCores);
}
else
{
// We have no cores to grant at the moment, queue up the request.
TaskCompletionSource<int> completionSource = new TaskCompletionSource<int>();
_pendingRequestCoresCallbacks.Enqueue(completionSource);
return completionSource.Task.ContinueWith((task) => grantCores(task.Result), TaskContinuationOptions.ExecuteSynchronously);
}
}
/// <summary>
/// Returns CPU resources.
/// </summary>
public List<ScheduleResponse> ReleaseCores(int requestId, int coresToRelease)
{
_schedulingData.RemoveCoresFromRequest(requestId, coresToRelease);
// Releasing cores means that we may be able to schedule more work.
List<ScheduleResponse> responses = new List<ScheduleResponse>();
ScheduleUnassignedRequests(responses);
return responses;
}
#endregion
#region IBuildComponent Members
/// <summary>
/// Initializes the component with the specified component host.
/// </summary>
/// <param name="host">The component host.</param>
public void InitializeComponent(IBuildComponentHost host)
{
_componentHost = host;
_resultsCache = (IResultsCache)_componentHost.GetComponent(BuildComponentType.ResultsCache);
_configCache = (IConfigCache)_componentHost.GetComponent(BuildComponentType.ConfigCache);
_inprocNodeContext = new NodeLoggingContext(_componentHost.LoggingService, InProcNodeId, true);
}
/// <summary>
/// Shuts down the component.
/// </summary>
public void ShutdownComponent()
{
Reset();
}
#endregion
/// <summary>
/// Factory for component construction.
/// </summary>
internal static IBuildComponent CreateComponent(BuildComponentType componentType)
{
ErrorUtilities.VerifyThrow(componentType == BuildComponentType.Scheduler, "Cannot create components of type {0}", componentType);
return new Scheduler();
}
/// <summary>
/// Updates the state of a request based on its desire to yield or reacquire control of its node.
/// </summary>
private void HandleYieldAction(SchedulableRequest parentRequest, BuildRequestBlocker blocker)
{
if (blocker.YieldAction == YieldAction.Yield)
{
// Mark the request blocked.
parentRequest.Yield(blocker.TargetsInProgress);
}
else
{
// Mark the request ready.
parentRequest.Reacquire();
}
}
/// <summary>
/// Attempts to schedule unassigned requests to free nodes.
/// </summary>
/// <param name="responses">The list which should be populated with responses from the scheduling.</param>
private void ScheduleUnassignedRequests(List<ScheduleResponse> responses)
{
DateTime schedulingTime = DateTime.UtcNow;
// See if we are done. We are done if there are no unassigned requests and no requests assigned to nodes.
if (_schedulingData.UnscheduledRequestsCount == 0 &&
_schedulingData.ReadyRequestsCount == 0 &&
_schedulingData.BlockedRequestsCount == 0)
{
if (_schedulingData.ExecutingRequestsCount == 0 && _schedulingData.YieldingRequestsCount == 0)
{
// We are done.
TraceScheduler("Build complete");
}
else
{
// Nodes still have work, but we have no requests. Let them proceed and only handle resource requests.
HandlePendingResourceRequests();
TraceScheduler("{0}: Waiting for existing work to proceed.", schedulingTime);
}
return;
}
// Resume any work available which has already been assigned to specific nodes.
ResumeRequiredWork(responses);
HashSet<int> idleNodes = new HashSet<int>();
foreach (int availableNodeId in _availableNodes.Keys)
{
if (!_schedulingData.IsNodeWorking(availableNodeId))
{
idleNodes.Add(availableNodeId);
}
}
int nodesFreeToDoWorkPriorToScheduling = idleNodes.Count;
// Assign requests to any nodes which are currently idle.
if (idleNodes.Count > 0 && _schedulingData.UnscheduledRequestsCount > 0)
{
AssignUnscheduledRequestsToNodes(responses, idleNodes);
}
// If we have no nodes free to do work, we might need more nodes. This will occur if:
// 1) We still have unscheduled requests, because an additional node might allow us to execute those in parallel, or
// 2) We didn't schedule anything because there were no nodes to schedule to
bool createNodePending = false;
if (_schedulingData.UnscheduledRequestsCount > 0 || responses.Count == 0)
{
createNodePending = CreateNewNodeIfPossible(responses, _schedulingData.UnscheduledRequests);
}
if (_availableNodes.Count > 0)
{
// If we failed to schedule any requests, report any results or create any nodes, we might be done.
if (_schedulingData.ExecutingRequestsCount > 0 || _schedulingData.YieldingRequestsCount > 0)
{
// We are still doing work.
}
else if (_schedulingData.UnscheduledRequestsCount == 0 &&
_schedulingData.ReadyRequestsCount == 0 &&
_schedulingData.BlockedRequestsCount == 0)
{
// We've exhausted our supply of work.
TraceScheduler("Build complete");
}
else if (_schedulingData.BlockedRequestsCount != 0)
{
// It is legitimate to have blocked requests with none executing if none of the requests can
// be serviced by any currently existing node, or if they are blocked by requests, none of
// which can be serviced by any currently existing node. However, in that case, we had better
// be requesting the creation of a node that can service them.
//
// Note: This is O(# nodes * closure of requests blocking current set of blocked requests),
// but all three numbers should usually be fairly small and, more importantly, this situation
// should occur at most once per build, since it requires a situation where all blocked requests
// are blocked on the creation of a node that can service them.
foreach (SchedulableRequest request in _schedulingData.BlockedRequests)
{
if (RequestOrAnyItIsBlockedByCanBeServiced(request))
{
DumpSchedulerState();
ErrorUtilities.ThrowInternalError("Somehow no requests are currently executing, and at least one of the {0} requests blocked by in-progress requests is servicable by a currently existing node, but no circular dependency was detected ...", _schedulingData.BlockedRequestsCount);
}
}
if (!createNodePending)
{
DumpSchedulerState();
ErrorUtilities.ThrowInternalError("None of the {0} blocked requests can be serviced by currently existing nodes, but we aren't requesting a new one.", _schedulingData.BlockedRequestsCount);
}
}
else if (_schedulingData.ReadyRequestsCount != 0)
{
DumpSchedulerState();
ErrorUtilities.ThrowInternalError("Somehow we have {0} requests which are ready to go but we didn't tell the nodes to continue.", _schedulingData.ReadyRequestsCount);
}
else if (_schedulingData.UnscheduledRequestsCount != 0 && !createNodePending)
{
DumpSchedulerState();
ErrorUtilities.ThrowInternalError("Somehow we have {0} unassigned build requests but {1} of our nodes are free and we aren't requesting a new one...", _schedulingData.UnscheduledRequestsCount, idleNodes.Count);
}
}
else
{
ErrorUtilities.VerifyThrow(responses.Count > 0, "We failed to request a node to be created.");
}
TraceScheduler("Requests scheduled: {0} Unassigned Requests: {1} Blocked Requests: {2} Unblockable Requests: {3} Free Nodes: {4}/{5} Responses: {6}", nodesFreeToDoWorkPriorToScheduling - idleNodes.Count, _schedulingData.UnscheduledRequestsCount, _schedulingData.BlockedRequestsCount, _schedulingData.ReadyRequestsCount, idleNodes.Count, _availableNodes.Count, responses.Count);
DumpSchedulerState();
}
/// <summary>
/// Determines which requests to assign to available nodes.
/// </summary>
/// <remarks>
/// This is where all the real scheduling decisions take place. It should not be necessary to edit functions outside of this
/// to alter how scheduling occurs.
/// </remarks>
private void AssignUnscheduledRequestsToNodes(List<ScheduleResponse> responses, HashSet<int> idleNodes)
{
if (_componentHost.BuildParameters.MaxNodeCount == 1)
{
// In the single-proc case, there are no decisions to be made. First-come, first-serve.
AssignUnscheduledRequestsFIFO(responses, idleNodes);
}
else
{
bool haveValidPlan = GetSchedulingPlanAndAlgorithm();
if (_customRequestSchedulingAlgorithm != null)
{
_customRequestSchedulingAlgorithm(responses, idleNodes);
}
else
{
// We want to find more work first, and we assign traversals to the in-proc node first, if possible.
AssignUnscheduledRequestsByTraversalsFirst(responses, idleNodes);
AssignUnscheduledProxyBuildRequestsToInProcNode(responses, idleNodes);
if (idleNodes.Count == 0)
{
return;
}
if (haveValidPlan)
{
if (_componentHost.BuildParameters.MaxNodeCount == 2)
{
AssignUnscheduledRequestsWithPlanByMostImmediateReferences(responses, idleNodes);
}
else
{
AssignUnscheduledRequestsWithPlanByGreatestPlanTime(responses, idleNodes);
}
}
else
{
AssignUnscheduledRequestsWithConfigurationCountLevelling(responses, idleNodes);
}
}
}
}
/// <summary>
/// Reads in the scheduling plan if one exists and has not previously been read; returns true if the scheduling plan
/// both exists and is valid, or false otherwise.
/// </summary>
private bool GetSchedulingPlanAndAlgorithm()
{
// Read the plan, if any.
if (_schedulingPlan == null)
{
_schedulingPlan = new SchedulingPlan(_configCache, _schedulingData);
ReadSchedulingPlan(_schedulingData.GetRequestsByHierarchy(null).First().BuildRequest.SubmissionId);
}
if (_customRequestSchedulingAlgorithm == null)
{
string customScheduler = Environment.GetEnvironmentVariable("MSBUILDCUSTOMSCHEDULER");
if (!String.IsNullOrEmpty(customScheduler))
{
// Assign to the delegate
if (customScheduler.Equals("WithPlanByMostImmediateReferences", StringComparison.OrdinalIgnoreCase) && _schedulingPlan.IsPlanValid)
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithPlanByMostImmediateReferences;
}
else if (customScheduler.Equals("WithPlanByGreatestPlanTime", StringComparison.OrdinalIgnoreCase) && _schedulingPlan.IsPlanValid)
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithPlanByGreatestPlanTime;
}
else if (customScheduler.Equals("ByTraversalsFirst", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsByTraversalsFirst;
}
else if (customScheduler.Equals("WithConfigurationCountLevelling", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithConfigurationCountLevelling;
}
else if (customScheduler.Equals("WithSmallestFileSize", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithSmallestFileSize;
}
else if (customScheduler.Equals("WithLargestFileSize", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithLargestFileSize;
}
else if (customScheduler.Equals("WithMaxWaitingRequests", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithMaxWaitingRequests;
}
else if (customScheduler.Equals("WithMaxWaitingRequests2", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsWithMaxWaitingRequests2;
}
else if (customScheduler.Equals("FIFO", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsFIFO;
}
else if (customScheduler.Equals("CustomSchedulerForSQL", StringComparison.OrdinalIgnoreCase))
{
_customRequestSchedulingAlgorithm = AssignUnscheduledRequestsUsingCustomSchedulerForSQL;
string multiplier = Environment.GetEnvironmentVariable("MSBUILDCUSTOMSCHEDULERFORSQLCONFIGURATIONLIMITMULTIPLIER");
double convertedMultiplier = 0;
if (!Double.TryParse(multiplier, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture.NumberFormat, out convertedMultiplier) || convertedMultiplier < 1)
{
_customSchedulerForSQLConfigurationLimitMultiplier = DefaultCustomSchedulerForSQLConfigurationLimitMultiplier;
}
else
{
_customSchedulerForSQLConfigurationLimitMultiplier = convertedMultiplier;
}
}
}
}
return _schedulingPlan.IsPlanValid;
}
/// <summary>
/// Assigns requests to nodes based on those which refer to the most other projects.
/// </summary>
private void AssignUnscheduledRequestsWithPlanByMostImmediateReferences(List<ScheduleResponse> responses, HashSet<int> idleNodes)
{
AssignUnscheduledRequestsWithPlan(responses, idleNodes, (plan1, plan2) => plan1.ReferencesCount < plan2.ReferencesCount);
}
/// <summary>
/// Assigns requests to nodes based on those which have the most plan time.
/// </summary>
private void AssignUnscheduledRequestsWithPlanByGreatestPlanTime(List<ScheduleResponse> responses, HashSet<int> idleNodes)
{
AssignUnscheduledRequestsWithPlan(responses, idleNodes, (plan1, plan2) => plan1.TotalPlanTime < plan2.TotalPlanTime);
}
private void AssignUnscheduledRequestsWithPlan(List<ScheduleResponse> responses, HashSet<int> idleNodes, Func<SchedulingPlan.PlanConfigData, SchedulingPlan.PlanConfigData, bool> comparisonFunction)
{
foreach (int idleNodeId in idleNodes)
{
SchedulingPlan.PlanConfigData bestConfig = null;
SchedulableRequest bestRequest = null;
// Find the most expensive request in the plan to schedule from among the ones available.
foreach (SchedulableRequest request in _schedulingData.UnscheduledRequestsWhichCanBeScheduled)
{
if (CanScheduleRequestToNode(request, idleNodeId))
{
SchedulingPlan.PlanConfigData configToConsider = _schedulingPlan.GetConfiguration(request.BuildRequest.ConfigurationId);
if (configToConsider is null)
{
if (bestConfig is null)
{
// By default we assume configs we don't know about aren't as important, and will only schedule them
// if nothing else is suitable
bestRequest ??= request;
}
}
else
{
if (bestConfig is null || comparisonFunction(bestConfig, configToConsider))
{
bestConfig = configToConsider;
bestRequest = request;
}
}
}
}
if (bestRequest is not null)
{
AssignUnscheduledRequestToNode(bestRequest, idleNodeId, responses);
}
}
}
/// <summary>
/// Assigns requests preferring those which are traversal projects as determined by filename.
/// </summary>
private void AssignUnscheduledRequestsByTraversalsFirst(List<ScheduleResponse> responses, HashSet<int> idleNodes)
{
AssignUnscheduledRequestsToInProcNode(responses, idleNodes, request => IsTraversalRequest(request.BuildRequest));
}
/// <summary>
/// Proxy build requests <see cref="ProxyTargets"/> should be really cheap (only return properties and items) and it's not worth
/// paying the IPC cost and re-evaluating them on out of proc nodes (they are guaranteed to be evaluated in the Scheduler process).
/// </summary>
private void AssignUnscheduledProxyBuildRequestsToInProcNode(List<ScheduleResponse> responses, HashSet<int> idleNodes)
{
AssignUnscheduledRequestsToInProcNode(responses, idleNodes, request => request.IsProxyBuildRequest());
}
private void AssignUnscheduledRequestsToInProcNode(List<ScheduleResponse> responses, HashSet<int> idleNodes, Func<SchedulableRequest, bool> shouldBeScheduled)
{
if (idleNodes.Contains(InProcNodeId))
{
List<SchedulableRequest> unscheduledRequests = new List<SchedulableRequest>(_schedulingData.UnscheduledRequestsWhichCanBeScheduled);
foreach (SchedulableRequest request in unscheduledRequests)
{
if (CanScheduleRequestToNode(request, InProcNodeId) && shouldBeScheduled(request))
{
AssignUnscheduledRequestToNode(request, InProcNodeId, responses);
idleNodes.Remove(InProcNodeId);