aboutsummaryrefslogtreecommitdiff
path: root/core/src/test/scala/org/apache/spark/storage/BlockInfoManagerSuite.scala
blob: 9d1bd7ec89bc7dc91b3b363e9904abb68f47f903 (plain) (blame)
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
/*
 * 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.storage

import java.util.Properties

import scala.concurrent.{Await, ExecutionContext, Future}
import scala.language.implicitConversions
import scala.reflect.ClassTag

import org.scalatest.BeforeAndAfterEach
import org.scalatest.time.SpanSugar._

import org.apache.spark.{SparkException, SparkFunSuite, TaskContext, TaskContextImpl}


class BlockInfoManagerSuite extends SparkFunSuite with BeforeAndAfterEach {

  private implicit val ec = ExecutionContext.global
  private var blockInfoManager: BlockInfoManager = _

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    blockInfoManager = new BlockInfoManager()
    for (t <- 0 to 4) {
      blockInfoManager.registerTask(t)
    }
  }

  override protected def afterEach(): Unit = {
    try {
      blockInfoManager = null
    } finally {
      super.afterEach()
    }
  }

  private implicit def stringToBlockId(str: String): BlockId = {
    TestBlockId(str)
  }

  private def newBlockInfo(): BlockInfo = {
    new BlockInfo(StorageLevel.MEMORY_ONLY, ClassTag.Any, tellMaster = false)
  }

  private def withTaskId[T](taskAttemptId: Long)(block: => T): T = {
    try {
      TaskContext.setTaskContext(
        new TaskContextImpl(0, 0, taskAttemptId, 0, null, new Properties, null))
      block
    } finally {
      TaskContext.unset()
    }
  }

  test("initial memory usage") {
    assert(blockInfoManager.size === 0)
  }

  test("get non-existent block") {
    assert(blockInfoManager.get("non-existent-block").isEmpty)
    assert(blockInfoManager.lockForReading("non-existent-block").isEmpty)
    assert(blockInfoManager.lockForWriting("non-existent-block").isEmpty)
  }

  test("basic lockNewBlockForWriting") {
    val initialNumMapEntries = blockInfoManager.getNumberOfMapEntries
    val blockInfo = newBlockInfo()
    withTaskId(1) {
      assert(blockInfoManager.lockNewBlockForWriting("block", blockInfo))
      assert(blockInfoManager.get("block").get eq blockInfo)
      assert(blockInfo.readerCount === 0)
      assert(blockInfo.writerTask === 1)
      // Downgrade lock so that second call doesn't block:
      blockInfoManager.downgradeLock("block")
      assert(blockInfo.readerCount === 1)
      assert(blockInfo.writerTask === BlockInfo.NO_WRITER)
      assert(!blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      assert(blockInfo.readerCount === 2)
      assert(blockInfoManager.get("block").get eq blockInfo)
      assert(blockInfo.readerCount === 2)
      assert(blockInfo.writerTask === BlockInfo.NO_WRITER)
      blockInfoManager.unlock("block")
      blockInfoManager.unlock("block")
      assert(blockInfo.readerCount === 0)
      assert(blockInfo.writerTask === BlockInfo.NO_WRITER)
    }
    assert(blockInfoManager.size === 1)
    assert(blockInfoManager.getNumberOfMapEntries === initialNumMapEntries + 1)
  }

  test("lockNewBlockForWriting blocks while write lock is held, then returns false after release") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
    }
    val lock1Future = Future {
      withTaskId(1) {
        blockInfoManager.lockNewBlockForWriting("block", newBlockInfo())
      }
    }
    val lock2Future = Future {
      withTaskId(2) {
        blockInfoManager.lockNewBlockForWriting("block", newBlockInfo())
      }
    }
    Thread.sleep(300)  // Hack to try to ensure that both future tasks are waiting
    withTaskId(0) {
      blockInfoManager.downgradeLock("block")
    }
    // After downgrading to a read lock, both threads should wake up and acquire the shared
    // read lock.
    assert(!Await.result(lock1Future, 1.seconds))
    assert(!Await.result(lock2Future, 1.seconds))
    assert(blockInfoManager.get("block").get.readerCount === 3)
  }

  test("lockNewBlockForWriting blocks while write lock is held, then returns true after removal") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
    }
    val lock1Future = Future {
      withTaskId(1) {
        blockInfoManager.lockNewBlockForWriting("block", newBlockInfo())
      }
    }
    val lock2Future = Future {
      withTaskId(2) {
        blockInfoManager.lockNewBlockForWriting("block", newBlockInfo())
      }
    }
    Thread.sleep(300)  // Hack to try to ensure that both future tasks are waiting
    withTaskId(0) {
      blockInfoManager.removeBlock("block")
    }
    // After removing the block, the write lock is released. Both threads should wake up but only
    // one should acquire the write lock. The second thread should block until the winner of the
    // write race releases its lock.
    val winningFuture: Future[Boolean] =
      Await.ready(Future.firstCompletedOf(Seq(lock1Future, lock2Future)), 1.seconds)
    assert(winningFuture.value.get.get)
    val winningTID = blockInfoManager.get("block").get.writerTask
    assert(winningTID === 1 || winningTID === 2)
    val losingFuture: Future[Boolean] = if (winningTID == 1) lock2Future else lock1Future
    assert(!losingFuture.isCompleted)
    // Once the writer releases its lock, the blocked future should wake up again and complete.
    withTaskId(winningTID) {
      blockInfoManager.unlock("block")
    }
    assert(!Await.result(losingFuture, 1.seconds))
    assert(blockInfoManager.get("block").get.readerCount === 1)
  }

  test("read locks are reentrant") {
    withTaskId(1) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
      assert(blockInfoManager.lockForReading("block").isDefined)
      assert(blockInfoManager.lockForReading("block").isDefined)
      assert(blockInfoManager.get("block").get.readerCount === 2)
      assert(blockInfoManager.get("block").get.writerTask === BlockInfo.NO_WRITER)
      blockInfoManager.unlock("block")
      assert(blockInfoManager.get("block").get.readerCount === 1)
      blockInfoManager.unlock("block")
      assert(blockInfoManager.get("block").get.readerCount === 0)
    }
  }

  test("multiple tasks can hold read locks") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
    }
    withTaskId(1) { assert(blockInfoManager.lockForReading("block").isDefined) }
    withTaskId(2) { assert(blockInfoManager.lockForReading("block").isDefined) }
    withTaskId(3) { assert(blockInfoManager.lockForReading("block").isDefined) }
    withTaskId(4) { assert(blockInfoManager.lockForReading("block").isDefined) }
    assert(blockInfoManager.get("block").get.readerCount === 4)
  }

  test("single task can hold write lock") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
    }
    withTaskId(1) {
      assert(blockInfoManager.lockForWriting("block").isDefined)
      assert(blockInfoManager.get("block").get.writerTask === 1)
    }
    withTaskId(2) {
      assert(blockInfoManager.lockForWriting("block", blocking = false).isEmpty)
      assert(blockInfoManager.get("block").get.writerTask === 1)
    }
  }

  test("cannot call lockForWriting while already holding a write lock") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
    }
    withTaskId(1) {
      assert(blockInfoManager.lockForWriting("block").isDefined)
      intercept[IllegalStateException] {
        blockInfoManager.lockForWriting("block")
      }
      blockInfoManager.assertBlockIsLockedForWriting("block")
    }
  }

  test("assertBlockIsLockedForWriting throws exception if block is not locked") {
    intercept[SparkException] {
      blockInfoManager.assertBlockIsLockedForWriting("block")
    }
    withTaskId(BlockInfo.NON_TASK_WRITER) {
      intercept[SparkException] {
        blockInfoManager.assertBlockIsLockedForWriting("block")
      }
    }
  }

  test("downgrade lock") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.downgradeLock("block")
    }
    withTaskId(1) {
      assert(blockInfoManager.lockForReading("block").isDefined)
    }
    assert(blockInfoManager.get("block").get.readerCount === 2)
    assert(blockInfoManager.get("block").get.writerTask === BlockInfo.NO_WRITER)
  }

  test("write lock will block readers") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
    }
    val get1Future = Future {
      withTaskId(1) {
        blockInfoManager.lockForReading("block")
      }
    }
    val get2Future = Future {
      withTaskId(2) {
        blockInfoManager.lockForReading("block")
      }
    }
    Thread.sleep(300)  // Hack to try to ensure that both future tasks are waiting
    withTaskId(0) {
      blockInfoManager.unlock("block")
    }
    assert(Await.result(get1Future, 1.seconds).isDefined)
    assert(Await.result(get2Future, 1.seconds).isDefined)
    assert(blockInfoManager.get("block").get.readerCount === 2)
  }

  test("read locks will block writer") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
      blockInfoManager.lockForReading("block")
    }
    val write1Future = Future {
      withTaskId(1) {
        blockInfoManager.lockForWriting("block")
      }
    }
    val write2Future = Future {
      withTaskId(2) {
        blockInfoManager.lockForWriting("block")
      }
    }
    Thread.sleep(300)  // Hack to try to ensure that both future tasks are waiting
    withTaskId(0) {
      blockInfoManager.unlock("block")
    }
    assert(
      Await.result(Future.firstCompletedOf(Seq(write1Future, write2Future)), 1.seconds).isDefined)
    val firstWriteWinner = if (write1Future.isCompleted) 1 else 2
    withTaskId(firstWriteWinner) {
      blockInfoManager.unlock("block")
    }
    assert(Await.result(write1Future, 1.seconds).isDefined)
    assert(Await.result(write2Future, 1.seconds).isDefined)
  }

  test("removing a non-existent block throws IllegalArgumentException") {
    withTaskId(0) {
      intercept[IllegalArgumentException] {
        blockInfoManager.removeBlock("non-existent-block")
      }
    }
  }

  test("removing a block without holding any locks throws IllegalStateException") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
      intercept[IllegalStateException] {
        blockInfoManager.removeBlock("block")
      }
    }
  }

  test("removing a block while holding only a read lock throws IllegalStateException") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
      blockInfoManager.unlock("block")
      assert(blockInfoManager.lockForReading("block").isDefined)
      intercept[IllegalStateException] {
        blockInfoManager.removeBlock("block")
      }
    }
  }

  test("removing a block causes blocked callers to receive None") {
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
    }
    val getFuture = Future {
      withTaskId(1) {
        blockInfoManager.lockForReading("block")
      }
    }
    val writeFuture = Future {
      withTaskId(2) {
        blockInfoManager.lockForWriting("block")
      }
    }
    Thread.sleep(300)  // Hack to try to ensure that both future tasks are waiting
    withTaskId(0) {
      blockInfoManager.removeBlock("block")
    }
    assert(Await.result(getFuture, 1.seconds).isEmpty)
    assert(Await.result(writeFuture, 1.seconds).isEmpty)
  }

  test("releaseAllLocksForTask releases write locks") {
    val initialNumMapEntries = blockInfoManager.getNumberOfMapEntries
    withTaskId(0) {
      assert(blockInfoManager.lockNewBlockForWriting("block", newBlockInfo()))
    }
    assert(blockInfoManager.getNumberOfMapEntries === initialNumMapEntries + 3)
    blockInfoManager.releaseAllLocksForTask(0)
    assert(blockInfoManager.getNumberOfMapEntries === initialNumMapEntries)
  }
}