Add support to schedule tasks on the EventLoop

This commit is contained in:
Norman Maurer committed 2017-08-17 13:50:32 +02:00
1 parent 4f91fe3f65
commit b2405eac44
6 files changed
+267 -38

No files matched your search

+4
View File
@@ -36,6 +36,10 @@ class EmbeddedEventLoop : EventLoop {
return Future<T>(eventLoop: self, checkForPossibleDeadlock: false, result: result)
}
func schedule<T>(task: @escaping () throws -> (T), in: TimeAmount) -> Future<T> {
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
+142 -12
View File
@@ -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<T>(task: @escaping () throws-> (T)) -> Future<T>
func schedule<T>(task: @escaping () throws-> (T), in: TimeAmount) -> Future<T>
func newPromise<T>() -> Promise<T>
func newFailedFuture<T>(error: Error) -> Future<T>
func newSucceedFuture<T>(result: T) -> Future<T>
}
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<T>(task: @escaping () throws-> (T)) -> Future<T> {
let promise: Promise<T> = newPromise()
@@ -97,9 +141,10 @@ private func withAutoReleasePool<T>(_ 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<NIORegistration>
private var thread: pthread_t?
private var tasks: [() -> ()]
private var scheduledTasks = PriorityQueue<ScheduledTask>(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<T>(task: @escaping () throws -> (T), in: TimeAmount) -> Future<T> {
let promise: Promise<T> = 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<C: SelectableChannel>(_ 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<C: SelectableChannel>(_ 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
}
+52 -26
View File
@@ -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<R: Registration> {
#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<R: Registration> {
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<R: Registration> {
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<R: Registration> {
}
#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<R: Registration> {
}
}
#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<R: Registration> {
}
#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..<ready {
let ev = events[i]
if ev.data.fd == eventfd {
var ev = eventfd_t()
switch ev.data.fd {
case eventfd:
var val = eventfd_t()
// Consume event
_ = eventfd_read(eventfd, &ev)
} else {
_ = eventfd_read(eventfd, &val)
case timerfd:
// Consume event
var val: UInt = 0
_ = Glibc.read(timerfd, &val, MemoryLayout<UInt>.size)
default:
let registration = registrations[Int(ev.data.fd)]!
try fn(
SelectorEvent(
@@ -326,7 +345,7 @@ final class Selector<R: Registration> {
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<R: Registration> {
#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<R: Registration> {
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<R> {
if readable {
io = writable ? .all : .read
} else if writable {
io = .write
io = .write
} else {
io = .none
}
@@ -414,7 +440,7 @@ struct SelectorEvent<R> {
enum SelectorStrategy {
case block
case blockUntilTimeout(ms: Int)
case blockUntilTimeout(nanoseconds: UInt64)
case now
}
+1
View File
@@ -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),
+33
View File
@@ -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),
]
}
}
+35
View File
@@ -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)
}
}