From b2405eac44e4d047c93fbf11b3eb68bb660a6059 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Thu, 17 Aug 2017 13:50:32 +0200 Subject: [PATCH] Add support to schedule tasks on the EventLoop --- Sources/NIO/Embedded.swift | 4 + Sources/NIO/EventLoop.swift | 154 ++++++++++++++++++++-- Sources/NIO/Selector.swift | 78 +++++++---- Tests/LinuxMain.swift | 1 + Tests/NIOTests/EventLoopTest+XCTest.swift | 33 +++++ Tests/NIOTests/EventLoopTest.swift | 35 +++++ 6 files changed, 267 insertions(+), 38 deletions(-) create mode 100644 Tests/NIOTests/EventLoopTest+XCTest.swift create mode 100644 Tests/NIOTests/EventLoopTest.swift diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift index 47223d951..4aec65cbd 100644 --- a/Sources/NIO/Embedded.swift +++ b/Sources/NIO/Embedded.swift @@ -36,6 +36,10 @@ class EmbeddedEventLoop : EventLoop { return Future(eventLoop: self, checkForPossibleDeadlock: false, result: result) } + func schedule(task: @escaping () throws -> (T), in: TimeAmount) -> Future { + return newFailedFuture(error: EventLoopError.unsupportedOperation) + } + // We're not really running a loop here. Tasks aren't run until run() is called, // at which point we run everything that's been submitted. Anything newly submitted // either gets on that train if it's still moving or diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index eac753a93..53e824ed8 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -14,16 +14,60 @@ import Foundation import ConcurrencyHelpers +import SwiftPriorityQueue +import Dispatch public protocol EventLoop: EventLoopGroup { var inEventLoop: Bool { get } func execute(task: @escaping () -> ()) func submit(task: @escaping () throws-> (T)) -> Future + func schedule(task: @escaping () throws-> (T), in: TimeAmount) -> Future func newPromise() -> Promise func newFailedFuture(error: Error) -> Future func newSucceedFuture(result: T) -> Future } +public struct TimeAmount { + public let nanoseconds: UInt64 + + private init(_ nanoseconds: UInt64) { + self.nanoseconds = nanoseconds + } + + public static func nanoseconds(_ amount: UInt64) -> TimeAmount { + return TimeAmount(amount) + } + + public static func microseconds(_ amount: UInt64) -> TimeAmount { + return TimeAmount(amount * 1000) + } + + public static func milliseconds(_ amount: Int) -> TimeAmount { + return TimeAmount(UInt64(amount) * 1000 * 1000) + } + + public static func seconds(_ amount: Int) -> TimeAmount { + return TimeAmount(UInt64(amount) * 1000 * 1000 * 1000) + } + + public static func minutes(_ amount: Int) -> TimeAmount { + return TimeAmount(UInt64(amount) * 1000 * 1000 * 1000 * 60) + } + + public static func hours(_ amount: Int) -> TimeAmount { + return TimeAmount(UInt64(amount) * 1000 * 1000 * 1000 * 60 * 60) + } +} + +extension TimeAmount: Comparable { + public static func < (lhs: TimeAmount, rhs: TimeAmount) -> Bool { + return lhs.nanoseconds < rhs.nanoseconds + } + public static func == (lhs: TimeAmount, rhs: TimeAmount) -> Bool { + return lhs.nanoseconds == rhs.nanoseconds + } +} + extension EventLoop { public func submit(task: @escaping () throws-> (T)) -> Future { let promise: Promise = newPromise() @@ -97,9 +141,10 @@ private func withAutoReleasePool(_ execute: () throws -> T) rethrows -> T { // TODO: Implement scheduling tasks in the future (a.k.a ScheduledExecutoreService final class SelectableEventLoop : EventLoop { + private let selector: NIO.Selector private var thread: pthread_t? - private var tasks: [() -> ()] + private var scheduledTasks = PriorityQueue(ascending: true) private let tasksLock = Lock() private var closed = false @@ -111,7 +156,6 @@ final class SelectableEventLoop : EventLoop { init() throws { self.selector = try NIO.Selector() - self.tasks = Array() self._iovecs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimit) self._storageRefs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimit) self.iovecs = UnsafeMutableBufferPointer(start: self._iovecs, count: Socket.writevLimit) @@ -146,13 +190,37 @@ final class SelectableEventLoop : EventLoop { return pthread_self() == thread } - func execute(task: @escaping () -> ()) { + func schedule(task: @escaping () throws -> (T), in: TimeAmount) -> Future { + let promise: Promise = newPromise() tasksLock.lock() - tasks.append(task) + scheduledTasks.push(ScheduledTask({() -> () in + do { + promise.succeed(result: try task()) + } catch let err { + promise.fail(error: err) + } + }, `in`)) tasksLock.unlock() - // TODO: What should we do in case of error ? - _ = try? selector.wakeup() + wakeupSelector() + + return promise.futureResult + } + + func execute(task: @escaping () -> ()) { + tasksLock.lock() + scheduledTasks.push(ScheduledTask(task, .microseconds(0))) + tasksLock.unlock() + + wakeupSelector() + } + + private func wakeupSelector() { + do { + try selector.wakeup() + } catch let err { + fatalError("Error during Selector.wakeup(): \(err)"); + } } private func handleEvent(_ ev: IOEvent, channel: C) { @@ -185,6 +253,27 @@ final class SelectableEventLoop : EventLoop { } + private func currentSelectorStrategy() -> SelectorStrategy { + // TODO: Just use an atomic + let scheduled: ScheduledTask? + tasksLock.lock() + scheduled = scheduledTasks.peek() + tasksLock.unlock() + + guard let sched = scheduled else { + // Not tasks to handle so just block + return .block + } + let nanos: UInt64 = sched.readyIn(DispatchTime.now()) + + if nanos == 0 { + // Something is ready to be processed just do a non-blocking select of events. + return .now + } else { + return .blockUntilTimeout(nanoseconds: nanos) + } + } + func run() throws { thread = pthread_self() defer { @@ -195,7 +284,8 @@ final class SelectableEventLoop : EventLoop { // Block until there are events to handle or the selector was woken up /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ try withAutoReleasePool { - try selector.whenReady(strategy: .block) { ev in + + try selector.whenReady(strategy: currentSelectorStrategy()) { ev in switch ev.registration { case .serverSocketChannel(let chan, _): self.handleEvent(ev.io, channel: chan) @@ -209,13 +299,21 @@ final class SelectableEventLoop : EventLoop { while true { // TODO: Better locking tasksLock.lock() - if tasks.isEmpty { + if scheduledTasks.isEmpty { tasksLock.unlock() break } - // Make a copy of the tasks sso we can execute these while not holding the lock anymore - var tasksCopy = Array(tasks) - tasks.removeAll() + var tasksCopy = ContiguousArray<() -> ()>() + + // We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway. + let now = DispatchTime.now() + + // Make a copy of the tasks so we can execute these while not holding the lock anymore + while let task = scheduledTasks.peek(), task.readyIn(now) == 0 { + tasksCopy.append(task.task) + + let _ = scheduledTasks.pop() + } tasksLock.unlock() // Execute all the tasks that were summited @@ -229,6 +327,8 @@ final class SelectableEventLoop : EventLoop { } } } + // This EventLoop was closed so also close the underlying selector. + try self.selector.close() } private func handleEvents(_ channel: C) -> Bool { @@ -250,7 +350,6 @@ final class SelectableEventLoop : EventLoop { } else { try self.submit(task: { () -> (Void) in self.closed = true - try self.selector.close() }).wait() } } @@ -310,6 +409,33 @@ final public class MultiThreadedEventLoopGroup : EventLoopGroup { _ = try loop.close0() } } + +} + +private struct ScheduledTask { + let task: () -> () + private let readyTime: UInt64 + + init(_ task: @escaping () -> (), _ time: TimeAmount) { + self.task = task + self.readyTime = time.nanoseconds + DispatchTime.now().uptimeNanoseconds + } + + func readyIn(_ t: DispatchTime) -> UInt64 { + if readyTime < t.uptimeNanoseconds { + return 0 + } + return readyTime - t.uptimeNanoseconds + } +} + +extension ScheduledTask : Comparable { + public static func < (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool { + return lhs.readyTime < rhs.readyTime + } + public static func == (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool { + return lhs.readyTime == rhs.readyTime + } } extension Int { @@ -320,3 +446,7 @@ extension Int { return -self } } + +public enum EventLoopError: Error { + case unsupportedOperation +} diff --git a/Sources/NIO/Selector.swift b/Sources/NIO/Selector.swift index 7ed7dec2e..816c560db 100644 --- a/Sources/NIO/Selector.swift +++ b/Sources/NIO/Selector.swift @@ -17,6 +17,7 @@ import Foundation #if os(Linux) import CEpoll import CEventfd + import CTimerfd import Glibc #else import Darwin @@ -28,6 +29,7 @@ final class Selector { #if os(Linux) private typealias EventType = epoll_event private let eventfd: Int32 + private let timerfd: Int32 #else private typealias EventType = kevent #endif @@ -72,6 +74,11 @@ final class Selector { eventfd = try wrapSyscall({ $0 >= 0 }, function: "eventfd") { CEventfd.eventfd(0, Int32(EFD_CLOEXEC | EFD_NONBLOCK)) } + + timerfd = try wrapSyscall({ $0 >= 0 }, function: "timerfd_create") { + CTimerfd.timerfd_create(CLOCK_MONOTONIC, Int32(CTimerfd.TFD_CLOEXEC | CTimerfd.TFD_NONBLOCK)); + } + self.open = true var ev = epoll_event() @@ -81,6 +88,13 @@ final class Selector { let _ = try wrapSyscall({ $0 == 0 }, function: "epoll_ctl") { CEpoll.epoll_ctl(self.fd, EPOLL_CTL_ADD, eventfd, &ev) } + + var timerev = epoll_event() + timerev.events = EPOLLIN.rawValue | EPOLLERR.rawValue | EPOLLRDHUP.rawValue | EPOLLET.rawValue + timerev.data.fd = timerfd + let _ = try wrapSyscall({ $0 == 0 }, function: "epoll_ctl") { + CEpoll.epoll_ctl(self.fd, EPOLL_CTL_ADD, timerfd, &timerev) + } #else fd = try wrapSyscall({ $0 >= 0 }, function: "kqueue") { Darwin.kqueue() @@ -105,16 +119,6 @@ final class Selector { } #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: IOEvent) -> UInt32 { // Also merge EPOLLRDHUP in so we can easily detect connection-reset @@ -130,15 +134,14 @@ final class Selector { } } #else - private static func toKQueueTimeSpec(strategy: SelectorStrategy) -> timespec? { + 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: ms / 1000, tv_nsec: (ms % 1000) * 1000000) + case .blockUntilTimeout(let nanoseconds): + return toTimerspec(nanoseconds) } } @@ -304,17 +307,33 @@ final class Selector { } #if os(Linux) - let timeout = Selector.toEpollWaitTimeout(strategy: strategy) - let ready = Int(try wrapSyscall({ $0 >= 0 }, function: "epoll_wait") { - CEpoll.epoll_wait(self.fd, events, Int32(eventsCapacity), timeout) - }) + let ready = try wrapSyscall({ $0 >= 0 }, function: "epoll_wait") { + switch strategy { + case .now: + return Int(CEpoll.epoll_wait(self.fd, events, Int32(eventsCapacity), 0)) + case .blockUntilTimeout(let nanoseconds): + var ts = itimerspec() + ts.it_value = toTimerspec(nanoseconds) + if (CTimerfd.timerfd_settime(timerfd, 0, &ts, nil) < 0) { + return -1 + } + fallthrough + case .block: + return Int(CEpoll.epoll_wait(self.fd, events, Int32(eventsCapacity), -1)) + } + } for i in 0...size) + default: let registration = registrations[Int(ev.data.fd)]! try fn( SelectorEvent( @@ -326,7 +345,7 @@ final class Selector { growEventArrayIfNeeded(ready: ready) #else - let timespec = Selector.toKQueueTimeSpec(strategy: strategy) + let timespec = toKQueueTimeSpec(strategy: strategy) let ready = try wrapSyscall({ $0 >= 0 }, function: "kevent") { if var ts = timespec { @@ -359,6 +378,12 @@ final class Selector { #endif } + private func toTimerspec(_ nanoseconds: UInt64) -> timespec { + let delaySeconds = nanoseconds / 1000000000 + let delayNanoSeconds = nanoseconds - delaySeconds * 1000000000 + return timespec(tv_sec: Int(delaySeconds), tv_nsec: Int(delayNanoSeconds)) + } + func close() throws { guard self.open else { throw IOError(errno: EBADF, reason: "can't close selector as it's not open anymore.") @@ -366,8 +391,9 @@ final class Selector { self.open = false let _ = try wrapSyscall({ $0 >= 0 }, function: "close") { #if os(Linux) - // Ignore closing error for eventfd + // Ignore closing error for eventfd and timerfd let _ = Glibc.close(self.eventfd) + let _ = Glibc.close(self.timerfd) return Int(Glibc.close(self.fd)) #else return Int(Darwin.close(self.fd)) @@ -404,7 +430,7 @@ struct SelectorEvent { if readable { io = writable ? .all : .read } else if writable { - io = .write + io = .write } else { io = .none } @@ -414,7 +440,7 @@ struct SelectorEvent { enum SelectorStrategy { case block - case blockUntilTimeout(ms: Int) + case blockUntilTimeout(nanoseconds: UInt64) case now } diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index e7b7f98fe..15ab0ccf7 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -36,6 +36,7 @@ import XCTest testCase(MessageToByteEncoderTest.allTests), testCase(EchoServerClientTest.allTests), testCase(EmbeddedChannelTest.allTests), + testCase(EventLoopTest.allTests), testCase(FileRegionTest.allTests), testCase(FutureTest.allTests), testCase(AdaptiveRecvByteBufferAllocatorTest.allTests), diff --git a/Tests/NIOTests/EventLoopTest+XCTest.swift b/Tests/NIOTests/EventLoopTest+XCTest.swift new file mode 100644 index 000000000..c3ebd04cb --- /dev/null +++ b/Tests/NIOTests/EventLoopTest+XCTest.swift @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +/// +/// EventLoopTest+XCTest.swift +/// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension EventLoopTest { + + static var allTests : [(String, (EventLoopTest) -> () throws -> Void)] { + return [ + ("testSchedule", testSchedule), + ] + } +} + diff --git a/Tests/NIOTests/EventLoopTest.swift b/Tests/NIOTests/EventLoopTest.swift new file mode 100644 index 000000000..66aba3767 --- /dev/null +++ b/Tests/NIOTests/EventLoopTest.swift @@ -0,0 +1,35 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest +import NIO +import Dispatch + +public class EventLoopTest : XCTestCase { + + public func testSchedule() throws { + let nanos = DispatchTime.now().uptimeNanoseconds + let amount: TimeAmount = .seconds(1) + let eventLoopGroup = try MultiThreadedEventLoopGroup(numThreads: 1) + defer { + let _ = try? eventLoopGroup.close() + } + let value = try eventLoopGroup.next().schedule(task: { + return true + }, in: amount).wait() + + XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= amount.nanoseconds) + XCTAssertTrue(value) + } +}