This is an automated email from the ASF dual-hosted git repository.
HeartSaVioR pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 5fb4d4c0311e [SPARK-56962][SS][RTM][STREAMINGSHUFFLE][PART2] Add
StreamingShuffleOutputTracker for streaming shuffle coordination
5fb4d4c0311e is described below
commit 5fb4d4c0311eb3e5b7a7bfbabaa55fa056df61ff
Author: Boyang Jerry Peng <[email protected]>
AuthorDate: Wed May 27 22:22:02 2026 +0900
[SPARK-56962][SS][RTM][STREAMINGSHUFFLE][PART2] Add
StreamingShuffleOutputTracker for streaming shuffle coordination
### What changes were proposed in this pull request?
#### Context
This is the second PR in a stack of nine that contributes a new
**streaming shuffle** implementation to Apache Spark. Streaming shuffle is a
push-based shuffle designed for low-latency,
continuously-running queries (e.g., Real-Time mode in Structured
Streaming) where the map and reduce stages must run concurrently rather than
sequentially. Each map task hosts a Netty
server that pushes records to reduce tasks as they are produced; reduce
tasks open clients to those servers and consume records as a stream — no
on-disk materialization, no map-stage
barrier.
Because the full implementation spans the network protocol, driver-side
coordination, plugin layer, executor-side writer/reader, engine integration,
and tests, it is split into nine
independently reviewable PRs:
1. **Wire protocol** (apache/spark#55620) — binary message types in
`network-common`, pure Java.
2. **Output tracker (this PR)** — driver-side coordination service
mapping shuffle IDs to writer task locations.
3. **Shuffle manager + Netty handlers + logging mixin** — the
`ShuffleManager` plugin entry point, the bidirectional Netty handlers, and a
`TaskContext`-aware logging trait.
4. **SparkEnv + DAGScheduler integration** — wires the tracker into
`SparkEnv` and registers shuffles from `DAGScheduler`.
5. **Writer** — `StreamingShuffleWriter` (server-side push).
6. **Reader** — `StreamingShuffleReader` (client-side pull).
7. **MultiShuffleManager** — routes per-shuffle to streaming or sort
shuffle based on a task-local property.
8. **Tests** — end-to-end suite for the streaming shuffle plugin.
9. **Documentation** — design and configuration reference.
This PR has **no compile dependency on PR1** (the tracker lives in
`org.apache.spark.*` and does not reference any of the protocol classes), so
the two can be reviewed in parallel. Each
PR compiles standalone. The plugin only becomes usable end-to-end after
PRs 1–7.
#### Changes in this PR
This PR introduces the driver-side coordination service that lets
streaming shuffle writers and readers discover each other.
**`StreamingShuffleOutputTracker`** (abstract base) exposes four public
methods:
| API | Caller | Behavior |
|-----|--------|----------|
| `registerShuffle(shuffleId, numMaps, numReduces, jobId)` |
`DAGScheduler` (PR 4) | Records the shuffle's metadata. |
| `registerShuffleWriterTask(shuffleId, mapId, location)` | Writer task
(PR 5) | Publishes a writer's `(executorId, host, port)`. |
| `getAllShuffleWriterTaskLocations(shuffleId)` | Reader (PR 6), barrier
API | Returns `None` until **all** writers have registered; then returns the
full map. |
| `getAvailableShuffleWriterTaskLocations(shuffleId)` | Reader (PR 6),
progressive API | Returns whatever writers have registered so far, together
with the total expected count. |
The base is specialized by:
- **`StreamingShuffleOutputTrackerMaster`** (driver) — backed by a
`ConcurrentHashMap`, with a message-loop thread pool that dispatches RPC
replies off the Netty threads so a slow
downstream cannot stall the I/O loop. Reuses
`SHUFFLE_MAPOUTPUT_DISPATCHER_NUM_THREADS` for sizing.
- **`StreamingShuffleOutputTrackerWorker`** (executor) — thin RPC proxy
that forwards every call to the master.
- **`StreamingShuffleOutputTrackerMasterEndpoint`** — Netty RPC endpoint
that feeds incoming requests into the master's blocking queue.
Supporting types:
- `StreamingShuffleTaskLocation(executorId, host, port)` — the location
record published by writers and consumed by readers.
- `ShuffleLocationResponse(locations, numShuffleWriterTasks)` — the
response type for the progressive (`getAvailable…`) API; carries the total
expected count so a reader can tell how
many writers it still has to discover.
- `StreamingShuffleInfo(numMaps, numReduces, jobId)` — per-shuffle
metadata held on the driver.
This PR also adds the three log keys used by the tracker — `NUM_MAPPERS`,
`NUM_REDUCERS`, and `TASK_LOCATION` — to `LogKeys.java`.
### Why are the changes needed?
The default `SortShuffleManager` requires every map task to finish
writing its output to disk before any reduce task can start. That model is not
workable for the streaming shuffle
introduced over the rest of this stack, where map and reduce tasks must
coexist for the lifetime of the query and reduce tasks need to start consuming
records the moment they are
produced.
For that to work, a reduce task has to be able to ask the driver, "where
is writer N's TransportServer running?" and the driver has to track the answer
as writers come online. That
coordination is what `StreamingShuffleOutputTracker` provides:
- It exposes **two lookup modes**. The barrier API
(`getAllShuffleWriterTaskLocations`) returns `None` until every writer has
registered — useful when a reader needs the full set up
front. The progressive API (`getAvailableShuffleWriterTaskLocations`)
returns whatever subset is known so far together with the total expected count
— what the streaming-shuffle reader
(PR 6) actually uses, so it can begin consuming from the first writer
while later writers are still launching.
- It uses an **off-Netty dispatcher thread pool** on the master so that
slow paths (e.g., a reader doing a lookup at task-launch time) never block the
RPC I/O loop. This is the same
pattern `MapOutputTrackerMaster` uses for the same reason.
- It is a separate service from `MapOutputTracker`. The streaming shuffle
does not produce `MapStatus` outputs, so it cannot reuse the existing tracker,
but it does need an analogous
coordination point.
This PR's coordination layer is the natural foundation for the rest of
the stack: every subsequent PR depends on it.
### Does this PR introduce _any_ user-facing change?
No.
`StreamingShuffleOutputTracker` is only instantiated when the configured
`spark.shuffle.manager` is `StreamingShuffleManager` or `MultiShuffleManager`.
Those manager classes are
introduced in later PRs in the stack (PR 3 and PR 7), and the `SparkEnv`
wiring that creates the tracker is introduced in PR 4. Until those land, there
is no caller for any of the code
in this PR, and there is no observable behavior change for any user.
### How was this patch tested?
`StreamingShuffleOutputTrackerSuite` runs 11 unit tests covering:
| Group | Tests |
|------|------|
| RPC lifecycle (through `RpcEnv`) | `master start and stop`, `test
tracker workflow` |
| Negative cases (through `RpcEnv`) | `register task for shuffle that
doesn't exist`, `get task location for shuffle that doesn't exist` |
| Master register/lookup (in-process) | `register shuffle`, `register and
get writer task locations`, `unregister shuffle`, `multiple shuffles` |
| Master progressive lookup (in-process) | `get available writer task
locations` (returns partial results before all writers register) |
| Master negative case (in-process) | `register writer before shuffle
fails` |
| Master concurrency | `concurrent registration` (100 concurrent register
calls, asserts all 100 land) |
To run locally:
build/sbt 'core/testOnly *StreamingShuffleOutputTrackerSuite'
Output:
[info] StreamingShuffleOutputTrackerSuite:
[info] - master start and stop (279 milliseconds)
[info] - test tracker workflow (26 milliseconds)
[info] - register task for shuffle that doesn't exist (19 milliseconds)
[info] - get task location for shuffle that doesn't exist (13
milliseconds)
[info] - StreamingShuffleOutputTrackerMaster - register shuffle (3
milliseconds)
[info] - StreamingShuffleOutputTrackerMaster - register and get writer
task locations (2 milliseconds)
[info] - StreamingShuffleOutputTrackerMaster - get available writer task
locations (2 milliseconds)
[info] - StreamingShuffleOutputTrackerMaster - unregister shuffle (1
millisecond)
[info] - StreamingShuffleOutputTrackerMaster - register writer before
shuffle fails (2 milliseconds)
[info] - StreamingShuffleOutputTrackerMaster - concurrent registration
(11 milliseconds)
[info] - StreamingShuffleOutputTrackerMaster - multiple shuffles (1
millisecond)
[info] Run completed in 1 second, 589 milliseconds.
[info] Tests: succeeded 11, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
### Was this patch authored or co-authored using generative AI tooling?
Co-authored with Claude
Closes #56008 from jerrypeng/stack/streaming-shuffle-pr2-tracker-solo.
Authored-by: Boyang Jerry Peng <[email protected]>
Signed-off-by: Jungtaek Lim <[email protected]>
---
.../java/org/apache/spark/internal/LogKeys.java | 3 +
.../spark/StreamingShuffleOutputTracker.scala | 443 ++++++++++++++++++++
.../spark/StreamingShuffleOutputTrackerSuite.scala | 459 +++++++++++++++++++++
3 files changed, 905 insertions(+)
diff --git
a/common/utils-java/src/main/java/org/apache/spark/internal/LogKeys.java
b/common/utils-java/src/main/java/org/apache/spark/internal/LogKeys.java
index e92ef6f462a3..d8ce9d025af9 100644
--- a/common/utils-java/src/main/java/org/apache/spark/internal/LogKeys.java
+++ b/common/utils-java/src/main/java/org/apache/spark/internal/LogKeys.java
@@ -502,6 +502,7 @@ public enum LogKeys implements LogKey {
NUM_LOCAL_BLOCKS,
NUM_LOCAL_DIRS,
NUM_LOCAL_FREQUENT_PATTERN,
+ NUM_MAPPERS,
NUM_MERGERS,
NUM_MERGER_LOCATIONS,
NUM_META_FILES,
@@ -522,6 +523,7 @@ public enum LogKeys implements LogKey {
NUM_PUSH_MERGED_LOCAL_BLOCKS,
NUM_RECEIVERS,
NUM_RECORDS_READ,
+ NUM_REDUCERS,
NUM_RELEASED_LOCKS,
NUM_REMAINED,
NUM_REMOTE_BLOCKS,
@@ -815,6 +817,7 @@ public enum LogKeys implements LogKey {
TASK_ID,
TASK_INDEX,
TASK_LOCALITY,
+ TASK_LOCATION,
TASK_NAME,
TASK_REQUIREMENTS,
TASK_RESOURCES,
diff --git
a/core/src/main/scala/org/apache/spark/StreamingShuffleOutputTracker.scala
b/core/src/main/scala/org/apache/spark/StreamingShuffleOutputTracker.scala
new file mode 100644
index 000000000000..090be7f691d4
--- /dev/null
+++ b/core/src/main/scala/org/apache/spark/StreamingShuffleOutputTracker.scala
@@ -0,0 +1,443 @@
+/*
+ * 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
+
+import java.util.concurrent.{ConcurrentHashMap, LinkedBlockingQueue,
ThreadPoolExecutor}
+
+import scala.jdk.CollectionConverters._
+import scala.reflect.ClassTag
+import scala.util.control.NonFatal
+
+import org.apache.spark.internal.{Logging, LogKeys}
+import
org.apache.spark.internal.config.SHUFFLE_MAPOUTPUT_DISPATCHER_NUM_THREADS
+import org.apache.spark.rpc.{RpcCallContext, RpcEndpoint, RpcEndpointRef,
RpcEnv}
+import org.apache.spark.util.ThreadUtils
+
+private[spark] sealed trait StreamingShuffleTaskLocationTrackerMessage
+
+private[spark] case class UpdateStreamingShuffleTaskLocation(
+ shuffleId: Int,
+ mapId: Long,
+ location: StreamingShuffleTaskLocation)
+ extends StreamingShuffleTaskLocationTrackerMessage
+
+private[spark] case class GetAllStreamingShuffleTaskLocations(shuffleId: Int)
+ extends StreamingShuffleTaskLocationTrackerMessage
+
+private[spark] case class GetAvailableStreamingShuffleTaskLocations(shuffleId:
Int)
+ extends StreamingShuffleTaskLocationTrackerMessage
+
+private[spark] case object StopStreamingShuffleOutputTracker
+ extends StreamingShuffleTaskLocationTrackerMessage
+
+private[spark] sealed trait StreamingShuffleTaskLocationTrackerMasterMessage
+
+private[spark] case class UpdateStreamingShuffleTaskLocationMasterMessage(
+ shuffleId: Int,
+ mapId: Long,
+ location: StreamingShuffleTaskLocation,
+ context: RpcCallContext)
+ extends StreamingShuffleTaskLocationTrackerMasterMessage
+
+private[spark] case class GetAllStreamingShuffleTaskLocationsMasterMessage(
+ shuffleId: Int,
+ context: RpcCallContext)
+ extends StreamingShuffleTaskLocationTrackerMasterMessage
+
+private[spark] case class
GetAvailableStreamingShuffleTaskLocationsMasterMessage(
+ shuffleId: Int,
+ context: RpcCallContext)
+ extends StreamingShuffleTaskLocationTrackerMasterMessage
+
+private[spark] case class StreamingShuffleTaskLocation(
+ executorId: String,
+ host: String,
+ port: Int)
+
+private[spark] class StreamingShuffleOutputTrackerMasterEndpoint(
+ override val rpcEnv: RpcEnv,
+ tracker: StreamingShuffleOutputTrackerMaster,
+ conf: SparkConf)
+ extends RpcEndpoint
+ with Logging {
+
+ logDebug("init") // force eager creation of logger
+
+ override def receiveAndReply(context: RpcCallContext): PartialFunction[Any,
Unit] = {
+ case GetAllStreamingShuffleTaskLocations(shuffleId) =>
+ tracker.post(GetAllStreamingShuffleTaskLocationsMasterMessage(shuffleId,
context))
+
+ case GetAvailableStreamingShuffleTaskLocations(shuffleId) =>
+
tracker.post(GetAvailableStreamingShuffleTaskLocationsMasterMessage(shuffleId,
context))
+
+ case UpdateStreamingShuffleTaskLocation(
+ shuffleId: Int,
+ mapId: Long,
+ location: StreamingShuffleTaskLocation) =>
+ tracker.post(
+ UpdateStreamingShuffleTaskLocationMasterMessage(shuffleId, mapId,
location, context))
+
+ case StopStreamingShuffleOutputTracker =>
+ logInfo(log"StreamingShuffleOutputTrackerMasterEndpoint stopped!")
+ // Unregister the endpoint from the Dispatcher BEFORE completing the
reply.
+ // This avoids a race where the caller (e.g., initializeShuffleManager)
is
+ // unblocked by context.reply() and tries to register a new endpoint
with the
+ // same name before this handler has finished unregistering the old one.
+ // stop() synchronously calls Dispatcher.stop(self) which removes the
endpoint
+ // name from the Dispatcher's endpoints map.
+ // context.reply() just completes a local Promise (p.success(true)) and
has no
+ // dependency on the endpoint's registration state, so it is safe to
call after
+ // stop().
+ stop()
+ context.reply(true)
+ }
+}
+
+case class ShuffleLocationResponse(
+ shuffleTaskLocations: Map[Long, StreamingShuffleTaskLocation],
+ numShuffleWriterTasks: Int)
+
+/**
+ * The purpose of this class is to support get task location information for
the streaming
+ * shuffle. For the streaming shuffle to work, tasks need to figure out what
where upstream tasks
+ * are located so it can connect to them to get data. The general usage of the
APIs are the
+ * following
+ * 1. The DAGScheduler will call registerShuffle for the tracker running on
the driver to
+ * register the shuffle. This is when information like number of mappers
will be passed into
+ * the driver.
+ * 2. Mapper / Shuffle writer tasks will call registerShuffleWriterTask to
+ * register themselves with the tracker running on the driver and provide
the information
+ * about where it is running
+ * 3. Reduce / Shuffle reader tasks will call
+ * getAllShuffleWriterTaskLocations to get the location information of
all the writers. The
+ * API "getAllShuffleWriterTaskLocations" returns all the writer task
locations or nothing at
+ * all. Partial results will not be returned. Shuffle readers should keep
polling this API
+ * until it returns a non-empty response.
+ */
+private[spark] abstract class StreamingShuffleOutputTracker(conf: SparkConf)
extends Logging {
+
+ /** Reference to the master endpoint living on the driver. */
+ var trackerEndpoint: RpcEndpointRef = _
+
+ /**
+ * Send a message to the trackerEndpoint and get its result within a default
timeout, or
+ * throw a SparkException if this fails.
+ */
+ protected def askTracker[T: ClassTag](message: Any): T = {
+ try {
+ trackerEndpoint.askSync[T](message)
+ } catch {
+ case e: Exception =>
+ logError(log"Error communicating with StreamingShuffleOutputTracker",
e)
+ throw new SparkException("Error communicating with
StreamingShuffleOutputTracker", e)
+ }
+ }
+
+ /** Send a one-way message to the trackerEndpoint, to which we expect it to
reply with true. */
+ protected def sendTracker(message: Any): Unit = {
+ val response = askTracker[Boolean](message)
+ if (response != true) {
+ throw new SparkException(
+ "Error reply received from StreamingShuffleOutputTracker. Expecting
true, got " +
+ response.toString)
+ }
+ }
+
+ def unregisterShuffle(shuffleId: Int): Unit = {}
+
+ def stop(): Unit = {}
+
+ /**
+ * Register a shuffle writer task (typically mapper task) for a shuffle and
provide information
+ * about where it is running. Will return false if the register is not
completed successfully
+ */
+ def registerShuffleWriterTask(
+ shuffleId: Int,
+ mapId: Long,
+ location: StreamingShuffleTaskLocation): Boolean
+
+ /**
+ * Get all shuffle writer tasks that are part of the shuffle. This API will
return None until
+ * all shuffle writer task location info is available.
+ * @param shuffleId The id of the shuffle to get the location information
about writer tasks
+ * @return A map in which the key is the shuffle writer task map id and the
value
+ * is the location information of the task.
+ */
+ def getAllShuffleWriterTaskLocations(
+ shuffleId: Int): Option[Map[Long, StreamingShuffleTaskLocation]]
+
+ /**
+ * Get the shuffle writer task locations that are currently available for a
shuffle. Please note
+ * that this function may not return all the shuffle writer locations if not
all of them are
+ * available. This contrast with the method
"getAllShuffleWriterTaskLocations" in which all
+ * locations will be returned or none with be returned.
+ * @param shuffleId The id of the shuffle to get the location information
about writer tasks
+ * @return ShuffleLocationResponse which contains a map shuffle writer task
locations and the
+ * total number of shuffle writers to expect.
+ */
+ def getAvailableShuffleWriterTaskLocations(shuffleId: Int):
Option[ShuffleLocationResponse]
+}
+
+private[spark] case class StreamingShuffleInfo(numMaps: Int, numReduces: Int,
jobId: Int)
+
+private[spark] class StreamingShuffleOutputTrackerMaster(conf: SparkConf)
+ extends StreamingShuffleOutputTracker(conf) {
+
+ // map that stores task location information organized in the following
fashion
+ // shuffle id -> {mapId -> location}
+ private val taskLocations =
+ new ConcurrentHashMap[Int, ConcurrentHashMap[Long,
StreamingShuffleTaskLocation]]()
+
+ private val shuffleInfos = new ConcurrentHashMap[Int, StreamingShuffleInfo]()
+
+ private val trackerMasterMessages =
+ new LinkedBlockingQueue[StreamingShuffleTaskLocationTrackerMasterMessage]
+
+ // Thread pool used for handling map output status requests. This is a
separate thread pool
+ // to ensure we don't block the normal dispatcher threads.
+ private val threadpool: ThreadPoolExecutor = {
+ val numThreads = conf.get(SHUFFLE_MAPOUTPUT_DISPATCHER_NUM_THREADS)
+ val pool =
+ ThreadUtils.newDaemonFixedThreadPool(numThreads,
"streaming-shuffle-location-dispatcher")
+ for (i <- 0 until numThreads) {
+ pool.execute(new MessageLoop)
+ }
+ pool
+ }
+
+ def registerShuffle(shuffleId: Int, numMaps: Int, numReduces: Int, jobId:
Int): Unit = {
+ logInfo(log"Registering shuffleId ${MDC(LogKeys.SHUFFLE_ID, shuffleId)}
with ${
+ MDC(LogKeys.NUM_MAPPERS, numMaps)} mappers and ${
+ MDC(LogKeys.NUM_REDUCERS, numReduces)} reducers")
+ if (shuffleInfos.putIfAbsent(
+ shuffleId, StreamingShuffleInfo(numMaps, numReduces, jobId)) != null) {
+ throw new IllegalArgumentException(s"Shuffle ID $shuffleId registered
twice")
+ }
+ }
+
+ // for testing purposes
+ private[spark] def getShuffleInfo(shuffleId: Int):
Option[StreamingShuffleInfo] = {
+ Option(shuffleInfos.get(shuffleId))
+ }
+
+ // for testing purposes -- size of the per-shuffle taskLocations map, used
to assert
+ // the absence of orphan entries left behind by a register/unregister race.
+ private[spark] def numShufflesWithTaskLocations: Int = taskLocations.size()
+
+ override def unregisterShuffle(shuffleId: Int): Unit = {
+ logInfo(log"Unregistering shuffleId ${MDC(LogKeys.SHUFFLE_ID, shuffleId)}")
+
+ if (!shuffleInfos.containsKey(shuffleId)) {
+ logWarning(log"Attempting to unregister a shuffle with id ${
+ MDC(LogKeys.SHUFFLE_ID, shuffleId)} that hasn't been registered")
+ }
+ // Order matters here: remove from shuffleInfos BEFORE taskLocations.
+ //
+ // A concurrent registerShuffleWriterTask installs into taskLocations from
inside a
+ // compute() lambda that holds ConcurrentHashMap's per-key bucket lock. Our
+ // taskLocations.remove below acquires the same lock, so the two
operations are
+ // strictly serialized for the same shuffleId. The lambda re-reads
+ // shuffleInfos.containsKey, with two possible outcomes:
+ // - If that read happens after our shuffleInfos.remove, the lambda
returns null
+ // and no entry is installed.
+ // - If that read happens before our shuffleInfos.remove, the lambda
installs the
+ // entry, but our taskLocations.remove then runs strictly after the
lambda
+ // releases the bucket lock and clears the entry.
+ // Either way, no orphan remains. See registerShuffleWriterTask.
+ shuffleInfos.remove(shuffleId)
+ taskLocations.remove(shuffleId)
+ }
+
+ def post(message: StreamingShuffleTaskLocationTrackerMasterMessage): Unit = {
+ trackerMasterMessages.offer(message)
+ }
+
+ /** Message loop used for dispatching messages. */
+ private class MessageLoop extends Runnable {
+
+ override def run(): Unit = {
+ try {
+ while (true) {
+ try {
+ val data = trackerMasterMessages.take()
+ if (data == PoisonPill) {
+ // Put PoisonPill back so that other MessageLoops can see it.
+ trackerMasterMessages.offer(PoisonPill)
+ return
+ }
+
+ data match {
+ case GetAllStreamingShuffleTaskLocationsMasterMessage(shuffleId,
context) =>
+ val ret = getAllShuffleWriterTaskLocations(shuffleId)
+ context.reply(ret)
+
+ case
GetAvailableStreamingShuffleTaskLocationsMasterMessage(shuffleId, context) =>
+ val ret = getAvailableShuffleWriterTaskLocations(shuffleId)
+ context.reply(ret)
+
+ case UpdateStreamingShuffleTaskLocationMasterMessage(
+ shuffleId,
+ mapId,
+ location,
+ context) =>
+ context.reply(registerShuffleWriterTask(shuffleId, mapId,
location))
+
+ }
+ } catch {
+ case NonFatal(e) => logError(log"${MDC(LogKeys.ERROR,
e.getMessage)}", e)
+ }
+ }
+ } catch {
+ case ie: InterruptedException => // exit
+ }
+ }
+ }
+
+ /** A poison endpoint that indicates MessageLoop should exit its message
loop. */
+ private val PoisonPill =
+ GetAllStreamingShuffleTaskLocationsMasterMessage(-99, null)
+
+ override def registerShuffleWriterTask(
+ shuffleId: Int,
+ mapId: Long,
+ location: StreamingShuffleTaskLocation): Boolean = {
+ if (!shuffleInfos.containsKey(shuffleId)) {
+ logWarning(
+ log"Attempting to register shuffle writer task for shuffle with id ${
+ MDC(LogKeys.SHUFFLE_ID, shuffleId)} that hasn't been registered. Map
id ${
+ MDC(LogKeys.MAP_ID, mapId)} location ${MDC(LogKeys.TASK_LOCATION,
location)}")
+ return false
+ }
+ // Re-check shuffleInfos from inside the compute lambda to make
register/unregister
+ // concurrency-safe. The lambda runs under ConcurrentHashMap's per-key
bucket lock,
+ // which serializes with unregisterShuffle's taskLocations.remove.
Together with
+ // unregisterShuffle's (shuffleInfos.remove, then taskLocations.remove)
ordering,
+ // any concurrent unregisterShuffle ends with no orphan entry in
taskLocations:
+ // - If the lambda observes the already-cleared shuffleInfos, it returns
null and
+ // no entry is installed.
+ // - If the lambda observes shuffleInfos still present, it installs the
entry, and
+ // the matching unregisterShuffle's taskLocations.remove (which had to
wait for
+ // this bucket lock) clears it strictly after.
+ var registered = true
+ taskLocations.compute(
+ shuffleId,
+ (
+ _: Int,
+ shuffleTaskLocationMap: ConcurrentHashMap[Long,
StreamingShuffleTaskLocation]) => {
+ if (!shuffleInfos.containsKey(shuffleId)) {
+ registered = false
+ null
+ } else {
+ val newShuffleTaskLocationMap = if (shuffleTaskLocationMap == null) {
+ new ConcurrentHashMap[Long, StreamingShuffleTaskLocation]()
+ } else {
+ shuffleTaskLocationMap
+ }
+ newShuffleTaskLocationMap.put(mapId, location)
+ newShuffleTaskLocationMap
+ }
+ })
+ if (!registered) {
+ logWarning(
+ log"Shuffle ${MDC(LogKeys.SHUFFLE_ID, shuffleId)} was unregistered " +
+ log"during registration of writer task ${MDC(LogKeys.MAP_ID,
mapId)}")
+ }
+ registered
+ }
+
+ override def getAllShuffleWriterTaskLocations(
+ shuffleId: Int): Option[Map[Long, StreamingShuffleTaskLocation]] = {
+ val shuffleInfo = shuffleInfos.get(shuffleId)
+ if (shuffleInfo == null) {
+ logWarning(log"Attempting to get shuffle writer task location
information " +
+ log"for shuffle with id ${MDC(LogKeys.SHUFFLE_ID, shuffleId)} that
hasn't been registered.")
+ return None
+ }
+
+ val shuffleTaskLocationMap = taskLocations.get(shuffleId)
+ if (shuffleTaskLocationMap == null) {
+ return None
+ }
+
+ // only return the mapper task location information if all mappers have
registered
+ if (shuffleInfo.numMaps == shuffleTaskLocationMap.size()) {
+ Some(shuffleTaskLocationMap.asScala.toMap)
+ } else {
+ None
+ }
+ }
+
+ override def stop(): Unit = {
+ trackerMasterMessages.offer(PoisonPill)
+ threadpool.shutdown()
+ if (trackerEndpoint != null) {
+ try {
+ sendTracker(StopStreamingShuffleOutputTracker)
+ } catch {
+ case e: SparkException =>
+ logError(log"Could not tell tracker we are stopping.", e)
+ }
+ trackerEndpoint = null
+ }
+ }
+
+ override def getAvailableShuffleWriterTaskLocations(
+ shuffleId: Int): Option[ShuffleLocationResponse] = {
+ val shuffleInfo = shuffleInfos.get(shuffleId)
+ if (shuffleInfo == null) {
+ logWarning(log"Attempting to get shuffle writer task location
information for " +
+ log"shuffle with id ${MDC(LogKeys.SHUFFLE_ID, shuffleId)} that hasn't
been registered.")
+ return None
+ }
+ val locations = taskLocations.get(shuffleId)
+ val shuffleTaskLocationMap = if (locations == null) {
+ Map.empty[Long, StreamingShuffleTaskLocation]
+ } else {
+ locations.asScala.toMap
+ }
+
+ Some(ShuffleLocationResponse(shuffleTaskLocationMap, shuffleInfo.numMaps))
+ }
+}
+
+private[spark] class StreamingShuffleOutputTrackerWorker(conf: SparkConf)
+ extends StreamingShuffleOutputTracker(conf) {
+
+ override def registerShuffleWriterTask(
+ shuffleId: Int,
+ mapId: Long,
+ location: StreamingShuffleTaskLocation): Boolean = {
+ askTracker[Boolean](UpdateStreamingShuffleTaskLocation(shuffleId, mapId,
location))
+ }
+
+ override def getAllShuffleWriterTaskLocations(
+ shuffleId: Int): Option[Map[Long, StreamingShuffleTaskLocation]] = {
+ askTracker[Option[Map[Long, StreamingShuffleTaskLocation]]](
+ GetAllStreamingShuffleTaskLocations(shuffleId))
+ }
+
+ override def getAvailableShuffleWriterTaskLocations(
+ shuffleId: Int): Option[ShuffleLocationResponse] = {
+ askTracker[Option[ShuffleLocationResponse]](
+ GetAvailableStreamingShuffleTaskLocations(shuffleId))
+ }
+}
+
+private[spark] object StreamingShuffleOutputTracker extends Logging {
+ val ENDPOINT_NAME = "StreamingShuffleOutputTracker"
+}
diff --git
a/core/src/test/scala/org/apache/spark/StreamingShuffleOutputTrackerSuite.scala
b/core/src/test/scala/org/apache/spark/StreamingShuffleOutputTrackerSuite.scala
new file mode 100644
index 000000000000..3c8d9b2f14e2
--- /dev/null
+++
b/core/src/test/scala/org/apache/spark/StreamingShuffleOutputTrackerSuite.scala
@@ -0,0 +1,459 @@
+/*
+ * 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
+
+import java.util.concurrent.CyclicBarrier
+
+import scala.collection.mutable.ArrayBuffer
+import scala.util.control.NonFatal
+
+import org.scalatest.BeforeAndAfter
+import org.scalatest.matchers.should.Matchers
+
+import
org.apache.spark.internal.config.SHUFFLE_MAPOUTPUT_DISPATCHER_NUM_THREADS
+import org.apache.spark.rpc.RpcEnv
+
+class StreamingShuffleOutputTrackerSuite
+ extends SparkFunSuite
+ with LocalSparkContext
+ with ThreadAudit
+ with BeforeAndAfter
+ with Matchers {
+
+ before {
+ doThreadPreAudit()
+ }
+
+ after {
+ trackersToStop.foreach { t =>
+ try t.stop() catch { case NonFatal(_) => }
+ }
+ trackersToStop.clear()
+ rpcEnvsToShutdown.foreach { e =>
+ try e.shutdown() catch { case NonFatal(_) => }
+ }
+ rpcEnvsToShutdown.clear()
+ doThreadPostAudit()
+ }
+
+ protected val conf = new SparkConf
+
+ private val trackersToStop = ArrayBuffer.empty[StreamingShuffleOutputTracker]
+ private val rpcEnvsToShutdown = ArrayBuffer.empty[RpcEnv]
+
+ protected def newTrackerMaster(sparkConf: SparkConf = conf) = {
+ val tracker = new StreamingShuffleOutputTrackerMaster(sparkConf)
+ trackersToStop += tracker
+ tracker
+ }
+
+ protected def newTrackerWorker(
+ sparkConf: SparkConf = conf): StreamingShuffleOutputTrackerWorker = {
+ val tracker = new StreamingShuffleOutputTrackerWorker(sparkConf)
+ trackersToStop += tracker
+ tracker
+ }
+
+ def createRpcEnv(
+ name: String,
+ host: String = "localhost",
+ port: Int = 0,
+ securityManager: SecurityManager = new SecurityManager(conf)): RpcEnv = {
+ val rpcEnv = RpcEnv.create(name, host, port, conf, securityManager)
+ rpcEnvsToShutdown += rpcEnv
+ rpcEnv
+ }
+
+ test("master start and stop") {
+ val rpcEnv = createRpcEnv("test")
+ val tracker = newTrackerMaster()
+ tracker.trackerEndpoint = rpcEnv.setupEndpoint(
+ StreamingShuffleOutputTracker.ENDPOINT_NAME,
+ new StreamingShuffleOutputTrackerMasterEndpoint(rpcEnv, tracker, conf))
+ }
+
+ test("test tracker workflow") {
+ val master = newTrackerMaster()
+ val worker = newTrackerWorker()
+
+ val rpcEnv = createRpcEnv("test")
+ val rpcEndpoint = rpcEnv.setupEndpoint(
+ StreamingShuffleOutputTracker.ENDPOINT_NAME,
+ new StreamingShuffleOutputTrackerMasterEndpoint(rpcEnv, master, conf))
+
+ master.trackerEndpoint = rpcEndpoint
+ worker.trackerEndpoint = rpcEndpoint
+
+ val shuffleId = 0
+ val numMaps = 2
+ val numReduces = 2
+ val jobId = 0
+ val taskMap =
+ Map(
+ 0 -> StreamingShuffleTaskLocation("executor-1", "host-1", 0),
+ 1 -> StreamingShuffleTaskLocation("executor-2", "host-2", 0))
+ master.registerShuffle(shuffleId, numMaps, numReduces, jobId)
+ // register one shuffle write task
+ worker.registerShuffleWriterTask(shuffleId, 0, taskMap(0))
+ // Get all shuffle write task location information. Should return None
since
+ // only one of the shuffle writers have registered
+ worker.getAllShuffleWriterTaskLocations(shuffleId) should be(None)
+ // register the next shuffle write task
+ worker.registerShuffleWriterTask(shuffleId, 1, taskMap(1))
+ // should get all the shuffle task location information now
+ worker.getAllShuffleWriterTaskLocations(shuffleId) should be(Some(taskMap))
+
+ // should be a no-op for the worker
+ worker.unregisterShuffle(shuffleId)
+ master.unregisterShuffle(shuffleId)
+
+ master.getShuffleInfo(shuffleId) should be(None)
+ }
+
+ test("register task for shuffle that doesn't exist") {
+ val master = newTrackerMaster()
+ val worker = newTrackerWorker()
+
+ val rpcEnv = createRpcEnv("test")
+ val rpcEndpoint = rpcEnv.setupEndpoint(
+ StreamingShuffleOutputTracker.ENDPOINT_NAME,
+ new StreamingShuffleOutputTrackerMasterEndpoint(rpcEnv, master, conf))
+
+ master.trackerEndpoint = rpcEndpoint
+ worker.trackerEndpoint = rpcEndpoint
+
+ worker.registerShuffleWriterTask(
+ 0,
+ 0,
+ StreamingShuffleTaskLocation("executor-1", "host-1", 0)) should be(false)
+ }
+
+ test("get task location for shuffle that doesn't exist") {
+ val master = newTrackerMaster()
+ val worker = newTrackerWorker()
+
+ val rpcEnv = createRpcEnv("test")
+ val rpcEndpoint = rpcEnv.setupEndpoint(
+ StreamingShuffleOutputTracker.ENDPOINT_NAME,
+ new StreamingShuffleOutputTrackerMasterEndpoint(rpcEnv, master, conf))
+
+ master.trackerEndpoint = rpcEndpoint
+ worker.trackerEndpoint = rpcEndpoint
+
+ worker.getAllShuffleWriterTaskLocations(0) should be(None)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - register shuffle") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ // Register a shuffle with 3 mappers and 2 reducers
+ tracker.registerShuffle(shuffleId = 0, numMaps = 3, numReduces = 2, jobId
= 1)
+
+ // Verify shuffle was registered
+ val shuffleInfo = tracker.getShuffleInfo(0)
+ assert(shuffleInfo.isDefined)
+ assert(shuffleInfo.get.numMaps === 3)
+ assert(shuffleInfo.get.numReduces === 2)
+ assert(shuffleInfo.get.jobId === 1)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - registering same shuffle twice
fails") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ tracker.registerShuffle(shuffleId = 0, numMaps = 2, numReduces = 2, jobId
= 1)
+
+ intercept[IllegalArgumentException] {
+ tracker.registerShuffle(shuffleId = 0, numMaps = 2, numReduces = 2,
jobId = 1)
+ }
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - register and get writer task
locations") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ // Register a shuffle
+ tracker.registerShuffle(shuffleId = 0, numMaps = 2, numReduces = 2, jobId
= 1)
+
+ // Register first writer task
+ val location1 = StreamingShuffleTaskLocation("executor1", "host1", 8000)
+ val success1 = tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0,
location1)
+ assert(success1)
+
+ // getAllShuffleWriterTaskLocations should return None until all writers
registered
+ assert(tracker.getAllShuffleWriterTaskLocations(0).isEmpty)
+
+ // Register second writer task
+ val location2 = StreamingShuffleTaskLocation("executor2", "host2", 8001)
+ val success2 = tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 1,
location2)
+ assert(success2)
+
+ // Now getAllShuffleWriterTaskLocations should return all locations
+ val allLocations = tracker.getAllShuffleWriterTaskLocations(0)
+ assert(allLocations.isDefined)
+ assert(allLocations.get.size === 2)
+ assert(allLocations.get(0L) === location1)
+ assert(allLocations.get(1L) === location2)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - get available writer task
locations") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ // Register a shuffle
+ tracker.registerShuffle(shuffleId = 0, numMaps = 3, numReduces = 2, jobId
= 1)
+
+ // Initially should return empty map with total count
+ val response1 = tracker.getAvailableShuffleWriterTaskLocations(0)
+ assert(response1.isDefined)
+ assert(response1.get.shuffleTaskLocations.isEmpty)
+ assert(response1.get.numShuffleWriterTasks === 3)
+
+ // Register one writer task
+ val location1 = StreamingShuffleTaskLocation("executor1", "host1", 8000)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0, location1)
+
+ // Should return partial locations
+ val response2 = tracker.getAvailableShuffleWriterTaskLocations(0)
+ assert(response2.isDefined)
+ assert(response2.get.shuffleTaskLocations.size === 1)
+ assert(response2.get.numShuffleWriterTasks === 3)
+ assert(response2.get.shuffleTaskLocations(0L) === location1)
+
+ // Register remaining writer tasks
+ val location2 = StreamingShuffleTaskLocation("executor2", "host2", 8001)
+ val location3 = StreamingShuffleTaskLocation("executor3", "host3", 8002)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 1, location2)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 2, location3)
+
+ // Should return all locations
+ val response3 = tracker.getAvailableShuffleWriterTaskLocations(0)
+ assert(response3.isDefined)
+ assert(response3.get.shuffleTaskLocations.size === 3)
+ assert(response3.get.numShuffleWriterTasks === 3)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - unregister shuffle") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ // Register a shuffle and a writer task
+ tracker.registerShuffle(shuffleId = 0, numMaps = 1, numReduces = 1, jobId
= 1)
+ val location = StreamingShuffleTaskLocation("executor1", "host1", 8000)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0, location)
+
+ // Verify it exists
+ assert(tracker.getShuffleInfo(0).isDefined)
+ assert(tracker.getAllShuffleWriterTaskLocations(0).isDefined)
+
+ // Unregister shuffle
+ tracker.unregisterShuffle(0)
+
+ // Verify it's removed
+ assert(tracker.getShuffleInfo(0).isEmpty)
+ assert(tracker.getAllShuffleWriterTaskLocations(0).isEmpty)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - register writer before shuffle
fails") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ // Try to register writer task without registering shuffle first
+ val location = StreamingShuffleTaskLocation("executor1", "host1", 8000)
+ val success = tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0,
location)
+
+ // Should fail
+ assert(!success)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - concurrent registration") {
+ val conf = new SparkConf(false)
+ .set(SHUFFLE_MAPOUTPUT_DISPATCHER_NUM_THREADS, 4)
+ val tracker = newTrackerMaster(conf)
+
+ // Register a shuffle with many mappers
+ val numMaps = 100
+ tracker.registerShuffle(shuffleId = 0, numMaps = numMaps, numReduces = 10,
jobId = 1)
+
+ // Register all writer tasks concurrently
+ val threads = (0 until numMaps).map { mapId =>
+ new Thread {
+ override def run(): Unit = {
+ val location = StreamingShuffleTaskLocation(
+ s"executor$mapId",
+ s"host$mapId",
+ 8000 + mapId)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = mapId,
location)
+ }
+ }
+ }
+
+ threads.foreach(_.start())
+ threads.foreach(_.join())
+
+ // Verify all were registered
+ val allLocations = tracker.getAllShuffleWriterTaskLocations(0)
+ assert(allLocations.isDefined)
+ assert(allLocations.get.size === numMaps)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - multiple shuffles") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ // Register multiple shuffles
+ tracker.registerShuffle(shuffleId = 0, numMaps = 2, numReduces = 2, jobId
= 1)
+ tracker.registerShuffle(shuffleId = 1, numMaps = 3, numReduces = 3, jobId
= 1)
+
+ // Register writer tasks for both shuffles
+ val location00 = StreamingShuffleTaskLocation("executor1", "host1", 8000)
+ val location01 = StreamingShuffleTaskLocation("executor2", "host2", 8001)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0, location00)
+ tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 1, location01)
+
+ val location10 = StreamingShuffleTaskLocation("executor3", "host3", 8002)
+ val location11 = StreamingShuffleTaskLocation("executor4", "host4", 8003)
+ val location12 = StreamingShuffleTaskLocation("executor5", "host5", 8004)
+ tracker.registerShuffleWriterTask(shuffleId = 1, mapId = 0, location10)
+ tracker.registerShuffleWriterTask(shuffleId = 1, mapId = 1, location11)
+ tracker.registerShuffleWriterTask(shuffleId = 1, mapId = 2, location12)
+
+ // Verify both shuffles have correct locations
+ val shuffle0Locations = tracker.getAllShuffleWriterTaskLocations(0)
+ assert(shuffle0Locations.isDefined)
+ assert(shuffle0Locations.get.size === 2)
+
+ val shuffle1Locations = tracker.getAllShuffleWriterTaskLocations(1)
+ assert(shuffle1Locations.isDefined)
+ assert(shuffle1Locations.get.size === 3)
+ }
+
+ test("get available writer task locations through worker RPC") {
+ val master = newTrackerMaster()
+ val worker = newTrackerWorker()
+
+ val rpcEnv = createRpcEnv("test")
+ val rpcEndpoint = rpcEnv.setupEndpoint(
+ StreamingShuffleOutputTracker.ENDPOINT_NAME,
+ new StreamingShuffleOutputTrackerMasterEndpoint(rpcEnv, master, conf))
+
+ master.trackerEndpoint = rpcEndpoint
+ worker.trackerEndpoint = rpcEndpoint
+
+ val shuffleId = 0
+ val numMaps = 2
+ val location = StreamingShuffleTaskLocation("executor-1", "host-1", 0)
+
+ master.registerShuffle(shuffleId, numMaps = numMaps, numReduces = 2, jobId
= 0)
+ worker.registerShuffleWriterTask(shuffleId, 0, location)
+
+ val response = worker.getAvailableShuffleWriterTaskLocations(shuffleId)
+ assert(response.isDefined)
+ assert(response.get.shuffleTaskLocations.size === 1)
+ assert(response.get.numShuffleWriterTasks === numMaps)
+ assert(response.get.shuffleTaskLocations(0L) === location)
+ }
+
+ test("get available writer task locations for shuffle that doesn't exist
through worker RPC") {
+ val master = newTrackerMaster()
+ val worker = newTrackerWorker()
+
+ val rpcEnv = createRpcEnv("test")
+ val rpcEndpoint = rpcEnv.setupEndpoint(
+ StreamingShuffleOutputTracker.ENDPOINT_NAME,
+ new StreamingShuffleOutputTrackerMasterEndpoint(rpcEnv, master, conf))
+
+ master.trackerEndpoint = rpcEndpoint
+ worker.trackerEndpoint = rpcEndpoint
+
+ worker.getAvailableShuffleWriterTaskLocations(0) should be(None)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - re-registering same mapId
overwrites location") {
+ val conf = new SparkConf(false)
+ val tracker = newTrackerMaster(conf)
+
+ tracker.registerShuffle(shuffleId = 0, numMaps = 1, numReduces = 1, jobId
= 1)
+
+ val location1 = StreamingShuffleTaskLocation("executor1", "host1", 8000)
+ assert(tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0,
location1))
+
+ // Simulate a task retry: same mapId, different location.
+ val location2 = StreamingShuffleTaskLocation("executor2", "host2", 8001)
+ assert(tracker.registerShuffleWriterTask(shuffleId = 0, mapId = 0,
location2))
+
+ // The newer registration should overwrite the older one.
+ val allLocations = tracker.getAllShuffleWriterTaskLocations(0)
+ assert(allLocations.isDefined)
+ assert(allLocations.get.size === 1)
+ assert(allLocations.get(0L) === location2)
+ }
+
+ test("StreamingShuffleOutputTrackerMaster - " +
+ "concurrent register/unregister leaves no orphan taskLocations") {
+ val conf = new SparkConf(false)
+ .set(SHUFFLE_MAPOUTPUT_DISPATCHER_NUM_THREADS, 4)
+ val tracker = newTrackerMaster(conf)
+
+ val numShuffles = 200
+ val numMappersPerShuffle = 50
+ // Use a CyclicBarrier so all 2*numShuffles threads release simultaneously,
+ // maximizing the chance of hitting the race window between
+ // registerShuffleWriterTask's outer containsKey check and its
taskLocations.compute.
+ val barrier = new CyclicBarrier(2 * numShuffles)
+
+ // Pre-register all shuffles so registerShuffleWriterTask passes its outer
+ // containsKey check and exercises the race window with unregisterShuffle.
+ (0 until numShuffles).foreach { shuffleId =>
+ tracker.registerShuffle(shuffleId, numMappersPerShuffle, 2, jobId = 1)
+ }
+
+ // Spawn one thread per shuffle that registers all its mapper tasks, and
one
+ // thread per shuffle that unregisters it. Barrier-aligned starts maximize
the race.
+ val registerThreads = (0 until numShuffles).map { shuffleId =>
+ new Thread {
+ override def run(): Unit = {
+ barrier.await()
+ (0 until numMappersPerShuffle).foreach { mapId =>
+ tracker.registerShuffleWriterTask(
+ shuffleId,
+ mapId.toLong,
+ StreamingShuffleTaskLocation(s"executor$mapId", s"host$mapId",
8000 + mapId))
+ }
+ }
+ }
+ }
+ val unregisterThreads = (0 until numShuffles).map { shuffleId =>
+ new Thread {
+ override def run(): Unit = {
+ barrier.await()
+ tracker.unregisterShuffle(shuffleId)
+ }
+ }
+ }
+
+ (registerThreads ++ unregisterThreads).foreach(_.start())
+ (registerThreads ++ unregisterThreads).foreach(_.join())
+
+ // Every shuffle was unregistered; taskLocations should contain no orphan
entries.
+ assert(tracker.numShufflesWithTaskLocations === 0,
+ s"Found orphan entries in taskLocations after concurrent
register/unregister; " +
+ s"size = ${tracker.numShufflesWithTaskLocations}")
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]