/
TaskSetManagerSuite.scala
2255 lines (1986 loc) · 95.9 KB
/
TaskSetManagerSuite.scala
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 Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.scheduler
import java.util.{Properties, Random}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._
import org.apache.hadoop.fs.FileAlreadyExistsException
import org.mockito.ArgumentMatchers.{any, anyBoolean, anyInt, anyString}
import org.mockito.Mockito._
import org.mockito.invocation.InvocationOnMock
import org.scalatest.Assertions._
import org.scalatest.PrivateMethodTester
import org.scalatest.concurrent.Eventually
import org.apache.spark.{FakeSchedulerBackend => _, _}
import org.apache.spark.internal.Logging
import org.apache.spark.internal.config
import org.apache.spark.internal.config.Tests.SKIP_VALIDATE_CORES_TESTING
import org.apache.spark.resource.{ResourceInformation, ResourceProfile}
import org.apache.spark.resource.ResourceUtils._
import org.apache.spark.resource.TestResourceIDs._
import org.apache.spark.scheduler.cluster.CoarseGrainedSchedulerBackend
import org.apache.spark.serializer.SerializerInstance
import org.apache.spark.storage.BlockManagerId
import org.apache.spark.util.{AccumulatorV2, Clock, ManualClock, SystemClock}
class FakeDAGScheduler(sc: SparkContext, taskScheduler: FakeTaskScheduler)
extends DAGScheduler(sc) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo): Unit = {
taskScheduler.startedTasks += taskInfo.index
}
override def taskEnded(
task: Task[_],
reason: TaskEndReason,
result: Any,
accumUpdates: Seq[AccumulatorV2[_, _]],
metricPeaks: Array[Long],
taskInfo: TaskInfo): Unit = {
taskScheduler.endedTasks(taskInfo.index) = reason
}
override def executorAdded(execId: String, host: String): Unit = {}
override def executorLost(execId: String, reason: ExecutorLossReason): Unit = {}
override def taskSetFailed(
taskSet: TaskSet,
reason: String,
exception: Option[Throwable]): Unit = {
taskScheduler.taskSetsFailed += taskSet.id
}
override def speculativeTaskSubmitted(task: Task[_]): Unit = {
taskScheduler.speculativeTasks += task.partitionId
}
}
// Get the rack for a given host
object FakeRackUtil {
private val hostToRack = new mutable.HashMap[String, String]()
var numBatchInvocation = 0
var numSingleHostInvocation = 0
def cleanUp(): Unit = {
hostToRack.clear()
numBatchInvocation = 0
numSingleHostInvocation = 0
}
def assignHostToRack(host: String, rack: String): Unit = {
hostToRack(host) = rack
}
def getRacksForHosts(hosts: Seq[String]): Seq[Option[String]] = {
assert(hosts.toSet.size == hosts.size) // no dups in hosts
if (hosts.nonEmpty && hosts.length != 1) {
numBatchInvocation += 1
} else if (hosts.length == 1) {
numSingleHostInvocation += 1
}
hosts.map(hostToRack.get(_))
}
}
/**
* A mock TaskSchedulerImpl implementation that just remembers information about tasks started and
* feedback received from the TaskSetManagers. Note that it's important to initialize this with
* a list of "live" executors and their hostnames for isExecutorAlive and hasExecutorsAliveOnHost
* to work, and these are required for locality in TaskSetManager.
*/
class FakeTaskScheduler(
sc: SparkContext,
clock: Clock,
liveExecutors: (String, String)* /* execId, host */)
extends TaskSchedulerImpl(sc, sc.conf.get(config.TASK_MAX_FAILURES), clock = clock)
{
val startedTasks = new ArrayBuffer[Long]
val endedTasks = new mutable.HashMap[Long, TaskEndReason]
val finishedManagers = new ArrayBuffer[TaskSetManager]
val taskSetsFailed = new ArrayBuffer[String]
val speculativeTasks = new ArrayBuffer[Int]
val executors = new mutable.HashMap[String, String]
def this(sc: SparkContext, liveExecutors: (String, String)*) = {
this(sc, new SystemClock, liveExecutors: _*)
}
// this must be initialized before addExecutor
override val defaultRackValue: Option[String] = Some("default")
for ((execId, host) <- liveExecutors) {
addExecutor(execId, host)
}
for ((execId, host) <- liveExecutors; rack <- getRackForHost(host)) {
hostsByRack.getOrElseUpdate(rack, new mutable.HashSet[String]()) += host
}
dagScheduler = new FakeDAGScheduler(sc, this)
def removeExecutor(execId: String): Unit = {
executors -= execId
val host = executorIdToHost.get(execId)
assert(host.isDefined)
val hostId = host.get
val executorsOnHost = hostToExecutors(hostId)
executorsOnHost -= execId
for (rack <- getRackForHost(hostId); hosts <- hostsByRack.get(rack)) {
hosts -= hostId
if (hosts.isEmpty) {
hostsByRack -= rack
}
}
}
override def taskSetFinished(manager: TaskSetManager): Unit = finishedManagers += manager
override def isExecutorAlive(execId: String): Boolean =
executors.contains(execId) && !isExecutorDecommissioned(execId)
override def hasExecutorsAliveOnHost(host: String): Boolean =
!isHostDecommissioned(host) && executors
.exists { case (e, h) => h == host && !isExecutorDecommissioned(e) }
def addExecutor(execId: String, host: String): Unit = {
executors.put(execId, host)
val executorsOnHost = hostToExecutors.getOrElseUpdate(host, new mutable.HashSet[String])
executorsOnHost += execId
executorIdToHost += execId -> host
for (rack <- getRackForHost(host)) {
hostsByRack.getOrElseUpdate(rack, new mutable.HashSet[String]()) += host
}
}
override def getRacksForHosts(hosts: Seq[String]): Seq[Option[String]] = {
FakeRackUtil.getRacksForHosts(hosts)
}
}
/**
* A Task implementation that results in a large serialized task.
*/
class LargeTask(stageId: Int) extends Task[Array[Byte]](stageId, 0, 0) {
val randomBuffer = new Array[Byte](TaskSetManager.TASK_SIZE_TO_WARN_KIB * 1024)
val random = new Random(0)
random.nextBytes(randomBuffer)
override def runTask(context: TaskContext): Array[Byte] = randomBuffer
override def preferredLocations: Seq[TaskLocation] = Seq[TaskLocation]()
}
class TaskSetManagerSuite
extends SparkFunSuite
with LocalSparkContext
with PrivateMethodTester
with Eventually
with Logging {
import TaskLocality.{ANY, PROCESS_LOCAL, NO_PREF, NODE_LOCAL, RACK_LOCAL}
private val conf = new SparkConf
val LOCALITY_WAIT_MS = conf.get(config.LOCALITY_WAIT)
val MAX_TASK_FAILURES = 4
var sched: FakeTaskScheduler = null
override def beforeEach(): Unit = {
super.beforeEach()
FakeRackUtil.cleanUp()
sched = null
}
override def afterEach(): Unit = {
if (sched != null) {
sched.dagScheduler.stop()
sched.stop()
sched = null
}
super.afterEach()
}
test("TaskSet with no preferences") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
val accumUpdates = taskSet.tasks.head.metrics.internalAccums
// Offer a host with NO_PREF as the constraint,
// we should get a nopref task immediately since that's what we only have
val taskOption = manager.resourceOffer("exec1", "host1", NO_PREF)._1
assert(taskOption.isDefined)
clock.advance(1)
// Tell it the task has finished
manager.handleSuccessfulTask(0, createTaskResult(0, accumUpdates))
assert(sched.endedTasks(0) === Success)
assert(sched.finishedManagers.contains(manager))
}
test("multiple offers with no preferences") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(3)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
val accumUpdatesByTask: Array[Seq[AccumulatorV2[_, _]]] = taskSet.tasks.map { task =>
task.metrics.internalAccums
}
// First three offers should all find tasks
for (i <- 0 until 3) {
val taskOption = manager.resourceOffer("exec1", "host1", NO_PREF)._1
assert(taskOption.isDefined)
val task = taskOption.get
assert(task.executorId === "exec1")
}
assert(sched.startedTasks.toSet === Set(0, 1, 2))
// Re-offer the host -- now we should get no more tasks
assert(manager.resourceOffer("exec1", "host1", NO_PREF)._1 === None)
// Finish the first two tasks
manager.handleSuccessfulTask(0, createTaskResult(0, accumUpdatesByTask(0)))
manager.handleSuccessfulTask(1, createTaskResult(1, accumUpdatesByTask(1)))
assert(sched.endedTasks(0) === Success)
assert(sched.endedTasks(1) === Success)
assert(!sched.finishedManagers.contains(manager))
// Finish the last task
manager.handleSuccessfulTask(2, createTaskResult(2, accumUpdatesByTask(2)))
assert(sched.endedTasks(2) === Success)
assert(sched.finishedManagers.contains(manager))
}
test("skip unsatisfiable locality levels") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("execA", "host1"), ("execC", "host2"))
val taskSet = FakeTask.createTaskSet(1, Seq(TaskLocation("host1", "execB")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// An executor that is not NODE_LOCAL should be rejected.
assert(manager.resourceOffer("execC", "host2", ANY)._1 === None)
// Because there are no alive PROCESS_LOCAL executors, the base locality level should be
// NODE_LOCAL. So, we should schedule the task on this offered NODE_LOCAL executor before
// any of the locality wait timers expire.
assert(manager.resourceOffer("execA", "host1", ANY)._1.get.index === 0)
}
test("basic delay scheduling") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"))
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "exec1")),
Seq(TaskLocation("host2", "exec2")),
Seq(TaskLocation("host1"), TaskLocation("host2", "exec2")),
Seq() // Last task has no locality prefs
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1, exec1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
assert(manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)._1 === None)
clock.advance(LOCALITY_WAIT_MS)
// Offer host1, exec1 again, at NODE_LOCAL level: the node local (task 3) should
// get chosen before the noPref task
assert(manager.resourceOffer("exec1", "host1", NODE_LOCAL)._1.get.index == 2)
// Offer host2, exec2, at NODE_LOCAL level: we should choose task 2
assert(manager.resourceOffer("exec2", "host2", NODE_LOCAL)._1.get.index == 1)
// Offer host2, exec2 again, at NODE_LOCAL level: we should get noPref task
// after failing to find a node_Local task
assert(manager.resourceOffer("exec2", "host2", NODE_LOCAL)._1 === None)
clock.advance(LOCALITY_WAIT_MS)
assert(manager.resourceOffer("exec2", "host2", NO_PREF)._1.get.index == 3)
}
test("we do not need to delay scheduling when we only have noPref tasks in the queue") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec3", "host2"))
val taskSet = FakeTask.createTaskSet(3,
Seq(TaskLocation("host1", "exec1")),
Seq(TaskLocation("host2", "exec3")),
Seq() // Last task has no locality prefs
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1, exec1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)._1.get.index === 0)
assert(manager.resourceOffer("exec3", "host2", PROCESS_LOCAL)._1.get.index === 1)
assert(manager.resourceOffer("exec3", "host2", NODE_LOCAL)._1 === None)
assert(manager.resourceOffer("exec3", "host2", NO_PREF)._1.get.index === 2)
}
test("delay scheduling with fallback") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc,
("exec1", "host1"), ("exec2", "host2"), ("exec3", "host3"))
val taskSet = FakeTask.createTaskSet(5,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("host3")),
Seq(TaskLocation("host2"))
)
sc.conf.set(config.LEGACY_LOCALITY_WAIT_RESET, true)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
// Offer host1 again: nothing should get chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1 === None)
clock.advance(LOCALITY_WAIT_MS)
// Offer host1 again: second task (on host2) should get chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 1)
// Offer host1 again: third task (on host2) should get chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 2)
// Offer host2: fifth task (also on host2) should get chosen
assert(manager.resourceOffer("exec2", "host2", ANY)._1.get.index === 4)
// Now that we've launched a local task, we should no longer launch the task for host3
assert(manager.resourceOffer("exec2", "host2", ANY)._1 === None)
clock.advance(LOCALITY_WAIT_MS)
// offers not accepted due to task set zombies are not delay schedule rejects
manager.isZombie = true
val (taskDescription, delayReject, _) = manager.resourceOffer("exec2", "host2", ANY)
assert(taskDescription.isEmpty)
assert(delayReject === false)
manager.isZombie = false
// offers not accepted due to excludelist are not delay schedule rejects
val tsmSpy = spy(manager)
val excludelist = mock(classOf[TaskSetExcludelist])
when(tsmSpy.taskSetExcludelistHelperOpt).thenReturn(Some(excludelist))
when(excludelist.isNodeExcludedForTaskSet(any())).thenReturn(true)
val (task, taskReject, _) = tsmSpy.resourceOffer("exec2", "host2", ANY)
assert(task.isEmpty)
assert(taskReject === false)
// After another delay, we can go ahead and launch that task non-locally
assert(manager.resourceOffer("exec2", "host2", ANY)._1.get.index === 3)
// offers not accepted due to no pending tasks are not delay schedule rejects
val (noPendingTask, noPendingReject, _) = manager.resourceOffer("exec2", "host2", ANY)
assert(noPendingTask.isEmpty)
assert(noPendingReject === false)
}
test("delay scheduling with failed hosts") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"),
("exec3", "host3"))
val taskSet = FakeTask.createTaskSet(3,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("host3"))
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
// After this, nothing should get chosen, because we have separated tasks with unavailable
// preference from the noPrefPendingTasks
assert(manager.resourceOffer("exec1", "host1", ANY)._1 === None)
// Now mark host2 as dead
sched.removeExecutor("exec2")
manager.executorLost("exec2", "host2", ExecutorProcessLost())
// nothing should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY)._1 === None)
clock.advance(LOCALITY_WAIT_MS * 2)
// task 1 and 2 would be scheduled as nonLocal task
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 1)
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 2)
// all finished
assert(manager.resourceOffer("exec1", "host1", ANY)._1 === None)
assert(manager.resourceOffer("exec2", "host2", ANY)._1 === None)
}
test("task result lost") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val clock = new ManualClock
clock.advance(1)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
// Tell it the task has finished but the result was lost.
manager.handleFailedTask(0, TaskState.FINISHED, TaskResultLost)
assert(sched.endedTasks(0) === TaskResultLost)
// Re-offer the host -- now we should get task 0 again.
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
}
test("repeated failures lead to task set abortion") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val clock = new ManualClock
clock.advance(1)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// Fail the task MAX_TASK_FAILURES times, and check that the task set is aborted
// after the last failure.
(1 to manager.maxTaskFailures).foreach { index =>
val offerResult = manager.resourceOffer("exec1", "host1", ANY)._1
assert(offerResult.isDefined,
"Expect resource offer on iteration %s to return a task".format(index))
assert(offerResult.get.index === 0)
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
if (index < MAX_TASK_FAILURES) {
assert(!sched.taskSetsFailed.contains(taskSet.id))
} else {
assert(sched.taskSetsFailed.contains(taskSet.id))
}
}
}
test("executors should be excluded after task failure, in spite of locality preferences") {
val rescheduleDelay = 300L
val conf = new SparkConf().
set(config.EXCLUDE_ON_FAILURE_ENABLED, true).
set(config.EXCLUDE_ON_FAILURE_TIMEOUT_CONF, rescheduleDelay).
// don't wait to jump locality levels in this test
set(config.LOCALITY_WAIT.key, "0")
sc = new SparkContext("local", "test", conf)
// two executors on same host, one on different.
sched = new FakeTaskScheduler(sc, ("exec1", "host1"),
("exec1.1", "host1"), ("exec2", "host2"))
// affinity to exec1 on host1 - which we will fail.
val taskSet = FakeTask.createTaskSet(1, Seq(TaskLocation("host1", "exec1")))
val clock = new ManualClock
clock.advance(1)
// We don't directly use the application excludelist, but its presence triggers exclusion
// within the taskset.
val mockListenerBus = mock(classOf[LiveListenerBus])
val healthTrackerOpt = Some(new HealthTracker(mockListenerBus, conf, None, clock))
val manager = new TaskSetManager(sched, taskSet, 4, healthTrackerOpt, clock)
{
val offerResult = manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)._1
assert(offerResult.isDefined, "Expect resource offer to return a task")
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec1")
// Cause exec1 to fail : failure 1
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
assert(!sched.taskSetsFailed.contains(taskSet.id))
// Ensure scheduling on exec1 fails after failure 1 due to executor being excluded
assert(manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)._1.isEmpty)
assert(manager.resourceOffer("exec1", "host1", NODE_LOCAL)._1.isEmpty)
assert(manager.resourceOffer("exec1", "host1", RACK_LOCAL)._1.isEmpty)
assert(manager.resourceOffer("exec1", "host1", ANY)._1.isEmpty)
}
// Run the task on exec1.1 - should work, and then fail it on exec1.1
{
val offerResult = manager.resourceOffer("exec1.1", "host1", NODE_LOCAL)._1
assert(offerResult.isDefined,
"Expect resource offer to return a task for exec1.1, offerResult = " + offerResult)
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec1.1")
// Cause exec1.1 to fail : failure 2
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
assert(!sched.taskSetsFailed.contains(taskSet.id))
// Ensure scheduling on exec1.1 fails after failure 2 due to executor being excluded
assert(manager.resourceOffer("exec1.1", "host1", NODE_LOCAL)._1.isEmpty)
}
// Run the task on exec2 - should work, and then fail it on exec2
{
val offerResult = manager.resourceOffer("exec2", "host2", ANY)._1
assert(offerResult.isDefined, "Expect resource offer to return a task")
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec2")
// Cause exec2 to fail : failure 3
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
assert(!sched.taskSetsFailed.contains(taskSet.id))
// Ensure scheduling on exec2 fails after failure 3 due to executor being excluded
assert(manager.resourceOffer("exec2", "host2", ANY)._1.isEmpty)
}
// Despite advancing beyond the time for expiring executors from within the excludelist,
// we *never* expire from *within* the stage excludelist
clock.advance(rescheduleDelay)
{
val offerResult = manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)._1
assert(offerResult.isEmpty)
}
{
val offerResult = manager.resourceOffer("exec3", "host3", ANY)._1
assert(offerResult.isDefined)
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec3")
assert(manager.resourceOffer("exec3", "host3", ANY)._1.isEmpty)
// Cause exec3 to fail : failure 4
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
}
// we have failed the same task 4 times now : task id should now be in taskSetsFailed
assert(sched.taskSetsFailed.contains(taskSet.id))
}
test("new executors get added and lost") {
// Assign host2 to rack2
FakeRackUtil.assignHostToRack("host2", "rack2")
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execB")),
Seq(TaskLocation("host2", "execC")),
Seq())
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// Only ANY is valid
assert(manager.myLocalityLevels.sameElements(Array(NO_PREF, ANY)))
// Add a new executor
sched.addExecutor("execD", "host1")
manager.executorAdded()
// Valid locality should contain NODE_LOCAL and ANY
assert(manager.myLocalityLevels.sameElements(Array(NODE_LOCAL, NO_PREF, ANY)))
// Add another executor
sched.addExecutor("execC", "host2")
manager.executorAdded()
// Valid locality should contain PROCESS_LOCAL, NODE_LOCAL, RACK_LOCAL and ANY
assert(manager.myLocalityLevels.sameElements(
Array(PROCESS_LOCAL, NODE_LOCAL, NO_PREF, RACK_LOCAL, ANY)))
// test if the valid locality is recomputed when the executor is lost
sched.removeExecutor("execC")
manager.executorLost("execC", "host2", ExecutorProcessLost())
assert(manager.myLocalityLevels.sameElements(Array(NODE_LOCAL, NO_PREF, ANY)))
sched.removeExecutor("execD")
manager.executorLost("execD", "host1", ExecutorProcessLost())
assert(manager.myLocalityLevels.sameElements(Array(NO_PREF, ANY)))
}
test("Executors exit for reason unrelated to currently running tasks") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execB")),
Seq(TaskLocation("host2", "execC")),
Seq())
val clock = new ManualClock()
clock.advance(1)
val manager = new TaskSetManager(sched, taskSet, 1, clock = clock)
sched.addExecutor("execA", "host1")
manager.executorAdded()
sched.addExecutor("execC", "host2")
manager.executorAdded()
assert(manager.resourceOffer("execB", "host1", ANY)._1.isDefined)
sched.removeExecutor("execA")
manager.executorLost(
"execA",
"host1",
ExecutorExited(143, false, "Terminated for reason unrelated to running tasks"))
assert(!sched.taskSetsFailed.contains(taskSet.id))
assert(manager.resourceOffer("execC", "host2", ANY)._1.isDefined)
sched.removeExecutor("execC")
manager.executorLost(
"execC", "host2", ExecutorExited(1, true, "Terminated due to issue with running tasks"))
assert(sched.taskSetsFailed.contains(taskSet.id))
}
test("SPARK-31837: Shift to the new highest locality level if there is when recomputeLocality") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val taskSet = FakeTask.createTaskSet(2,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execA")))
val clock = new ManualClock()
val manager = new TaskSetManager(sched, taskSet, 1, clock = clock)
// before any executors are added to TaskScheduler, the manager's
// locality level only has ANY, so tasks can be scheduled anyway.
assert(manager.resourceOffer("execB", "host2", ANY)._1.isDefined)
sched.addExecutor("execA", "host1")
manager.executorAdded()
// after adding a new executor, the manager locality has PROCESS_LOCAL, NODE_LOCAL, ANY.
// And we'll shift to the new highest locality level, which is PROCESS_LOCAL in this case.
assert(manager.resourceOffer("execC", "host3", ANY)._1.isEmpty)
assert(manager.resourceOffer("execA", "host1", ANY)._1.isDefined)
}
test("SPARK-32653: Decommissioned host should not be used to calculate locality levels") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val backend = mock(classOf[SchedulerBackend])
doNothing().when(backend).reviveOffers()
sched.initialize(backend)
val exec0 = "exec0"
val exec1 = "exec1"
val host0 = "host0"
sched.addExecutor(exec0, host0)
sched.addExecutor(exec1, host0)
val taskSet = FakeTask.createTaskSet(2,
Seq(ExecutorCacheTaskLocation(host0, exec0)),
Seq(ExecutorCacheTaskLocation(host0, exec1)))
sched.submitTasks(taskSet)
val manager = sched.taskSetManagerForAttempt(0, 0).get
assert(manager.myLocalityLevels === Array(PROCESS_LOCAL, NODE_LOCAL, ANY))
// Decommission all executors on host0, to mimic CoarseGrainedSchedulerBackend.
sched.executorDecommission(exec0, ExecutorDecommissionInfo("test", Some(host0)))
sched.executorDecommission(exec1, ExecutorDecommissionInfo("test", Some(host0)))
assert(manager.myLocalityLevels === Array(ANY))
}
test("SPARK-32653: Decommissioned executor should not be used to calculate locality levels") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val backend = mock(classOf[SchedulerBackend])
doNothing().when(backend).reviveOffers()
sched.initialize(backend)
val exec0 = "exec0"
val exec1 = "exec1"
val host0 = "host0"
sched.addExecutor(exec0, host0)
sched.addExecutor(exec1, host0)
val taskSet = FakeTask.createTaskSet(1, Seq(ExecutorCacheTaskLocation(host0, exec0)))
sched.submitTasks(taskSet)
val manager = sched.taskSetManagerForAttempt(0, 0).get
assert(manager.myLocalityLevels === Array(PROCESS_LOCAL, NODE_LOCAL, ANY))
// Decommission the only executor (without the host) that the task is interested in running on.
sched.executorDecommission(exec0, ExecutorDecommissionInfo("test", None))
assert(manager.myLocalityLevels === Array(NODE_LOCAL, ANY))
}
test("test RACK_LOCAL tasks") {
// Assign host1 to rack1
FakeRackUtil.assignHostToRack("host1", "rack1")
// Assign host2 to rack1
FakeRackUtil.assignHostToRack("host2", "rack1")
// Assign host3 to rack2
FakeRackUtil.assignHostToRack("host3", "rack2")
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc,
("execA", "host1"), ("execB", "host2"), ("execC", "host3"))
val taskSet = FakeTask.createTaskSet(2,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execA")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
assert(manager.myLocalityLevels.sameElements(Array(PROCESS_LOCAL, NODE_LOCAL, RACK_LOCAL, ANY)))
// Set allowed locality to ANY
clock.advance(LOCALITY_WAIT_MS * 3)
// Offer host3
// No task is scheduled if we restrict locality to RACK_LOCAL
assert(manager.resourceOffer("execC", "host3", RACK_LOCAL)._1 === None)
// Task 0 can be scheduled with ANY
assert(manager.resourceOffer("execC", "host3", ANY)._1.get.index === 0)
// Offer host2
// Task 1 can be scheduled with RACK_LOCAL
assert(manager.resourceOffer("execB", "host2", RACK_LOCAL)._1.get.index === 1)
}
test("do not emit warning when serialized task is small") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
assert(!manager.emittedTaskSizeWarning)
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
assert(!manager.emittedTaskSizeWarning)
}
test("emit warning when serialized task is large") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = new TaskSet(Array(new LargeTask(0)), 0, 0, 0,
null, ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
assert(!manager.emittedTaskSizeWarning)
assert(manager.resourceOffer("exec1", "host1", ANY)._1.get.index === 0)
assert(manager.emittedTaskSizeWarning)
}
test("Not serializable exception thrown if the task cannot be serialized") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = new TaskSet(
Array(new NotSerializableFakeTask(1, 0), new NotSerializableFakeTask(0, 1)),
0, 0, 0, null, ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
intercept[TaskNotSerializableException] {
manager.resourceOffer("exec1", "host1", ANY)
}
assert(manager.isZombie)
}
test("abort the job if total size of results is too large") {
val conf = new SparkConf().set(config.MAX_RESULT_SIZE.key, "2m")
sc = new SparkContext("local", "test", conf)
def genBytes(size: Int): (Int) => Array[Byte] = { (x: Int) =>
val bytes = Array.ofDim[Byte](size)
scala.util.Random.nextBytes(bytes)
bytes
}
// multiple 1k result
val r = sc.makeRDD(0 until 10, 10).map(genBytes(1024)).collect()
assert(10 === r.size)
// single 10M result
val thrown = intercept[SparkException] {sc.makeRDD(genBytes(10 << 20)(0), 1).collect()}
assert(thrown.getMessage().contains("bigger than spark.driver.maxResultSize"))
// multiple 1M results
val thrown2 = intercept[SparkException] {
sc.makeRDD(0 until 10, 10).map(genBytes(1 << 20)).collect()
}
assert(thrown2.getMessage().contains("bigger than spark.driver.maxResultSize"))
}
test("SPARK-32470: do not check total size of intermediate stages") {
val conf = new SparkConf().set(config.MAX_RESULT_SIZE.key, "20k")
sc = new SparkContext("local", "test", conf)
// final result is below limit.
val r = sc.makeRDD(0 until 2000, 2000).distinct(10).filter(_ == 0).collect()
assert(1 === r.size)
}
test("[SPARK-13931] taskSetManager should not send Resubmitted tasks after being a zombie") {
val conf = new SparkConf().set(config.SPECULATION_ENABLED, true)
sc = new SparkContext("local", "test", conf)
sched = new FakeTaskScheduler(sc, ("execA", "host1"), ("execB", "host2"))
sched.initialize(new FakeSchedulerBackend() {
override def killTask(
taskId: Long,
executorId: String,
interruptThread: Boolean,
reason: String): Unit = {}
})
// Keep track of the number of tasks that are resubmitted,
// so that the test can check that no tasks were resubmitted.
var resubmittedTasks = 0
val dagScheduler = new FakeDAGScheduler(sc, sched) {
override def taskEnded(
task: Task[_],
reason: TaskEndReason,
result: Any,
accumUpdates: Seq[AccumulatorV2[_, _]],
metricPeaks: Array[Long],
taskInfo: TaskInfo): Unit = {
super.taskEnded(task, reason, result, accumUpdates, metricPeaks, taskInfo)
reason match {
case Resubmitted => resubmittedTasks += 1
case _ =>
}
}
}
sched.dagScheduler.stop()
sched.setDAGScheduler(dagScheduler)
val singleTask = new ShuffleMapTask(0, 0, null, new Partition {
override def index: Int = 0
}, Seq(TaskLocation("host1", "execA")), new Properties, null)
val taskSet = new TaskSet(Array(singleTask), 0, 0, 0,
null, ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
// Offer host1, which should be accepted as a PROCESS_LOCAL location
// by the one task in the task set
val task1 = manager.resourceOffer("execA", "host1", TaskLocality.PROCESS_LOCAL)._1.get
// Mark the task as available for speculation, and then offer another resource,
// which should be used to launch a speculative copy of the task.
manager.speculatableTasks += singleTask.partitionId
manager.addPendingTask(singleTask.partitionId, speculatable = true)
val task2 = manager.resourceOffer("execB", "host2", TaskLocality.ANY)._1.get
assert(manager.runningTasks === 2)
assert(manager.isZombie === false)
val directTaskResult = new DirectTaskResult[String](null, Seq(), Array()) {
override def value(resultSer: SerializerInstance): String = ""
}
// Complete one copy of the task, which should result in the task set manager
// being marked as a zombie, because at least one copy of its only task has completed.
manager.handleSuccessfulTask(task1.taskId, directTaskResult)
assert(manager.isZombie)
assert(resubmittedTasks === 0)
assert(manager.runningTasks === 1)
manager.executorLost("execB", "host2", new ExecutorProcessLost())
assert(manager.runningTasks === 0)
assert(resubmittedTasks === 0)
}
test("[SPARK-22074] Task killed by other attempt task should not be resubmitted") {
val conf = new SparkConf().set(config.SPECULATION_ENABLED, true)
sc = new SparkContext("local", "test", conf)
// Set the speculation multiplier to be 0 so speculative tasks are launched immediately
sc.conf.set(config.SPECULATION_MULTIPLIER, 0.0)
sc.conf.set(config.SPECULATION_QUANTILE, 0.5)
sc.conf.set(config.SPECULATION_ENABLED, true)
var killTaskCalled = false
sched = new FakeTaskScheduler(sc, ("exec1", "host1"),
("exec2", "host2"), ("exec3", "host3"))
sched.initialize(new FakeSchedulerBackend() {
override def killTask(
taskId: Long,
executorId: String,
interruptThread: Boolean,
reason: String): Unit = {
// Check the only one killTask event in this case, which triggered by
// task 2.1 completed.
assert(taskId === 2)
assert(executorId === "exec3")
assert(interruptThread)
assert(reason === "another attempt succeeded")
killTaskCalled = true
}
})
// Keep track of the number of tasks that are resubmitted,
// so that the test can check that no tasks were resubmitted.
var resubmittedTasks = 0
val dagScheduler = new FakeDAGScheduler(sc, sched) {
override def taskEnded(
task: Task[_],
reason: TaskEndReason,
result: Any,
accumUpdates: Seq[AccumulatorV2[_, _]],
metricPeaks: Array[Long],
taskInfo: TaskInfo): Unit = {
super.taskEnded(task, reason, result, accumUpdates, metricPeaks, taskInfo)
reason match {
case Resubmitted => resubmittedTasks += 1
case _ =>
}
}
}
sched.dagScheduler.stop()
sched.setDAGScheduler(dagScheduler)
val taskSet = FakeTask.createShuffleMapTaskSet(4, 0, 0,
Seq(TaskLocation("host1", "exec1")),
Seq(TaskLocation("host1", "exec1")),
Seq(TaskLocation("host3", "exec3")),
Seq(TaskLocation("host2", "exec2")))
val clock = new ManualClock()
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
val accumUpdatesByTask: Array[Seq[AccumulatorV2[_, _]]] = taskSet.tasks.map { task =>
task.metrics.internalAccums
}
// Offer resources for 4 tasks to start
for ((exec, host) <- Seq(
"exec1" -> "host1",
"exec1" -> "host1",
"exec3" -> "host3",
"exec2" -> "host2")) {
val taskOption = manager.resourceOffer(exec, host, NO_PREF)._1
assert(taskOption.isDefined)
val task = taskOption.get
assert(task.executorId === exec)
// Add an extra assert to make sure task 2.0 is running on exec3
if (task.index == 2) {
assert(task.attemptNumber === 0)
assert(task.executorId === "exec3")
}
}
assert(sched.startedTasks.toSet === Set(0, 1, 2, 3))
clock.advance(1)
// Complete the 2 tasks and leave 2 task in running
for (id <- Set(0, 1)) {
manager.handleSuccessfulTask(id, createTaskResult(id, accumUpdatesByTask(id)))
assert(sched.endedTasks(id) === Success)
}
// checkSpeculatableTasks checks that the task runtime is greater than the threshold for
// speculating. Since we use a threshold of 0 for speculation, tasks need to be running for
// > 0ms, so advance the clock by 1ms here.
clock.advance(1)
assert(manager.checkSpeculatableTasks(0))
assert(sched.speculativeTasks.toSet === Set(2, 3))
// Offer resource to start the speculative attempt for the running task 2.0
val taskOption = manager.resourceOffer("exec2", "host2", ANY)._1
assert(taskOption.isDefined)
val task4 = taskOption.get
assert(task4.index === 2)
assert(task4.taskId === 4)
assert(task4.executorId === "exec2")
assert(task4.attemptNumber === 1)
// Complete the speculative attempt for the running task
manager.handleSuccessfulTask(4, createTaskResult(2, accumUpdatesByTask(2)))
// Make sure schedBackend.killTask(2, "exec3", true, "another attempt succeeded") gets called
assert(killTaskCalled)
// Host 3 Losts, there's only task 2.0 on it, which killed by task 2.1
manager.executorLost("exec3", "host3", ExecutorProcessLost())
// Check the resubmittedTasks
assert(resubmittedTasks === 0)
}
test("speculative and noPref task should be scheduled after node-local") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(