|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.broadcast |
| 19 | + |
| 20 | +import java.io.ObjectOutputStream |
| 21 | + |
| 22 | +import scala.collection.mutable.ArrayBuffer |
| 23 | +import scala.reflect.ClassTag |
| 24 | +import scala.util.Random |
| 25 | + |
| 26 | +import org.apache.spark._ |
| 27 | +import org.apache.spark.internal.Logging |
| 28 | +import org.apache.spark.storage.{BlockId, BlockResult, BroadcastBlockId, RDDBlockId, StorageLevel} |
| 29 | +import org.apache.spark.util.Utils |
| 30 | + |
| 31 | +/** |
| 32 | + * A BitTorrent-like implementation of [[org.apache.spark.broadcast.Broadcast]]. |
| 33 | + * |
| 34 | + * Different to [[TorrentBroadcast]], this implementation doesn't divide the object to broadcast. |
| 35 | + * In contrast, this implementation performs broadcast on executor side for a RDD. So the results |
| 36 | + * of the RDD does not need to collect first back to the driver before broadcasting. |
| 37 | + * |
| 38 | + * The mechanism is as follows: |
| 39 | + * |
| 40 | + * On each executor, the executor first attempts to fetch the object from its BlockManager. If |
| 41 | + * it doesn not exist, it then uses remote fetches to fetch the blocks of the RDD from other |
| 42 | + * executors if available. Once it gets the blocks, it puts the blocks in its own BlockManager, |
| 43 | + * ready for other executors to fetch from. |
| 44 | + * |
| 45 | + * @tparam T The type of the element of RDD to be broadcasted. |
| 46 | + * @tparam U The type of object transformed from the collection of elements of the RDD. |
| 47 | + * |
| 48 | + * @param numBlocks Total number of blocks this broadcast variable contains. |
| 49 | + * @param rddId The id of the RDD to be broadcasted on executors. |
| 50 | + * @param mode The [[BroadcastMode]] object used to transform the result of RDD to the object which |
| 51 | + * will be stored in the [[BlockManager]]. |
| 52 | + * @param id A unique identifier for the broadcast variable. |
| 53 | + */ |
| 54 | +private[spark] class TorrentExecutorBroadcast[T: ClassTag, U: ClassTag]( |
| 55 | + numBlocks: Int, |
| 56 | + rddId: Int, |
| 57 | + mode: BroadcastMode[T], |
| 58 | + id: Long) extends Broadcast[U](id) with Logging with Serializable { |
| 59 | + |
| 60 | + /** |
| 61 | + * Value of the broadcast object on executors. This is reconstructed by [[readBroadcastBlock]], |
| 62 | + * which builds this value by reading blocks from other executors. |
| 63 | + */ |
| 64 | + @transient private lazy val _value: U = readBroadcastBlock() |
| 65 | + |
| 66 | + private val broadcastId = BroadcastBlockId(id) |
| 67 | + |
| 68 | + override protected def getValue() = { |
| 69 | + _value |
| 70 | + } |
| 71 | + |
| 72 | + /** Fetch torrent blocks from other executors. */ |
| 73 | + private def readBlocks(): Array[T] = { |
| 74 | + // Fetch chunks of data. Note that all these chunks are stored in the BlockManager and reported |
| 75 | + // to the driver, so other executors can pull these chunks from this executor as well. |
| 76 | + val blocks = new Array[Array[T]](numBlocks) |
| 77 | + val bm = SparkEnv.get.blockManager |
| 78 | + |
| 79 | + for (pid <- Random.shuffle(Seq.range(0, numBlocks))) { |
| 80 | + val pieceId = RDDBlockId(rddId, pid) |
| 81 | + // First try getLocalValues because there is a chance that previous attempts to fetch the |
| 82 | + // broadcast blocks have already fetched some of the blocks. In that case, some blocks |
| 83 | + // would be available locally (on this executor). |
| 84 | + bm.getLocalValues(pieceId) match { |
| 85 | + case Some(block: BlockResult) => |
| 86 | + blocks(pid) = block.data.asInstanceOf[Iterator[T]].toArray |
| 87 | + case None => |
| 88 | + bm.get[T](pieceId) match { |
| 89 | + case Some(b) => |
| 90 | + val data = b.data.asInstanceOf[Iterator[T]].toArray |
| 91 | + // We found the block from remote executors' BlockManager, so put the block |
| 92 | + // in this executor's BlockManager. |
| 93 | + if (!bm.putIterator(pieceId, data.toIterator, |
| 94 | + StorageLevel.MEMORY_AND_DISK_SER, tellMaster = true)) { |
| 95 | + throw new SparkException( |
| 96 | + s"Failed to store $pieceId of $broadcastId in local BlockManager") |
| 97 | + } |
| 98 | + blocks(pid) = data |
| 99 | + case None => |
| 100 | + throw new SparkException(s"Failed to get $pieceId of $broadcastId") |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + blocks.flatMap(x => x) |
| 105 | + } |
| 106 | + |
| 107 | + /** |
| 108 | + * Remove all persisted state associated with this Torrent broadcast on the executors. |
| 109 | + */ |
| 110 | + override protected def doUnpersist(blocking: Boolean) { |
| 111 | + TorrentBroadcast.unpersist(id, removeFromDriver = false, blocking) |
| 112 | + } |
| 113 | + |
| 114 | + /** |
| 115 | + * Remove all persisted state associated with this Torrent broadcast on the executors |
| 116 | + * and driver. |
| 117 | + */ |
| 118 | + override protected def doDestroy(blocking: Boolean) { |
| 119 | + TorrentBroadcast.unpersist(id, removeFromDriver = true, blocking) |
| 120 | + } |
| 121 | + |
| 122 | + /** Used by the JVM when serializing this object. */ |
| 123 | + private def writeObject(out: ObjectOutputStream): Unit = Utils.tryOrIOException { |
| 124 | + assertValid() |
| 125 | + out.defaultWriteObject() |
| 126 | + } |
| 127 | + |
| 128 | + private def readBroadcastBlock(): U = Utils.tryOrIOException { |
| 129 | + TorrentBroadcast.synchronized { |
| 130 | + val blockManager = SparkEnv.get.blockManager |
| 131 | + blockManager.getLocalValues(broadcastId).map(_.data.next()) match { |
| 132 | + case Some(x) => |
| 133 | + // Found broadcasted value in local [[BlockManager]]. Use it directly. |
| 134 | + releaseLock(broadcastId) |
| 135 | + x.asInstanceOf[U] |
| 136 | + |
| 137 | + case None => |
| 138 | + // Not found. Going to fetch the chunks of the broadcasted value from executors. |
| 139 | + logInfo("Started reading broadcast variable " + id) |
| 140 | + val startTimeMs = System.currentTimeMillis() |
| 141 | + val rawInput = readBlocks() |
| 142 | + logInfo("Reading broadcast variable " + id + " took" + Utils.getUsedTimeMs(startTimeMs)) |
| 143 | + |
| 144 | + val obj = mode.transform(rawInput.toArray).asInstanceOf[U] |
| 145 | + // Store the merged copy in BlockManager so other tasks on this executor don't |
| 146 | + // need to re-fetch it. |
| 147 | + val storageLevel = StorageLevel.MEMORY_AND_DISK |
| 148 | + if (!blockManager.putSingle(broadcastId, obj, storageLevel, tellMaster = false)) { |
| 149 | + throw new SparkException(s"Failed to store $broadcastId in BlockManager") |
| 150 | + } |
| 151 | + obj |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * If running in a task, register the given block's locks for release upon task completion. |
| 158 | + * Otherwise, if not running in a task then immediately release the lock. |
| 159 | + */ |
| 160 | + private def releaseLock(blockId: BlockId): Unit = { |
| 161 | + val blockManager = SparkEnv.get.blockManager |
| 162 | + Option(TaskContext.get()) match { |
| 163 | + case Some(taskContext) => |
| 164 | + taskContext.addTaskCompletionListener(_ => blockManager.releaseLock(blockId)) |
| 165 | + case None => |
| 166 | + // This should only happen on the driver, where broadcast variables may be accessed |
| 167 | + // outside of running tasks (e.g. when computing rdd.partitions()). In order to allow |
| 168 | + // broadcast variables to be garbage collected we need to free the reference here |
| 169 | + // which is slightly unsafe but is technically okay because broadcast variables aren't |
| 170 | + // stored off-heap. |
| 171 | + blockManager.releaseLock(blockId) |
| 172 | + } |
| 173 | + } |
| 174 | +} |
0 commit comments