diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index 4c440f4d3..84ebcc974 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -18,18 +18,20 @@ import Future public class ServerBootstrap { - private let eventLoop: EventLoop + private let group: EventLoopGroup + private let childGroup: EventLoopGroup private var handler: ChannelHandler? private var childHandler: ChannelHandler? private var options = ChannelOptionStorage() private var childOptions = ChannelOptionStorage() - public init(eventLoop: EventLoop) { - self.eventLoop = eventLoop + public convenience init(group: EventLoopGroup) { + self.init(group: group, childGroup: group) } - public init() throws { - self.eventLoop = try EventLoop() + public init(group: EventLoopGroup, childGroup: EventLoopGroup) { + self.group = group + self.childGroup = childGroup } public func handler(handler: ChannelHandler) -> Self { @@ -52,36 +54,54 @@ public class ServerBootstrap { return self } - public func bind(host: String, port: Int32) -> Future { + public func bind(host: String, port: Int32) -> Future { return bind(local: SocketAddresses.newAddress(for: host, on: port)!) } - - // TODO: At the moment this never returns but once we make the whole thing multi-threaded it will. - public func bind(local: SocketAddress) -> Future { + + public func bind(local: SocketAddress) -> Future { + let evGroup = group + let chEvGroup = childGroup + let opts = options + let eventLoop = evGroup.next() + let h = handler + let chHandler = childHandler + let chOptions = childOptions + + let promise = eventLoop.newPromise(type: Channel.self) do { - let serverChannel = try ServerSocketChannel(eventLoop: eventLoop) + let serverChannel = try ServerSocketChannel(eventLoop: eventLoop, group: chEvGroup) - defer { - _ = serverChannel.close() + func finishServerSetup() { + do { + try opts.applyAll(channel: serverChannel) + let f = serverChannel.register().then(callback: { serverChannel.bind(local: local) }) + f.whenSuccess { + promise.succeed(result: serverChannel) + } + f.cascadeFailure(promise: promise) + } catch let err { + promise.fail(error: err) + } } - if let serverHandler = handler { - try serverChannel.pipeline.add(handler: serverHandler) + if let serverHandler = h { + let future = serverChannel.pipeline.add(handler: serverHandler) + future.whenSuccess { + let f = serverChannel.pipeline.add(handler: AcceptHandler(childHandler: chHandler, childOptions: chOptions)) + f.whenSuccess { finishServerSetup() } + f.cascadeFailure(promise: promise) + } + future.cascadeFailure(promise: promise) + } else { + let f = serverChannel.pipeline.add(handler: AcceptHandler(childHandler: chHandler, childOptions: chOptions)) + f.whenSuccess { finishServerSetup() } + f.cascadeFailure(promise: promise) } - - try serverChannel.pipeline.add(handler: AcceptHandler(childHandler: childHandler, childOptions: childOptions)) - try options.applyAll(channel: serverChannel) - - try serverChannel.register().then(callback: { (void: Void) -> Future in - return serverChannel.bind(local: local) - }).wait() - - - try eventLoop.run() - return eventLoop.newSucceedFuture(result: ()) } catch let err { - return eventLoop.newFailedFuture(type: Void.self, error: err) + promise.fail(error: err) } + + return promise.futureResult } private class AcceptHandler : ChannelHandler { @@ -100,20 +120,24 @@ public class ServerBootstrap { try self.childOptions.applyAll(channel: accepted) if let handler = childHandler { - try accepted.pipeline.add(handler: handler) + let f = accepted.pipeline.add(handler: handler) + f.whenSuccess { ctx.fireChannelRead(data: data) } + f.whenFailure( callback: { err in + self.closeAndFire(ctx: ctx, accepted: accepted, err: err) + }) } - } catch { - // TODO: Log something ? - _ = accepted.close() + } catch let err { + closeAndFire(ctx: ctx, accepted: accepted, err: err) } + } else { + ctx.fireChannelRead(data: data) } - ctx.fireChannelRead(data: data) } - } - - - public func close() throws { - try eventLoop.close() + + private func closeAndFire(ctx: ChannelHandlerContext, accepted: SocketChannel, err: Error) { + _ = accepted.close() + ctx.fireErrorCaught(error: err) + } } } @@ -139,7 +163,6 @@ fileprivate struct ChannelOptionStorage { if !hasSet { self.storage.append((key, (newValue, applier))) } - } func applyAll(channel: Channel) throws { diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index ccb374126..05a0623bf 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -214,6 +214,9 @@ fileprivate class PendingWrites { } } +/* + All operations on SocketChannel are thread-safe + */ public class SocketChannel : Channel { fileprivate init(socket: Socket, eventLoop: EventLoop) throws { try socket.setNonBlocking() @@ -253,11 +256,15 @@ public class SocketChannel : Channel { } } +/* + All operations on ServerSocketChannel are thread-safe + */ public class ServerSocketChannel : Channel { private var backlog: Int32 = 128 + private let group: EventLoopGroup - public init(eventLoop: EventLoop) throws { + public init(eventLoop: EventLoop, group: EventLoopGroup) throws { let serverSocket = try ServerSocket() do { try serverSocket.setNonBlocking() @@ -265,25 +272,29 @@ public class ServerSocketChannel : Channel { let _ = try? serverSocket.close() throw err } + self.group = group super.init(socket: serverSocket, eventLoop: eventLoop) } - override public func setOption(option: T, value: T.OptionType) throws { + override fileprivate func setOption0(option: T, value: T.OptionType) throws { + assert(eventLoop.inEventLoop) if option is BacklogOption { backlog = value as! Int32 } else { - try super.setOption(option: option, value: value) + try super.setOption0(option: option, value: value) } } - override public func getOption(option: T) throws -> T.OptionType { + override fileprivate func getOption0(option: T) throws -> T.OptionType { + assert(eventLoop.inEventLoop) if option is BacklogOption { return backlog as! T.OptionType } - return try super.getOption(option: option) + return try super.getOption0(option: option) } override func bind0(local: SocketAddress, promise: Promise) { + assert(eventLoop.inEventLoop) do { try socket.bind(local: local) try (self.socket as! ServerSocket).listen(backlog: backlog) @@ -305,7 +316,7 @@ public class ServerSocketChannel : Channel { override fileprivate func readFromSocket() throws -> Any? { if let accepted = try (self.socket as! ServerSocket).accept() { do { - return try SocketChannel(socket: accepted, eventLoop: eventLoop) + return try SocketChannel(socket: accepted, eventLoop: group.next()) } catch let err { let _ = try? accepted.close() pipeline.fireErrorCaught(error: err) @@ -320,6 +331,8 @@ public class ServerSocketChannel : Channel { } override func channelRead(data: Any) { + assert(eventLoop.inEventLoop) + if let ch = data as? Channel { let f = ch.register() f.whenFailure(callback: { err in @@ -332,22 +345,41 @@ public class ServerSocketChannel : Channel { } } +/* + All operations on Channel are thread-safe +*/ public class Channel : ChannelOutboundInvoker { - public private(set) var open: Bool = true - public let eventLoop: EventLoop // Visible to access from EventLoop directly let socket: BaseSocket var interestedEvent: InterestedEvent = .none + var closed = false private let pendingWrites: PendingWrites = PendingWrites() - private var readPending: Bool = false + private var readPending = false private var neverRegistered = true private var pendingConnect: Promise? + private let closePromise: Promise + + public var closeFuture: Future { + return closePromise.futureResult + } + + public var open: Bool { + return !closeFuture.fulfilled + } + + public var allocator: ByteBufferAllocator { + if eventLoop.inEventLoop { + return bufferAllocator + } else { + return try! eventLoop.submit{ self.bufferAllocator }.wait() + } + } - public private(set) var allocator: ByteBufferAllocator = ByteBufferAllocator() + private var bufferAllocator: ByteBufferAllocator = ByteBufferAllocator() fileprivate var recvAllocator: RecvByteBufferAllocator = FixedSizeRecvByteBufferAllocator(capacity: 8192) fileprivate var autoRead: Bool = true fileprivate var maxMessagesPerRead: UInt = 1 @@ -355,11 +387,23 @@ public class Channel : ChannelOutboundInvoker { public lazy var pipeline: ChannelPipeline = ChannelPipeline(channel: self) public func setOption(option: T, value: T.OptionType) throws { + if eventLoop.inEventLoop { + try setOption0(option: option, value: value) + } else { + let _ = try eventLoop.submit{ + try self.setOption0(option: option, value: value) + }.wait() + } + } + + fileprivate func setOption0(option: T, value: T.OptionType) throws { + assert(eventLoop.inEventLoop) + if option is SocketOption { let (level, name) = option.value as! (Int, Int32) try socket.setOption(level: Int32(level), name: name, value: value) } else if option is AllocatorOption { - allocator = value as! ByteBufferAllocator + bufferAllocator = value as! ByteBufferAllocator } else if option is RecvAllocatorOption { recvAllocator = value as! RecvByteBufferAllocator } else if option is AutoReadOption { @@ -376,14 +420,24 @@ public class Channel : ChannelOutboundInvoker { fatalError("option \(option) not supported") } } - + public func getOption(option: T) throws -> T.OptionType { + if eventLoop.inEventLoop { + return try getOption0(option: option) + } else { + return try eventLoop.submit{ try self.getOption0(option: option) }.wait() + } + } + + fileprivate func getOption0(option: T) throws -> T.OptionType { + assert(eventLoop.inEventLoop) + if option is SocketOption { let (level, name) = option.value as! (Int32, Int32) return try socket.getOption(level: level, name: name) } if option is AllocatorOption { - return allocator as! T.OptionType + return bufferAllocator as! T.OptionType } if option is RecvAllocatorOption { return recvAllocator as! T.OptionType @@ -410,6 +464,8 @@ public class Channel : ChannelOutboundInvoker { } func readIfNeeded() { + assert(eventLoop.inEventLoop) + if autoRead { read() } @@ -445,6 +501,8 @@ public class Channel : ChannelOutboundInvoker { // Methods invoked from the HeadHandler of the ChannelPipeline func bind0(local: SocketAddress, promise: Promise ) { + assert(eventLoop.inEventLoop) + do { try socket.bind(local: local) promise.succeed(result: ()) @@ -454,7 +512,9 @@ public class Channel : ChannelOutboundInvoker { } func write0(data: Any, promise: Promise) { - guard open else { + assert(eventLoop.inEventLoop) + + guard !closed else { // Channel was already closed, fail the promise and not even queue it. promise.fail(error: ChannelError.closed) return @@ -479,13 +539,15 @@ public class Channel : ChannelOutboundInvoker { } func flush0() { + assert(eventLoop.inEventLoop) + guard !isWritePending() else { return } // This flush is triggered by the user and so we should mark all pending messages as flushed if !flushNow(markFlushCheckpoint: true) { - guard open else { + guard !closed else { return } @@ -495,7 +557,9 @@ public class Channel : ChannelOutboundInvoker { } func startReading0() { - guard open else { + assert(eventLoop.inEventLoop) + + guard !closed else { return } readPending = true @@ -504,7 +568,9 @@ public class Channel : ChannelOutboundInvoker { } func stopReading0() { - guard open else { + assert(eventLoop.inEventLoop) + + guard !closed else { return } unregisterForReadable() @@ -533,14 +599,15 @@ public class Channel : ChannelOutboundInvoker { } func close0(promise: Promise = Promise(), error: Error = ChannelError.closed) { - guard open else { + assert(eventLoop.inEventLoop) + guard !closed else { // Already closed promise.succeed(result: ()) return } + closed = true - open = false safeDeregister() do { @@ -562,9 +629,13 @@ public class Channel : ChannelOutboundInvoker { pendingConnect = nil connectPromise.fail(error: error) } + closePromise.succeed(result: ()) } + func register0(promise: Promise) { + assert(eventLoop.inEventLoop) + // Was not registered yet so do it now. if safeRegister(interested: .read) { neverRegistered = false @@ -574,6 +645,7 @@ public class Channel : ChannelOutboundInvoker { promise.succeed(result: ()) } } + public func register(promise: Promise) -> Future { return pipeline.register(promise: promise) } @@ -581,7 +653,8 @@ public class Channel : ChannelOutboundInvoker { // Methods invoked from the EventLoop itself func writable() { - assert(open) + assert(eventLoop.inEventLoop) + assert(!closed) if finishConnect() { finishWritable() @@ -612,7 +685,9 @@ public class Channel : ChannelOutboundInvoker { } private func finishWritable() { - guard open else { + assert(eventLoop.inEventLoop) + + guard !closed else { return } @@ -626,11 +701,12 @@ public class Channel : ChannelOutboundInvoker { } func readable() { - assert(open) + assert(eventLoop.inEventLoop) + assert(!closed) readPending = false defer { - if open, !readPending { + if !closed, !readPending { unregisterForReadable() } } @@ -665,6 +741,8 @@ public class Channel : ChannelOutboundInvoker { } func connect0(remote: SocketAddress, promise: Promise) { + assert(eventLoop.inEventLoop) + guard pendingConnect == nil else { promise.fail(error: ChannelError.connectPending) return @@ -707,7 +785,7 @@ public class Channel : ChannelOutboundInvoker { } private func safeReregister(interested: InterestedEvent) { - guard open else { + guard !closed else { interestedEvent = .none return } @@ -722,7 +800,7 @@ public class Channel : ChannelOutboundInvoker { } private func safeRegister(interested: InterestedEvent) -> Bool { - guard open else { + guard !closed else { interestedEvent = .none return false } @@ -738,7 +816,7 @@ public class Channel : ChannelOutboundInvoker { } private func flushNow(markFlushCheckpoint: Bool) -> Bool { - while open { + while !closed { if markFlushCheckpoint { pendingWrites.markFlushCheckpoint() } @@ -767,6 +845,7 @@ public class Channel : ChannelOutboundInvoker { fileprivate init(socket: BaseSocket, eventLoop: EventLoop) { self.socket = socket self.eventLoop = eventLoop + self.closePromise = eventLoop.newPromise(type: Void.self) } deinit { diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index 520bfdc71..c881c32da 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -16,6 +16,7 @@ // import Foundation +import Future /** ChannelHandler implementation which enforces back-pressure by stop reading from the remote-peer when it can not write back fast-enough and start reading again @@ -58,8 +59,9 @@ public class BackPressureHandler: ChannelHandler { } public class ChannelInitializer: ChannelHandler { - private let initChannel: (Channel) throws ->() - public init(initChannel: @escaping (Channel) throws ->()) { + private let initChannel: (Channel) -> (Future) + + public init(initChannel: @escaping (Channel) -> (Future)) { self.initChannel = initChannel } @@ -67,9 +69,15 @@ public class ChannelInitializer: ChannelHandler { defer { let _ = ctx.pipeline?.remove(handler: self) } + if let ch = ctx.channel { - try initChannel(ch) + + let f = initChannel(ch) + + f.whenSuccess { ctx.fireChannelRegistered() } + f.whenFailure(callback: { ctx.fireErrorCaught(error: $0) }) + } else { + ctx.fireChannelRegistered() } - ctx.fireChannelRegistered() } } diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 7c37226e7..d581ab3ed 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -16,6 +16,10 @@ import Foundation import Future import Sockets + +/* + All operations on ChannelPipeline are thread-safe + */ public class ChannelPipeline : ChannelInboundInvoker { private var head: ChannelHandlerContext? @@ -25,7 +29,21 @@ public class ChannelPipeline : ChannelInboundInvoker { public unowned let channel: Channel - public func add(name: String? = nil, handler: ChannelHandler, first: Bool = false) throws { + public func add(name: String? = nil, handler: ChannelHandler, first: Bool = false) -> Future { + let promise = eventLoop.newPromise(type: Void.self) + if eventLoop.inEventLoop { + add0(name: name, handler: handler, first: first, promise: promise) + } else { + eventLoop.execute { + self.add0(name: name, handler: handler, first: first, promise: promise) + } + } + return promise.futureResult + } + + public func add0(name: String?, handler: ChannelHandler, first: Bool, promise: Promise) { + assert(eventLoop.inEventLoop) + let ctx = ChannelHandlerContext(name: name ?? nextName(), handler: handler, pipeline: self) if first { let next = head!.next @@ -45,57 +63,91 @@ public class ChannelPipeline : ChannelInboundInvoker { do { try ctx.invokeHandlerAdded() + promise.succeed(result: ()) } catch let err { ctx.prev!.next = ctx.next ctx.next!.prev = ctx.prev + + promise.fail(error: err) + } + } + + public func remove(handler: ChannelHandler) -> Future { + let promise = Promise() + if eventLoop.inEventLoop { + remove0(handler: handler, promise: promise) + } else { + eventLoop.execute { + self.remove0(handler: handler, promise: promise) + } + } + return promise.futureResult + } + + private func remove0(handler: ChannelHandler, promise: Promise) { + assert(eventLoop.inEventLoop) + + guard let ctx = getCtx(equalsFunc: { ctx in + return ctx.handler === handler + }) else { + promise.succeed(result: false) + return + } + + defer { + ctx.prev!.next = ctx.next + ctx.next?.prev = ctx.prev - throw err + // Was removed so set pipeline and prev / next to nil + ctx.pipeline = nil + ctx.prev = nil + ctx.next = nil } - } - - @discardableResult public func remove(handler: ChannelHandler) -> Bool { - guard let ctx = getCtx(equalsFunc: { ctx in - return ctx.handler === handler - }) else { - return false + do { + try ctx.invokeHandlerRemoved() + promise.succeed(result: true) + } catch let err { + promise.fail(error: err) } - ctx.prev!.next = ctx.next - ctx.next?.prev = ctx.prev - return true } - @discardableResult public func remove(name: String) -> Bool { + public func remove(name: String) -> Future { + let promise = Promise() + if eventLoop.inEventLoop { + remove0(name: name, promise: promise) + } else { + eventLoop.execute { + self.remove0(name: name, promise: promise) + } + } + return promise.futureResult + } + + private func remove0(name: String, promise: Promise) { + assert(eventLoop.inEventLoop) + guard let ctx = getCtx(equalsFunc: { ctx in return ctx.name == name }) else { - return false + promise.succeed(result: false) + return } - ctx.prev!.next = ctx.next - ctx.next?.prev = ctx.prev - return true - } - - public func contains(handler: ChannelHandler) -> Bool { - if getCtx(equalsFunc: { ctx in - return ctx.handler === handler - }) == nil { - return false + defer { + ctx.prev!.next = ctx.next + ctx.next?.prev = ctx.prev } - - return true - } - - public func contains(name: String) -> Bool { - if getCtx(equalsFunc: { ctx in - return ctx.name == name - }) == nil { - return false - } - - return true - } + do { + try ctx.invokeHandlerRemoved() + promise.succeed(result: true) + } catch let err { + promise.fail(error: err) + } + } + private func nextName() -> String { + assert(eventLoop.inEventLoop) + let name = "handler\(idx)" idx += 1 return name @@ -103,6 +155,8 @@ public class ChannelPipeline : ChannelInboundInvoker { // Just traverse the pipeline from the start private func getCtx(equalsFunc: (ChannelHandlerContext) -> Bool) -> ChannelHandlerContext? { + assert(eventLoop.inEventLoop) + var ctx = head?.next while let c = ctx { if c === tail { @@ -117,6 +171,8 @@ public class ChannelPipeline : ChannelInboundInvoker { } func removeHandlers() { + assert(eventLoop.inEventLoop) + // The channel was unregistered which means it will not handle any more events. // Remove all handlers now. var ctx = head?.next @@ -139,76 +195,178 @@ public class ChannelPipeline : ChannelInboundInvoker { // Just delegate to the head and tail context public func fireChannelRegistered() { - head!.invokeChannelRegistered() + if eventLoop.inEventLoop { + head!.invokeChannelRegistered() + } else { + eventLoop.execute { + self.head!.invokeChannelRegistered() + } + } } public func fireChannelUnregistered() { - head!.invokeChannelUnregistered() + if eventLoop.inEventLoop { + head!.invokeChannelUnregistered() + } else { + eventLoop.execute { + self.head!.invokeChannelUnregistered() + } + } } public func fireChannelInactive() { - head!.invokeChannelInactive() + if eventLoop.inEventLoop { + head!.invokeChannelInactive() + } else { + eventLoop.execute { + self.head!.invokeChannelInactive() + } + } } public func fireChannelActive() { - head!.invokeChannelActive() + if eventLoop.inEventLoop { + head!.invokeChannelActive() + } else { + eventLoop.execute { + self.head!.invokeChannelActive() + } + } } public func fireChannelRead(data: Any) { - head!.invokeChannelRead(data: data) + if eventLoop.inEventLoop { + head!.invokeChannelRead(data: data) + } else { + eventLoop.execute { + self.head!.invokeChannelRead(data: data) + } + } } public func fireChannelReadComplete() { - head!.invokeChannelReadComplete() + if eventLoop.inEventLoop { + head!.invokeChannelReadComplete() + } else { + eventLoop.execute { + self.head!.invokeChannelReadComplete() + } + } } public func fireChannelWritabilityChanged(writable: Bool) { - head!.invokeChannelWritabilityChanged(writable: writable) + if eventLoop.inEventLoop { + head!.invokeChannelWritabilityChanged(writable: writable) + } else { + eventLoop.execute { + self.head!.invokeChannelWritabilityChanged(writable: writable) + } + } } public func fireUserEventTriggered(event: Any) { - head!.invokeUserEventTriggered(event: event) + if eventLoop.inEventLoop { + head!.invokeUserEventTriggered(event: event) + } else { + eventLoop.execute { + self.head!.invokeUserEventTriggered(event: event) + } + } } public func fireErrorCaught(error: Error) { - head!.invokeErrorCaught(error: error) + if eventLoop.inEventLoop { + head!.invokeErrorCaught(error: error) + } else { + eventLoop.execute { + self.head!.invokeErrorCaught(error: error) + } + } } func close(promise: Promise) -> Future { - tail!.invokeClose(promise: promise) + if eventLoop.inEventLoop { + tail!.invokeClose(promise: promise) + } else { + eventLoop.execute { + self.tail!.invokeClose(promise: promise) + } + } return promise.futureResult } func flush() { - tail!.invokeFlush() + if eventLoop.inEventLoop { + tail!.invokeFlush() + } else { + eventLoop.execute { + self.tail!.invokeFlush() + } + } } func read() { - tail!.invokeRead() + if eventLoop.inEventLoop { + tail!.invokeRead() + } else { + eventLoop.execute { + self.tail!.invokeRead() + } + } } func write(data: Any, promise: Promise) -> Future { - tail!.invokeWrite(data: data, promise: promise) + if eventLoop.inEventLoop { + tail!.invokeWrite(data: data, promise: promise) + } else { + eventLoop.execute { + self.tail!.invokeWrite(data: data, promise: promise) + } + } return promise.futureResult } func writeAndFlush(data: Any, promise: Promise) -> Future { - tail!.invokeWriteAndFlush(data: data, promise: promise) + if eventLoop.inEventLoop { + tail!.invokeWriteAndFlush(data: data, promise: promise) + } else { + eventLoop.execute { + self.tail!.invokeWriteAndFlush(data: data, promise: promise) + } + } return promise.futureResult } func bind(local: SocketAddress, promise: Promise) -> Future { - tail!.invokeBind(local: local, promise: promise) + if eventLoop.inEventLoop { + tail!.invokeBind(local: local, promise: promise) + } else { + eventLoop.execute { + self.tail!.invokeBind(local: local, promise: promise) + } + } return promise.futureResult } func connect(remote: SocketAddress, promise: Promise) -> Future { - tail!.invokeConnect(remote: remote, promise: promise) + if eventLoop.inEventLoop { + tail!.invokeConnect(remote: remote, promise: promise) + } else { + eventLoop.execute { + self.tail!.invokeConnect(remote: remote, promise: promise) + } + } return promise.futureResult } func register(promise: Promise) -> Future { - tail!.invokeRegister(promise: promise) + if eventLoop.inEventLoop { + tail!.invokeRegister(promise: promise) + } else { + eventLoop.execute { + self.tail!.invokeRegister(promise: promise) + } + } return promise.futureResult } @@ -338,7 +496,7 @@ public class ChannelHandlerContext : ChannelInboundInvoker, ChannelOutboundInvok fileprivate var next: ChannelHandlerContext? // marked as weak to not create a reference cycle between this instance and the pipeline - public private(set) weak var pipeline: ChannelPipeline? + public fileprivate(set) weak var pipeline: ChannelPipeline? public var channel: Channel? { return pipeline?.channel @@ -578,12 +736,6 @@ public class ChannelHandlerContext : ChannelInboundInvoker, ChannelOutboundInvok func invokeHandlerRemoved() throws { assert(inEventLoop) - - defer { - pipeline = nil - prev = nil - next = nil - } try handler.handlerRemoved(ctx: self) } diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index 18c18b94a..7ddf71531 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -15,17 +15,20 @@ import Foundation import Future import Sockets +import ConcurrencyHelpers + // TODO: Implement scheduling tasks in the future (a.k.a ScheduledExecutoreService -public class EventLoop { +public class EventLoop : EventLoopGroup { private let selector: Sockets.Selector - private let thread: Thread + private var thread: Thread? private var tasks: [() -> ()] + private let tasksLock = Lock() + private var closed = false init() throws { self.selector = try Sockets.Selector() self.tasks = Array() - thread = Thread.current } func register(channel: Channel) throws { @@ -48,23 +51,36 @@ public class EventLoop { } public func execute(task: @escaping () -> ()) { - assert(inEventLoop) + tasksLock.lock() tasks.append(task) + tasksLock.unlock() + + // TODO: What should we do in case of error ? + _ = try? selector.wakeup() } - public func schedule(task: @escaping () -> (T)) -> Future { + public func submit(task: @escaping () throws-> (T)) -> Future { let promise = Promise() - tasks.append({() -> () in - promise.succeed(result: task()) + + execute(task: {() -> () in + do { + promise.succeed(result: try task()) + } catch let err { + promise.fail(error: err) + } }) - + return promise.futureResult } func run() throws { - assert(inEventLoop) - while true { - // Block until there are events to handle + thread = Thread.current + defer { + // Ensure we reset the running Thread when this methods returns. + thread = nil + } + while !closed { + // Block until there are events to handle or the selector was woken up if let events = try selector.ready(strategy: .block) { for ev in events { @@ -93,21 +109,24 @@ public class EventLoop { } // Ensure we never reach here if the channel is not open anymore. - assert(channel.open) - } - - // Execute all the tasks that were summited - while let task = tasks.first { - task() - - let _ = tasks.removeFirst() + assert(!channel.closed) } } + + // TODO: Better locking + tasksLock.lock() + // Execute all the tasks that were summited + while let task = tasks.first { + task() + + let _ = tasks.removeFirst() + } + tasksLock.unlock() } } private func handleEvents(_ channel: Channel) -> Bool { - if channel.open { + if !channel.closed { return true } do { @@ -119,8 +138,15 @@ public class EventLoop { return false } - public func close() throws { - try self.selector.close() + fileprivate func close() throws { + if inEventLoop { + try self.selector.close() + } else { + try self.submit(task: { () -> (Void) in + self.closed = true + try self.selector.close() + }).wait() + } } public func newPromise(type: T.Type) -> Promise { @@ -138,4 +164,73 @@ public class EventLoop { promise.succeed(result: result) return promise.futureResult } + + public func next() -> EventLoop { + return self + } +} + +/** + Provides an "endless" stream of `EventLoop`s to use. + */ +public protocol EventLoopGroup { + /* + Returns the next `EventLoop` to use. + */ + func next() -> EventLoop +} + +/* + An `EventLoopGroup` which will create multiple `EventLoop`s, each tight to its own `Thread`. + */ +public class MultiThreadedEventLoopGroup : EventLoopGroup { + + private let index = Atomic(value: 0) + + private let eventLoops: [EventLoop] + + public init(numThreads: Int) throws { + var loops: [EventLoop] = [] + for _ in 0.. EventLoop { + return eventLoops[(index.add(1) % eventLoops.count).abs()] + } + + public func close() throws { + for loop in eventLoops { + // TODO: Should we log this somehow or just rethrow the first error ? + _ = try loop.close() + } + } +} + +extension Int { + public func abs() -> Int { + if self >= 0 { + return 0 + } + return -self + } } diff --git a/Sources/NIO/Futures.swift b/Sources/NIO/Futures.swift new file mode 100644 index 000000000..0c9d87e7a --- /dev/null +++ b/Sources/NIO/Futures.swift @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation +import Future + +extension Future { + + public func cascadeFailure(promise: Promise) { + self.whenFailure(callback: { err in + promise.fail(error: err) + }) + } +} diff --git a/Sources/NIOEchoServer/main.swift b/Sources/NIOEchoServer/main.swift index 81a98916c..066f554fe 100644 --- a/Sources/NIOEchoServer/main.swift +++ b/Sources/NIOEchoServer/main.swift @@ -22,9 +22,9 @@ public class EchoHandler: ChannelHandler { let f = ctx.write(data: data) // If the write fails close the channel - f.whenFailure(callback: { error in + /*f.whenFailure(callback: { error in let _ = ctx.close() - }) + })*/ } // Flush it out. This can make use of gathering writes if multiple buffers are pending @@ -33,12 +33,12 @@ public class EchoHandler: ChannelHandler { } public func errorCaught(ctx: ChannelHandlerContext, error: Error) { - print("error: {}", error) + print("error: ", error) let _ = ctx.close() } } - -let bootstrap = try ServerBootstrap() +let group = try MultiThreadedEventLoopGroup(numThreads: 2) +let bootstrap = ServerBootstrap(group: group) // Specify backlog and enable SO_REUSEADDR for the server itself .option(option: ChannelOptions.Backlog, value: 256) .option(option: ChannelOptions.Socket(SOL_SOCKET, SO_REUSEADDR), value: 1) @@ -46,8 +46,9 @@ let bootstrap = try ServerBootstrap() // Set the handlers that are appled to the accepted Channels .handler(childHandler: ChannelInitializer(initChannel: { channel in // Ensure we not read faster then we can write by adding the BackPressureHandler into the pipeline. - try channel.pipeline.add(handler: BackPressureHandler()) - try channel.pipeline.add(handler: EchoHandler()) + return channel.pipeline.add(handler: BackPressureHandler()).then(callback: { v in + return channel.pipeline.add(handler: EchoHandler()) + }) })) // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels @@ -55,8 +56,15 @@ let bootstrap = try ServerBootstrap() .option(childOption: ChannelOptions.Socket(SOL_SOCKET, SO_REUSEADDR), childValue: 1) defer { - _ = try? bootstrap.close() + _ = try? group.close() } -try bootstrap.bind(host: "0.0.0.0", port: 9999).wait() +let channel = try bootstrap.bind(host: "0.0.0.0", port: 9999).wait() + +print("Server started") + +// This will never unblock as we not close the ServerChannel +try channel.closeFuture.wait() + +print("Server closed") diff --git a/Sources/Sockets/IO.swift b/Sources/Sockets/IO.swift index 5c432f343..6c7a39947 100644 --- a/Sources/Sockets/IO.swift +++ b/Sources/Sockets/IO.swift @@ -32,7 +32,7 @@ func ioError(errno: Int32, function: String) -> IOError { func reasonForError(errno: Int32, function: String) -> String { if let strError = String(utf8String: strerror(errno)) { - return "\(function) failed: \(strError)" + return "\(function) failed: errno(\(errno)) \(strError)" } else { return "\(function) failed" } diff --git a/Sources/Sockets/Selector.swift b/Sources/Sockets/Selector.swift index 72bb6c3ab..e4f707eae 100644 --- a/Sources/Sockets/Selector.swift +++ b/Sources/Sockets/Selector.swift @@ -14,40 +14,65 @@ import Foundation - #if os(Linux) import CEpoll + import CEventfd import Glibc #else import Darwin #endif public class Selector { - private let fd: Int32 #if os(Linux) private typealias EventType = epoll_event private let eventsCapacity = 2048 + private let eventfd: Int32 #else private typealias EventType = kevent private let eventsCapacity = 2048 + // TODO: Just reserve 0 is most likely not the best idea, need to think about a better way to handle this. + private static let EvUserIdent = UInt(0) #endif + + private let fd: Int32 private let events: UnsafeMutablePointer - - - var registrations = [Int: Registration]() + private var registrations = [Int: Registration]() public init() throws { + events = UnsafeMutablePointer.allocate(capacity: eventsCapacity) + events.initialize(to: EventType()) + #if os(Linux) fd = try wrapSyscall({ $0 >= 0 }, function: "epoll_create") { CEpoll.epoll_create(128) } + + eventfd = try wrapSyscall({ $0 >= 0 }, function: "eventfd") { + CEventfd.eventfd(0, Int32(EFD_CLOEXEC | EFD_NONBLOCK)) + } + + var ev = epoll_event() + ev.events = Selector.toEpollEvents(interested: .read) + ev.data.fd = eventfd + + let _ = try wrapSyscall({ $0 == 0 }, function: "epoll_ctl") { + CEpoll.epoll_ctl(self.fd, EPOLL_CTL_ADD, eventfd, &ev) + } #else fd = try wrapSyscall({ $0 >= 0 }, function: "kqueue") { Darwin.kqueue() } + + var event = kevent() + event.ident = Selector.EvUserIdent + event.filter = Int16(EVFILT_USER) + event.fflags = UInt32(NOTE_FFNOP) + event.data = 0 + event.udata = nil + event.flags = UInt16(EV_ADD | EV_ENABLE | EV_CLEAR) + + try keventChangeSetOnly(event: &event, numEvents: 1) #endif - events = UnsafeMutablePointer.allocate(capacity: eventsCapacity) - events.initialize(to: EventType()) } deinit { @@ -56,8 +81,57 @@ public class Selector { } -#if !os(Linux) - private func register_kqueue(selectable: Selectable, interested: InterestedEvent) throws { +#if os(Linux) + private static func toEpollWaitTimeout(strategy: SelectorStrategy) -> Int32 { + switch strategy { + case .block: + return -1 + case .now: + return 0 + case .blockUntilTimeout(let ms): + return Int32(ms) + } + } + + private static func toEpollEvents(interested: InterestedEvent) -> UInt32 { + // Also merge EPOLLRDHUP in so we can easily detect connection-reset + switch interested { + case .read: + return EPOLLIN.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue + case .write: + return EPOLLOUT.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue + case .all: + return EPOLLIN.rawValue | EPOLLOUT.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue + case .none: + return EPOLLERR.rawValue | EPOLLRDHUP.rawValue + } + } +#else + private static func toKQueueTimeSpec(strategy: SelectorStrategy) -> timespec? { + switch strategy { + case .block: + return nil + case .now: + return timespec(tv_sec: 0, tv_nsec: 0) + case .blockUntilTimeout(let ms): + // Convert to nanoseconds + return timespec(tv_sec: 0, tv_nsec: ms * 1000 * 1000) + } + } + + private func keventChangeSetOnly(event: UnsafePointer?, numEvents: Int32) throws { + let _ = try wrapSyscall({ $0 >= 0 }, function: "kevent") { + let res = kevent(self.fd, event, numEvents, nil, 0, nil) + if res < 0 && errno == EINTR { + // See https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 + // When kevent() call fails with EINTR error, all changes in the changelist have been applied. + return 0 + } + return Int(res) + } + } + + private func register_kqueue(selectable: Selectable, interested: InterestedEvent, oldInterested: InterestedEvent?) throws { // Allocated on the stack var events = (kevent(), kevent()) @@ -75,77 +149,98 @@ public class Selector { switch interested { case .read: - events.0.flags = UInt16(Int16(EV_ADD)) - events.1.flags = UInt16(Int16(EV_DELETE)) + events.0.flags = UInt16(EV_ADD) + events.1.flags = UInt16(EV_DELETE) case .write: - events.0.flags = UInt16(Int16(EV_DELETE)) - events.1.flags = UInt16(Int16(EV_ADD)) + events.0.flags = UInt16(EV_DELETE) + events.1.flags = UInt16(EV_ADD) case .all: - events.0.flags = UInt16(Int16(EV_ADD)) - events.1.flags = UInt16(Int16(EV_ADD)) + events.0.flags = UInt16(EV_ADD) + events.1.flags = UInt16(EV_ADD) case .none: - events.0.flags = UInt16(Int16(EV_DELETE)) - events.1.flags = UInt16(Int16(EV_DELETE)) + events.0.flags = UInt16(EV_DELETE) + events.1.flags = UInt16(EV_DELETE) } - let _ = try withUnsafeMutableBytes(of: &events) { event_ptr -> Int32 in - precondition(MemoryLayout.size * 2 == event_ptr.count) - let ptr = event_ptr.baseAddress?.bindMemory(to: kevent.self, capacity: 2) - - return try wrapSyscall({ $0 >= 0 }, function: "kevent") { - kevent(self.fd, ptr, 2, ptr, 2, nil) + var offset: Int = 0 + var numEvents: Int32 = 2 + + if let old = oldInterested { + switch old { + case .read: + if events.1.flags == UInt16(EV_DELETE) { + numEvents -= 1 + } + case .write: + if events.0.flags == UInt16(EV_DELETE) { + offset += 1 + numEvents -= 1 + } + case .none: + numEvents = 0 + case .all: + // No need to adjust anything + break + } + } else { + // If its not reregister operation we MUST NOT include EV_DELETE as otherwise kevent will fail with ENOENT. + if events.0.flags == UInt16(EV_DELETE) { + offset += 1 + numEvents -= 1 + } + if events.1.flags == UInt16(EV_DELETE) { + numEvents -= 1 } } - } -#endif - -#if os(Linux) - private func toEpollEvents(interested: InterestedEvent) -> UInt32 { - // Also merge EPOLL_ERR in so we can easily detect connection-reset - switch interested { - case .Read: - return EPOLLIN.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue - case .Write: - return EPOLLOUT.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue - case .All: - return EPOLLIN.rawValue | EPOLLOUT.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue - case .None: - return EPOLLERR.rawValue | EPOLLRDHUP.rawValue + + if numEvents > 0 { + try withUnsafeMutableBytes(of: &events) { event_ptr in + precondition(MemoryLayout.size * 2 == event_ptr.count) + let ptr = event_ptr.baseAddress?.bindMemory(to: kevent.self, capacity: 2) + + try keventChangeSetOnly(event: ptr!.advanced(by: offset), numEvents: numEvents) + } } } #endif public func register(selectable: Selectable, interested: InterestedEvent = .read, attachment: AnyObject? = nil) throws { + assert(registrations[Int(selectable.descriptor)] == nil) #if os(Linux) var ev = epoll_event() - ev.events = toEpollEvents(interested: interested) + ev.events = Selector.toEpollEvents(interested: interested) ev.data.fd = selectable.descriptor let _ = try wrapSyscall({ $0 == 0 }, function: "epoll_ctl") { CEpoll.epoll_ctl(self.fd, EPOLL_CTL_ADD, selectable.descriptor, &ev) } #else - try register_kqueue(selectable: selectable, interested: interested) + try register_kqueue(selectable: selectable, interested: interested, oldInterested: nil) #endif - registrations[Int(selectable.descriptor)] = Registration(selectable: selectable, attachment: attachment) + registrations[Int(selectable.descriptor)] = Registration(selectable: selectable, interested: interested, attachment: attachment) } public func reregister(selectable: Selectable, interested: InterestedEvent) throws { + var reg = registrations[Int(selectable.descriptor)]! + #if os(Linux) var ev = epoll_event() - ev.events = toEpollEvents(interested: interested) + ev.events = Selector.toEpollEvents(interested: interested) ev.data.fd = selectable.descriptor let _ = try wrapSyscall({ $0 == 0 }, function: "epoll_ctl") { CEpoll.epoll_ctl(self.fd, EPOLL_CTL_MOD, selectable.descriptor, &ev) } #else - try register_kqueue(selectable: selectable, interested: interested) + try register_kqueue(selectable: selectable, interested: interested, oldInterested: reg.interested) #endif + reg.interested = interested + registrations[Int(selectable.descriptor)] = reg } public func deregister(selectable: Selectable) throws { - guard registrations.removeValue(forKey: Int(selectable.descriptor)) != nil else { + let reg = registrations.removeValue(forKey: Int(selectable.descriptor)) + guard reg != nil else { return } #if os(Linux) @@ -154,58 +249,43 @@ public class Selector { CEpoll.epoll_ctl(self.fd, EPOLL_CTL_DEL, selectable.descriptor, &ev) } #else - try register_kqueue(selectable: selectable, interested: .none) + try register_kqueue(selectable: selectable, interested: .none, oldInterested: reg!.interested) #endif } -#if os(Linux) - private func toEpollWaitTimeout(strategy: SelectStrategy) -> Int { - switch strategy { - case .block: - return -1 - case .now: - return 0 - case .blockUntilTimeout(let ms): - return ms - } - } -#else - private func toKQueueTimeSpec(strategy: SelectorStrategy) -> timespec? { - switch strategy { - case .block: - return nil - case .now: - return timespec(tv_sec: 0, tv_nsec: 0) - case .blockUntilTimeout(let ms): - // Convert to nanoseconds - return timespec(tv_sec: 0, tv_nsec: ms * 1000 * 1000) - } - } -#endif public func ready(strategy: SelectorStrategy) throws -> Array? { #if os(Linux) - let timeout = toEpollWaitTimeout(strategy: strategy) + let timeout = Selector.toEpollWaitTimeout(strategy: strategy) let ready = try wrapSyscall({ $0 >= 0 }, function: "epoll_wait") { - CEpoll.epoll_wait(self.fd, events, eventsCapacity, timeout) + CEpoll.epoll_wait(self.fd, events, Int32(eventsCapacity), timeout) } if (ready > 0) { var sEvents = [SelectorEvent]() var i = 0; while (i < Int(ready)) { let ev = events[Int(i)] - let registration = registrations[Int(ev.data.fd)]! - sEvents.append( - SelectorEvent( - isReadable: (ev.events & EPOLLIN.rawValue) != 0 || (ev.events & EPOLLERR.rawValue) != 0 || (ev.events & EPOLLRDHUP.rawValue) != 0, - isWritable: (ev.events & EPOLLOUT.rawValue) != 0 || (ev.events & EPOLLERR.rawValue) != 0 || (ev.events & EPOLLRDHUP.rawValue) != 0, - selectable: registration.selectable, attachment: registration.attachment)) + if ev.data.fd == eventfd { + var ev = eventfd_t() + // Consume event + let _ = eventfd_read(eventfd, &ev) + } else { + let registration = registrations[Int(ev.data.fd)]! + sEvents.append( + SelectorEvent( + isReadable: (ev.events & EPOLLIN.rawValue) != 0 || (ev.events & EPOLLERR.rawValue) != 0 || (ev.events & EPOLLRDHUP.rawValue) != 0, + isWritable: (ev.events & EPOLLOUT.rawValue) != 0 || (ev.events & EPOLLERR.rawValue) != 0 || (ev.events & EPOLLRDHUP.rawValue) != 0, + selectable: registration.selectable, attachment: registration.attachment)) + } i += 1 } + if sEvents.isEmpty { + return nil + } return sEvents } #else - let timespec = toKQueueTimeSpec(strategy: strategy) + let timespec = Selector.toKQueueTimeSpec(strategy: strategy) let ready = try wrapSyscall({ $0 >= 0 }, function: "kevent") { if var ts = timespec { @@ -220,10 +300,16 @@ public class Selector { while (i < Int(ready)) { let ev = events[Int(i)] - let registration = registrations[Int(ev.ident)]! - sEvents.append(SelectorEvent(isReadable: Int32(ev.filter) == EVFILT_READ, isWritable: Int32(ev.filter) == EVFILT_WRITE, selectable: registration.selectable, attachment: registration.attachment)) + if ev.ident != Selector.EvUserIdent { + let registration = registrations[Int(ev.ident)]! + sEvents.append(SelectorEvent(isReadable: Int32(ev.filter) == EVFILT_READ, isWritable: Int32(ev.filter) == EVFILT_WRITE, selectable: registration.selectable, attachment: registration.attachment)) + } + i += 1 } + if sEvents.isEmpty { + return nil + } return sEvents } #endif @@ -233,6 +319,8 @@ public class Selector { public func close() throws { let _ = try wrapSyscall({ $0 >= 0 }, function: "close") { #if os(Linux) + // Ignore closing error for eventfd + let _ = Glibc.close(self.eventfd) return Int(Glibc.close(self.fd)) #else return Int(Darwin.close(self.fd)) @@ -240,14 +328,31 @@ public class Selector { } } + public func wakeup() throws { +#if os(Linux) + // TODO: Should we throw an error if it returns != 0 ? + let _ = CEventfd.eventfd_write(eventfd, 1) +#else + var event = kevent() + event.ident = Selector.EvUserIdent + event.filter = Int16(EVFILT_USER) + event.fflags = UInt32(NOTE_TRIGGER | NOTE_FFNOP) + event.data = 0 + event.udata = nil + event.flags = 0 + try keventChangeSetOnly(event: &event, numEvents: 1) +#endif + } } -struct Registration { - public internal(set) var selectable: Selectable - public internal(set) var attachment: AnyObject? +private struct Registration { + internal(set) var interested: InterestedEvent + internal(set) var selectable: Selectable + internal(set) var attachment: AnyObject? - init(selectable: Selectable, attachment: AnyObject?) { + init(selectable: Selectable, interested: InterestedEvent, attachment: AnyObject?) { self.selectable = selectable + self.interested = interested self.attachment = attachment } }