diff --git a/Package.swift b/Package.swift index 783f4e12a..3cb21b0a2 100644 --- a/Package.swift +++ b/Package.swift @@ -53,6 +53,8 @@ var targets: [PackageDescription.Target] = [ dependencies: ["NIO", "NIOHTTP1", "NIOFoundationCompat"]), .target(name: "NIOMulticastChat", dependencies: ["NIO"]), + .target(name: "NIOUDPEchoServer", + dependencies: ["NIO"]), .testTarget(name: "NIOTests", dependencies: ["NIO", "NIOFoundationCompat"]), .testTarget(name: "NIOConcurrencyHelpersTests", @@ -78,6 +80,7 @@ let package = Package( .executable(name: "NIOPerformanceTester", targets: ["NIOPerformanceTester"]), .executable(name: "NIOMulticastChat", targets: ["NIOMulticastChat"]), + .executable(name: "NIOUDPEchoServer", targets: ["NIOUDPEchoServer"]), .library(name: "NIO", targets: ["NIO"]), .library(name: "_NIO1APIShims", targets: ["_NIO1APIShims"]), .library(name: "NIOTLS", targets: ["NIOTLS"]), diff --git a/Sources/NIO/ChannelOption.swift b/Sources/NIO/ChannelOption.swift index 77ef92b1b..c1071df8b 100644 --- a/Sources/NIO/ChannelOption.swift +++ b/Sources/NIO/ChannelOption.swift @@ -93,6 +93,36 @@ public struct BacklogOption: ChannelOption { public init() {} } +/// `DatagramVectorReadMessageCountOption` allows users to configure the number of messages to attempt to read in a single syscall on a +/// datagram `Channel`. +/// +/// Some datagram `Channel`s have extremely high datagram throughput. This can occur when the single datagram socket is encapsulating +/// many logical "connections" (e.g. with QUIC) or when the datagram socket is simply serving an enormous number of consumers (e.g. +/// with a public-facing DNS server). In this case the overhead of one syscall per datagram is profoundly limiting. Using this +/// `ChannelOption` allows the `Channel` to read multiple datagrams at once. +/// +/// Note that simply increasing this number will not necessarily bring performance gains and may in fact cause data loss. Any increase +/// to this should be matched by increasing the size of the buffers allocated by the `Channel` `RecvByteBufferAllocator` (as set by +/// `ChannelOption.recvAllocator`) proportionally. For example, to receive 10 messages at a time, set the size of the buffers allocated +/// by the `RecvByteBufferAllocator` to at least 10x the size of the maximum datagram size you wish to receive. +/// +/// Naturally, this option is only valid on datagram channels. +/// +/// This option only works on the following platforms: +/// +/// - Linux +/// - FreeBSD +/// - Android +/// +/// On all other platforms, setting it has no effect. +/// +/// Set this option to 0 to disable vector reads and to use serial reads instead. +public struct DatagramVectorReadMessageCountOption: ChannelOption { + public typealias Value = Int + + public init() { } +} + /// The watermark used to detect when `Channel.isWritable` returns `true` or `false`. public struct WriteBufferWaterMark { /// The low mark setting for a `Channel`. @@ -185,6 +215,9 @@ public struct ChannelOptions { /// - seealso: `AllowRemoteHalfClosureOption`. public static let allowRemoteHalfClosure = AllowRemoteHalfClosureOption() + + /// - seealso: `DatagramVectorReadMessageCountOption` + public static let datagramVectorReadMessageCount = DatagramVectorReadMessageCountOption() } extension ChannelOptions { diff --git a/Sources/NIO/DatagramVectorReadManager.swift b/Sources/NIO/DatagramVectorReadManager.swift new file mode 100644 index 000000000..673402c93 --- /dev/null +++ b/Sources/NIO/DatagramVectorReadManager.swift @@ -0,0 +1,220 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// An object that manages issuing vector reads for datagram channels. +/// +/// Datagram channels have slightly complex read semantics, as high-throughput datagram +/// channels would like to use gathering reads to minimise syscall overhead. This requires +/// managing memory carefully, as well as includes some complex logic that needs to be +/// carefully arranged. For this reason, we store this logic on this separate struct +/// that makes understanding the code a lot simpler. +struct DatagramVectorReadManager { + enum ReadResult { + case some(reads: [AddressedEnvelope], totalSize: Int) + case none + } + + /// The number of messages that will be read in each syscall. + var messageCount: Int { + get { + return self.messageVector.count + } + set { + precondition(newValue >= 0) + self.messageVector.deinitializeAndDeallocate() + self.ioVector.deinitializeAndDeallocate() + self.sockaddrVector.deinitializeAndDeallocate() + + self.messageVector = .allocateAndInitialize(repeating: MMsgHdr(msg_hdr: msghdr(), msg_len: 0), count: newValue) + self.ioVector = .allocateAndInitialize(repeating: IOVector(), count: newValue) + self.sockaddrVector = .allocateAndInitialize(repeating: sockaddr_storage(), count: newValue) + } + } + + /// The vector of MMsgHdrs that are used for the gathering reads. + private var messageVector: UnsafeMutableBufferPointer + + /// The vector of iovec structures needed by msghdr structures. + private var ioVector: UnsafeMutableBufferPointer + + /// The vector of sockaddr structures used for saving addresses. + private var sockaddrVector: UnsafeMutableBufferPointer + + // FIXME(cory): Right now there's no good API for specifying the various parameters of multi-read, especially how + // it should interact with RecvByteBufferAllocator. For now I'm punting on this to see if I can get it working, + // but we should design it back. + fileprivate init(messageVector: UnsafeMutableBufferPointer, ioVector: UnsafeMutableBufferPointer, sockaddrVector: UnsafeMutableBufferPointer) { + self.messageVector = messageVector + self.ioVector = ioVector + self.sockaddrVector = sockaddrVector + } + + /// Performs a socket vector read. + /// + /// This method takes a single byte buffer and segments it into `messageCount` pieces. It then + /// prepares and issues a single recvmmsg syscall, instructing the kernel to write multiple datagrams + /// into that single buffer. Assuming that some datagrams have been successfully read, it then slices + /// that large buffer up into multiple buffers, prepares a series of AddressedEnvelope structures + /// appropriately, and then returns that result to the caller. + /// + /// - warning: If buffer is not at least 1.5kB times `messageCount`, this will almost certainly lead to + /// dropped data. Caution should be taken to ensure that the RecvByteBufferAllocator is allocating an + /// appropriate amount of memory. + /// - warning: Unlike most of the rest of SwiftNIO, the read managers use withVeryUnsafeMutableBytes to + /// obtain a pointer to the entire buffer storage. This is because they assume they own the entire + /// buffer. + /// + /// - parameters: + /// - socket: The underlying socket from which to read. + /// - buffer: The single large buffer into which reads will be written. + func readFromSocket(socket: Socket, buffer: inout ByteBuffer) throws -> ReadResult { + assert(buffer.readerIndex == 0, "Buffer was not cleared between calls to readFromSocket!") + + let messageSize = buffer.capacity / self.messageCount + + let result = try buffer.withVeryUnsafeMutableBytes { bufferPointer -> IOResult in + for i in 0...size), + msg_iov: self.ioVector.baseAddress! + i, + msg_iovlen: 1, // This is weird, but each message gets only one array. Duh. + msg_control: nil, + msg_controllen: 0, + msg_flags: 0) + self.messageVector[i] = MMsgHdr(msg_hdr: msgHdr, msg_len: 0) + + // Note that we don't set up the sockaddr vector: that's because it needs no initialization, + // it's written into by the kernel. + } + + // We've set up our pointers, it's time to get going. We now issue the call. + return try socket.recvmmsg(msgs: self.messageVector) + } + + switch result { + case .wouldBlock(let messagesProcessed): + assert(messagesProcessed == 0) + return .none + case .processed(let messagesProcessed): + return self.buildMessages(messageCount: messagesProcessed, sliceSize: messageSize, buffer: &buffer) + } + } + + /// Destroys this vector read manager, rendering it impossible to re-use. Use of the vector read manager after this is called is not possible. + mutating func deallocate() { + self.messageVector.deinitializeAndDeallocate() + self.ioVector.deinitializeAndDeallocate() + self.sockaddrVector.deinitializeAndDeallocate() + } + + private func buildMessages(messageCount: Int, sliceSize: Int, buffer: inout ByteBuffer) -> ReadResult { + var sliceOffset = buffer.readerIndex + var totalReadSize = 0 + + var results = Array>() + results.reserveCapacity(messageCount) + + for i in 0.. DatagramVectorReadManager { + let messageVector = UnsafeMutableBufferPointer.allocateAndInitialize(repeating: MMsgHdr(msg_hdr: msghdr(), msg_len: 0), count: messageCount) + let ioVector = UnsafeMutableBufferPointer.allocateAndInitialize(repeating: IOVector(), count: messageCount) + let sockaddrVector = UnsafeMutableBufferPointer.allocateAndInitialize(repeating: sockaddr_storage(), count: messageCount) + + return DatagramVectorReadManager(messageVector: messageVector, ioVector: ioVector, sockaddrVector: sockaddrVector) + } +} + + +extension Optional where Wrapped == DatagramVectorReadManager { + /// Updates the message count of the wrapped `DatagramVectorReadManager` to the new value. + /// + /// If the new value is 0 or negative, will destroy the contained vector read manager and set + /// self to `nil`. + mutating func updateMessageCount(_ newCount: Int) { + if newCount > 0 { + if self != nil { + self!.messageCount = newCount + } else { + self = DatagramVectorReadManager.allocate(messageCount: newCount) + } + } else { + if self != nil { + self!.deallocate() + } + self = nil + } + } +} + + +extension UnsafeMutableBufferPointer { + /// Safely creates an UnsafeMutableBufferPointer that can be used by the rest of the code. It ensures that + /// the memory has been bound, allocated, and initialized, such that other Swift code can use it safely without + /// worrying. + fileprivate static func allocateAndInitialize(repeating element: Element, count: Int) -> UnsafeMutableBufferPointer { + let newPointer = UnsafeMutableBufferPointer.allocate(capacity: count) + newPointer.initialize(repeating: element) + return newPointer + } + + /// This safely destroys an UnsafeMutableBufferPointer by deinitializing and deallocating + /// the underlying memory. This ensures that if the pointer contains non-trivial Swift + /// types that no accidental memory leaks will occur, as can happen if UnsafeMutableBufferPointer.deallocate() + /// is used. + fileprivate func deinitializeAndDeallocate() { + guard let basePointer = self.baseAddress else { + // If there's no base address, who cares? + return + } + + // This is the safe way to do things: the moment that deinitialize + // is called, we deallocate. + let rawPointer = basePointer.deinitialize(count: self.count) + rawPointer.deallocate() + } +} diff --git a/Sources/NIO/SocketChannel.swift b/Sources/NIO/SocketChannel.swift index 7ee4ba7f7..b0cb7a2c9 100644 --- a/Sources/NIO/SocketChannel.swift +++ b/Sources/NIO/SocketChannel.swift @@ -491,6 +491,9 @@ final class DatagramChannel: BaseSocketChannel { // Guard against re-entrance of flushNow() method. private let pendingWrites: PendingDatagramWritesManager + /// Support for vector reads, if enabled. + private var vectorReadManager: DatagramVectorReadManager? + // This is `Channel` API so must be thread-safe. override public var isWritable: Bool { return pendingWrites.isWritable @@ -513,6 +516,12 @@ final class DatagramChannel: BaseSocketChannel { } } + deinit { + if var vectorReadManager = self.vectorReadManager { + vectorReadManager.deallocate() + } + } + init(eventLoop: SelectableEventLoop, protocolFamily: Int32) throws { let socket = try Socket(protocolFamily: protocolFamily, type: Posix.SOCK_DGRAM) do { @@ -553,6 +562,13 @@ final class DatagramChannel: BaseSocketChannel { pendingWrites.writeSpinCount = value as! UInt case _ as WriteBufferWaterMarkOption: pendingWrites.waterMark = value as! WriteBufferWaterMark + case _ as DatagramVectorReadMessageCountOption: + // We only support vector reads on these OSes. Let us know if there's another OS with this syscall! + #if os(Linux) || os(FreeBSD) || os(Android) + self.vectorReadManager.updateMessageCount(value as! Int) + #else + break + #endif default: try super.setOption0(option, value: value) } @@ -570,6 +586,8 @@ final class DatagramChannel: BaseSocketChannel { return pendingWrites.writeSpinCount as! Option.Value case _ as WriteBufferWaterMarkOption: return pendingWrites.waterMark as! Option.Value + case _ as DatagramVectorReadMessageCountOption: + return (self.vectorReadManager?.messageCount ?? 0) as! Option.Value default: return try super.getOption0(option) } @@ -590,6 +608,14 @@ final class DatagramChannel: BaseSocketChannel { } override func readFromSocket() throws -> ReadResult { + if self.vectorReadManager != nil { + return try self.vectorReadFromSocket() + } else { + return try self.singleReadFromSocket() + } + } + + private func singleReadFromSocket() throws -> ReadResult { var rawAddress = sockaddr_storage() var rawAddressLength = socklen_t(MemoryLayout.size) var buffer = self.recvAllocator.buffer(allocator: self.allocator) @@ -626,6 +652,52 @@ final class DatagramChannel: BaseSocketChannel { return readResult } + private func vectorReadFromSocket() throws -> ReadResult { + #if os(Linux) || os(FreeBSD) || os(Android) + var buffer = self.recvAllocator.buffer(allocator: self.allocator) + var readResult = ReadResult.none + + readLoop: for i in 1...self.maxMessagesPerRead { + guard self.isOpen else { + throw ChannelError.eof + } + guard let vectorReadManager = self.vectorReadManager else { + // The vector read manager went away. This happens if users unset the vector read manager + // during channelRead. It's unlikely, but we tolerate it by aborting the read early. + break readLoop + } + buffer.clear() + + // This force-unwrap is safe, as we checked whether this is nil in the caller. + let result = try vectorReadManager.readFromSocket(socket: self.socket, buffer: &buffer) + switch result { + case .some(let results, let totalRead): + assert(self.isOpen) + assert(self.isActive) + + let mayGrow = recvAllocator.record(actualReadBytes: totalRead) + readPending = false + + var messageIterator = results.makeIterator() + while self.isActive, let message = messageIterator.next() { + pipeline.fireChannelRead(NIOAny(message)) + } + + if mayGrow && i < maxMessagesPerRead { + buffer = recvAllocator.buffer(allocator: allocator) + } + readResult = .some + case .none: + break readLoop + } + } + + return readResult + #else + fatalError("Cannot perform vector reads on this operating system") + #endif + } + override func shouldCloseOnReadError(_ err: Error) -> Bool { guard let err = err as? IOError else { return true } diff --git a/Sources/NIOUDPEchoServer/main.swift b/Sources/NIOUDPEchoServer/main.swift new file mode 100644 index 000000000..978a20d1b --- /dev/null +++ b/Sources/NIOUDPEchoServer/main.swift @@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// +// 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 NIO + +private final class EchoHandler: ChannelInboundHandler { + public typealias InboundIn = ByteBuffer + public typealias OutboundOut = ByteBuffer + + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + // As we are not really interested getting notified on success or failure we just pass nil as promise to + // reduce allocations. + ctx.write(data, promise: nil) + } + + public func channelReadComplete(ctx: ChannelHandlerContext) { + // As we are not really interested getting notified on success or failure we just pass nil as promise to + // reduce allocations. + ctx.flush() + } + + public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + print("error: ", error) + + // As we are not really interested getting notified on success or failure we just pass nil as promise to + // reduce allocations. + ctx.close(promise: nil) + } +} + +// We don't need more than one thread, as we're creating only one datagram channel. +let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) +var bootstrap = DatagramBootstrap(group: group) + // Specify backlog and enable SO_REUSEADDR + .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + + // Set the handlers that are applied to the bound channel + .channelInitializer { channel in + // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. + channel.pipeline.addHandler(EchoHandler()) + } + +defer { + try! group.syncShutdownGracefully() +} + +var arguments = CommandLine.arguments.dropFirst(0) // just to get an ArraySlice from [String] +if arguments.dropFirst().first == .some("--enable-gathering-reads") { + bootstrap = bootstrap.channelOption(ChannelOptions.datagramVectorReadMessageCount, value: 30) + bootstrap = bootstrap.channelOption(ChannelOptions.recvAllocator, value: FixedSizeRecvByteBufferAllocator(capacity: 30 * 2048)) + arguments = arguments.dropFirst() +} +let arg1 = arguments.dropFirst().first +let arg2 = arguments.dropFirst().dropFirst().first + +let defaultHost = "::1" +let defaultPort = 9999 + +enum BindTo { + case ip(host: String, port: Int) + case unixDomainSocket(path: String) +} + +let bindTarget: BindTo +switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) { +case (.some(let h), _ , .some(let p)): + /* we got two arguments, let's interpret that as host and port */ + bindTarget = .ip(host: h, port: p) +case (.some(let portString), .none, _): + /* couldn't parse as number, expecting unix domain socket path */ + bindTarget = .unixDomainSocket(path: portString) +case (_, .some(let p), _): + /* only one argument --> port */ + bindTarget = .ip(host: defaultHost, port: p) +default: + bindTarget = .ip(host: defaultHost, port: defaultPort) +} + +let channel = try { () -> Channel in + switch bindTarget { + case .ip(let host, let port): + return try bootstrap.bind(host: host, port: port).wait() + case .unixDomainSocket(let path): + return try bootstrap.bind(unixDomainSocketPath: path).wait() + } + }() + +print("Server started and listening on \(channel.localAddress!)") + +// This will never unblock as we don't close the channel +try channel.closeFuture.wait() + +print("Server closed") diff --git a/Tests/NIOTests/DatagramChannelTests+XCTest.swift b/Tests/NIOTests/DatagramChannelTests+XCTest.swift index b47cd5670..8b6e69d18 100644 --- a/Tests/NIOTests/DatagramChannelTests+XCTest.swift +++ b/Tests/NIOTests/DatagramChannelTests+XCTest.swift @@ -39,10 +39,16 @@ extension DatagramChannelTests { ("testRecvFromFailsWithECONNREFUSED", testRecvFromFailsWithECONNREFUSED), ("testRecvFromFailsWithENOMEM", testRecvFromFailsWithENOMEM), ("testRecvFromFailsWithEFAULT", testRecvFromFailsWithEFAULT), + ("testRecvMmsgFailsWithECONNREFUSED", testRecvMmsgFailsWithECONNREFUSED), + ("testRecvMmsgFailsWithENOMEM", testRecvMmsgFailsWithENOMEM), + ("testRecvMmsgFailsWithEFAULT", testRecvMmsgFailsWithEFAULT), ("testSetGetOptionClosedDatagramChannel", testSetGetOptionClosedDatagramChannel), ("testWritesAreAccountedCorrectly", testWritesAreAccountedCorrectly), ("testSettingTwoDistinctChannelOptionsWorksForDatagramChannel", testSettingTwoDistinctChannelOptionsWorksForDatagramChannel), ("testUnprocessedOutboundUserEventFailsOnDatagramChannel", testUnprocessedOutboundUserEventFailsOnDatagramChannel), + ("testBasicMultipleReads", testBasicMultipleReads), + ("testMmsgWillTruncateWithoutChangeToAllocator", testMmsgWillTruncateWithoutChangeToAllocator), + ("testRecvMmsgForMultipleCycles", testRecvMmsgForMultipleCycles), ] } } diff --git a/Tests/NIOTests/DatagramChannelTests.swift b/Tests/NIOTests/DatagramChannelTests.swift index f5c12b4ff..3ca272d17 100644 --- a/Tests/NIOTests/DatagramChannelTests.swift +++ b/Tests/NIOTests/DatagramChannelTests.swift @@ -27,6 +27,20 @@ private extension Channel { return self.eventLoop.makeSucceededFuture([] as [AddressedEnvelope]) }.wait() } + + func readCompleteCount() throws -> Int { + return try self.pipeline.context(name: "ByteReadRecorder").map { context in + return (context.handler as! DatagramReadRecorder).readCompleteCount + }.wait() + } + + func configureForRecvMmsg(messageCount: Int) throws { + let totalBufferSize = messageCount * 2048 + + try self.setOption(ChannelOptions.recvAllocator, value: FixedSizeRecvByteBufferAllocator(capacity: totalBufferSize)).flatMap { + self.setOption(ChannelOptions.datagramVectorReadMessageCount, value: messageCount) + }.wait() + } } /// A class that records datagrams received and forwards them on. @@ -47,6 +61,7 @@ private class DatagramReadRecorder: ChannelInboundHandler { var state: State = .fresh var readWaiters: [Int: EventLoopPromise<[AddressedEnvelope]>] = [:] + var readCompleteCount = 0 func channelRegistered(context: ChannelHandlerContext) { XCTAssertEqual(.fresh, self.state) @@ -71,6 +86,11 @@ private class DatagramReadRecorder: ChannelInboundHandler { context.fireChannelRead(self.wrapInboundOut(data)) } + func channelReadComplete(context: ChannelHandlerContext) { + self.readCompleteCount += 1 + context.fireChannelReadComplete() + } + func notifyForDatagrams(_ count: Int) -> EventLoopFuture<[AddressedEnvelope]> { guard reads.count < count else { return loop!.makeSucceededFuture(.init(reads.prefix(count))) @@ -420,6 +440,84 @@ final class DatagramChannelTests: XCTestCase { XCTAssertEqual(error, ioError.errnoCode) } + public func testRecvMmsgFailsWithECONNREFUSED() throws { + try assertRecvMmsgFails(error: ECONNREFUSED, active: true) + } + + public func testRecvMmsgFailsWithENOMEM() throws { + try assertRecvMmsgFails(error: ENOMEM, active: true) + } + + public func testRecvMmsgFailsWithEFAULT() throws { + try assertRecvMmsgFails(error: EFAULT, active: false) + } + + private func assertRecvMmsgFails(error: Int32, active: Bool) throws { + // Only run this test on platforms that support recvmmsg: the others won't even + // try. + #if os(Linux) || os(FreeBSD) || os(Android) + final class RecvMmsgHandler: ChannelInboundHandler { + typealias InboundIn = AddressedEnvelope + typealias InboundOut = AddressedEnvelope + + private let promise: EventLoopPromise + + init(_ promise: EventLoopPromise) { + self.promise = promise + } + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + XCTFail("Should not receive data but got \(self.unwrapInboundIn(data))") + } + + func errorCaught(context: ChannelHandlerContext, error: Error) { + if let ioError = error as? IOError { + self.promise.succeed(ioError) + } + } + } + + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + class NonRecvMmsgSocket : Socket { + private var error: Int32? + + init(error: Int32) throws { + self.error = error + try super.init(protocolFamily: AF_INET, type: Posix.SOCK_DGRAM) + } + + override func recvmmsg(msgs: UnsafeMutableBufferPointer) throws -> IOResult { + if let err = self.error { + self.error = nil + throw IOError(errnoCode: err, function: "recvfrom") + } + return IOResult.wouldBlock(0) + } + } + let socket = try NonRecvMmsgSocket(error: error) + let channel = try DatagramChannel(socket: socket, eventLoop: group.next() as! SelectableEventLoop) + let promise = channel.eventLoop.makePromise(of: IOError.self) + XCTAssertNoThrow(try channel.register().wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(RecvMmsgHandler(promise)).wait()) + XCTAssertNoThrow(try channel.configureForRecvMmsg(messageCount: 10)) + XCTAssertNoThrow(try channel.bind(to: SocketAddress.init(ipAddress: "127.0.0.1", port: 0)).wait()) + + XCTAssertEqual(active, try channel.eventLoop.submit { + channel.readable() + return channel.isActive + }.wait()) + + if active { + XCTAssertNoThrow(try channel.close().wait()) + } + let ioError = try promise.futureResult.wait() + XCTAssertEqual(error, ioError.errnoCode) + #endif + } + public func testSetGetOptionClosedDatagramChannel() throws { try assertSetGetOptionOnOpenAndClosed(channel: firstChannel, option: ChannelOptions.maxMessagesPerRead, value: 1) } @@ -473,4 +571,96 @@ final class DatagramChannelTests: XCTestCase { } } } + + func testBasicMultipleReads() throws { + XCTAssertNoThrow(try self.secondChannel.configureForRecvMmsg(messageCount: 10)) + + // This test should exercise recvmmsg. + var buffer = self.firstChannel.allocator.buffer(capacity: 256) + buffer.writeStaticString("hello, world!") + let writeData = AddressedEnvelope(remoteAddress: self.secondChannel.localAddress!, data: buffer) + + // We write this in three times. + self.firstChannel.write(NIOAny(writeData), promise: nil) + self.firstChannel.write(NIOAny(writeData), promise: nil) + self.firstChannel.write(NIOAny(writeData), promise: nil) + self.firstChannel.flush() + + let reads = try self.secondChannel.waitForDatagrams(count: 3) + XCTAssertEqual(reads.count, 3) + + for (idx, read) in reads.enumerated() { + XCTAssertEqual(read.data, buffer, "index: \(idx)") + XCTAssertEqual(read.remoteAddress, self.firstChannel.localAddress!, "index: \(idx)") + } + } + + func testMmsgWillTruncateWithoutChangeToAllocator() throws { + // This test validates that setting a small allocator will lead to datagram truncation. + // Right now we don't error on truncation, so this test looks for short receives. + // Setting the recv allocator to 30 bytes forces 3 bytes per message. + // Sadly, this test only truncates for the platforms with recvmmsg support: the rest don't truncate as 30 bytes is sufficient. + XCTAssertNoThrow(try self.secondChannel.configureForRecvMmsg(messageCount: 10)) + XCTAssertNoThrow(try self.secondChannel.setOption(ChannelOptions.recvAllocator, value: FixedSizeRecvByteBufferAllocator(capacity: 30)).wait()) + + var buffer = self.firstChannel.allocator.buffer(capacity: 256) + buffer.writeStaticString("hello, world!") + let writeData = AddressedEnvelope(remoteAddress: self.secondChannel.localAddress!, data: buffer) + + // We write this in three times. + self.firstChannel.write(NIOAny(writeData), promise: nil) + self.firstChannel.write(NIOAny(writeData), promise: nil) + self.firstChannel.write(NIOAny(writeData), promise: nil) + self.firstChannel.flush() + + let reads = try self.secondChannel.waitForDatagrams(count: 3) + XCTAssertEqual(reads.count, 3) + + for (idx, read) in reads.enumerated() { + #if os(Linux) || os(FreeBSD) || os(Android) + XCTAssertEqual(read.data.readableBytes, 3, "index: \(idx)") + #else + XCTAssertEqual(read.data.readableBytes, 13, "index: \(idx)") + #endif + XCTAssertEqual(read.remoteAddress, self.firstChannel.localAddress!, "index: \(idx)") + } + } + + func testRecvMmsgForMultipleCycles() throws { + // The goal of this test is to provide more datagrams than can be received in a single invocation of + // recvmmsg, and to confirm that they all make it through. + // This test is allowed to run on systems without recvmmsg: it just exercises the serial read path. + XCTAssertNoThrow(try self.secondChannel.configureForRecvMmsg(messageCount: 10)) + + // We now turn off autoread. + XCTAssertNoThrow(try self.secondChannel.setOption(ChannelOptions.autoRead, value: false).wait()) + XCTAssertNoThrow(try self.secondChannel.setOption(ChannelOptions.maxMessagesPerRead, value: 3).wait()) + + var buffer = self.firstChannel.allocator.buffer(capacity: 256) + buffer.writeStaticString("data") + let writeData = AddressedEnvelope(remoteAddress: self.secondChannel.localAddress!, data: buffer) + + // Ok, now we're good. Let's queue up a bunch of datagrams. We've configured to receive 10 at a time, so we'll send 30. + for _ in 0..<29 { + self.firstChannel.write(NIOAny(writeData), promise: nil) + } + XCTAssertNoThrow(try self.firstChannel.writeAndFlush(NIOAny(writeData)).wait()) + + // Now we read. Rather than issue many read() calls, we'll turn autoread back on. + XCTAssertNoThrow(try self.secondChannel.setOption(ChannelOptions.autoRead, value: true).wait()) + + // Wait for all 30 datagrams to come through. There should be no loss here, as this is small datagrams on loopback. + let reads = try self.secondChannel.waitForDatagrams(count: 30) + XCTAssertEqual(reads.count, 30) + + // Now we want to count the number of readCompletes. On any platform without recvmmsg, we should have seen 10 or more + // (as max messages per read is 3). On platforms with recvmmsg, we would expect to see + // substantially fewer than 10, and potentially as low as 1. + #if os(Linux) || os(FreeBSD) || os(Android) + XCTAssertLessThan(try assertNoThrowWithValue(self.secondChannel.readCompleteCount()), 10) + XCTAssertGreaterThanOrEqual(try assertNoThrowWithValue(self.secondChannel.readCompleteCount()), 1) + #else + XCTAssertGreaterThanOrEqual(try assertNoThrowWithValue(self.secondChannel.readCompleteCount()), 10) + #endif + } }