From 0dc794498f3fdddae76b5949b7ce1bcb16d3dae9 Mon Sep 17 00:00:00 2001 From: Dario Rexin Date: Tue, 30 Jul 2019 09:18:10 -0700 Subject: [PATCH] Fix hanging thread when shutting down an already closed EventLoopGroup (#1085) * Fix hanging thread when shutting down an already closed EventLoopGroup * Generate Linux tests * Remove accidental shutdownLock.unlock * Move dispatching of callbacks out of lock * Use Lock.withLock instead of manual lock/unlock * Remove superfluous lock.unlock --- Sources/NIO/EventLoop.swift | 45 +++++++++++++++++++++++ Tests/NIOTests/EventLoopTest+XCTest.swift | 2 + Tests/NIOTests/EventLoopTest.swift | 33 +++++++++++++++++ 3 files changed, 80 insertions(+) diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index e3e179cc1..e434a4e3c 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -996,10 +996,18 @@ typealias ThreadInitializer = (NIOThread) -> Void /// subclass, a good place to shut it down is the `tearDown` method. public final class MultiThreadedEventLoopGroup: EventLoopGroup { + private enum RunState { + case running + case closing([(DispatchQueue, (Error?) -> Void)]) + case closed(Error?) + } + private static let threadSpecificEventLoop = ThreadSpecificVariable() private let index = Atomic(value: 0) private let eventLoops: [SelectableEventLoop] + private let shutdownLock: Lock = Lock() + private var runState: RunState = .running private static func setupThreadAndEventLoop(name: String, initializer: @escaping ThreadInitializer) -> SelectableEventLoop { let lock = Lock() @@ -1104,6 +1112,27 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { // our shutdown signaling, and then do our cleanup once the DispatchQueue is empty. let g = DispatchGroup() let q = DispatchQueue(label: "nio.shutdownGracefullyQueue", target: queue) + let wasRunning: Bool = self.shutdownLock.withLock { + switch self.runState { + case .running: + self.runState = .closing([]) + return true + case .closing(var callbacks): + callbacks.append((q, handler)) + self.runState = .closing(callbacks) + return false + case .closed(let error): + q.async { + handler(error) + } + return false + } + } + + guard wasRunning else { + return + } + var error: Error? = nil for loop in self.eventLoops { @@ -1125,6 +1154,22 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { } handler(error) + + let callbacks: [(DispatchQueue, (Error?) -> Void)] = self.shutdownLock.withLock { + guard case .closing(let callbacks) = self.runState else { + fatalError("runState was \(self.runState), expected .closing") + } + + self.runState = .closed(error) + + return callbacks + } + + for (q, handler) in callbacks { + q.async { + handler(error) + } + } } } } diff --git a/Tests/NIOTests/EventLoopTest+XCTest.swift b/Tests/NIOTests/EventLoopTest+XCTest.swift index ab4dcba16..e239f8a9b 100644 --- a/Tests/NIOTests/EventLoopTest+XCTest.swift +++ b/Tests/NIOTests/EventLoopTest+XCTest.swift @@ -55,6 +55,8 @@ extension EventLoopTest { ("testCancelledScheduledTasksDoNotHoldOnToRunClosure", testCancelledScheduledTasksDoNotHoldOnToRunClosure), ("testIllegalCloseOfEventLoopFails", testIllegalCloseOfEventLoopFails), ("testSubtractingDeadlineFromPastAndFuturesDeadlinesWorks", testSubtractingDeadlineFromPastAndFuturesDeadlinesWorks), + ("testCallingSyncShutdownGracefullyMultipleTimesShouldNotHang", testCallingSyncShutdownGracefullyMultipleTimesShouldNotHang), + ("testCallingShutdownGracefullyMultipleTimesShouldExecuteAllCallbacks", testCallingShutdownGracefullyMultipleTimesShouldExecuteAllCallbacks), ] } } diff --git a/Tests/NIOTests/EventLoopTest.swift b/Tests/NIOTests/EventLoopTest.swift index 8a53e742c..c1d98e187 100644 --- a/Tests/NIOTests/EventLoopTest.swift +++ b/Tests/NIOTests/EventLoopTest.swift @@ -804,4 +804,37 @@ public final class EventLoopTest : XCTestCase { XCTAssertLessThan(older - newer, .nanoseconds(0)) XCTAssertGreaterThan(newer - older, .nanoseconds(0)) } + + func testCallingSyncShutdownGracefullyMultipleTimesShouldNotHang() throws { + let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) + try elg.syncShutdownGracefully() + try elg.syncShutdownGracefully() + try elg.syncShutdownGracefully() + } + + func testCallingShutdownGracefullyMultipleTimesShouldExecuteAllCallbacks() throws { + let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) + let condition: ConditionLock = ConditionLock(value: 0) + elg.shutdownGracefully { _ in + if condition.lock(whenValue: 0, timeoutSeconds: 1) { + condition.unlock(withValue: 1) + } + } + elg.shutdownGracefully { _ in + if condition.lock(whenValue: 1, timeoutSeconds: 1) { + condition.unlock(withValue: 2) + } + } + elg.shutdownGracefully { _ in + if condition.lock(whenValue: 2, timeoutSeconds: 1) { + condition.unlock(withValue: 3) + } + } + + guard condition.lock(whenValue: 3, timeoutSeconds: 1) else { + XCTFail("Not all shutdown callbacks have been executed") + return + } + condition.unlock() + } }