-
Notifications
You must be signed in to change notification settings - Fork 1.4k
cancellation handler #4173
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
cancellation handler #4173
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
/* | ||
This source file is part of the Swift.org open source project | ||
|
||
Copyright (c) 2022 Apple Inc. and the Swift project authors | ||
Licensed under Apache License v2.0 with Runtime Library Exception | ||
|
||
See http://swift.org/LICENSE.txt for license information | ||
See http://swift.org/CONTRIBUTORS.txt for Swift project authors | ||
*/ | ||
|
||
import Dispatch | ||
import Foundation | ||
import TSCBasic | ||
|
||
public typealias CancellationHandler = (DispatchTime) throws -> Void | ||
|
||
public class Cancellator: Cancellable { | ||
public typealias RegistrationKey = String | ||
|
||
private let observabilityScope: ObservabilityScope? | ||
private let registry = ThreadSafeKeyValueStore<String, (name: String, handler: CancellationHandler)>() | ||
private let cancelationQueue = DispatchQueue(label: "org.swift.swiftpm.cancellator", qos: .userInteractive, attributes: .concurrent) | ||
private let cancelling = ThreadSafeBox<Bool>(false) | ||
|
||
public init(observabilityScope: ObservabilityScope?) { | ||
self.observabilityScope = observabilityScope | ||
} | ||
|
||
@discardableResult | ||
public func register(name: String, handler: @escaping CancellationHandler) -> RegistrationKey? { | ||
if self.cancelling.get(default: false) { | ||
self.observabilityScope?.emit(debug: "not registering '\(name)' with terminator, termination in progress") | ||
return .none | ||
} | ||
let key = UUID().uuidString | ||
self.observabilityScope?.emit(debug: "registering '\(name)' with terminator") | ||
self.registry[key] = (name: name, handler: handler) | ||
return key | ||
} | ||
|
||
@discardableResult | ||
public func register(name: String, handler: Cancellable) -> RegistrationKey? { | ||
self.register(name: name, handler: handler.cancel(deadline:)) | ||
} | ||
|
||
@discardableResult | ||
public func register(name: String, handler: @escaping () throws -> Void) -> RegistrationKey? { | ||
self.register(name: name, handler: { _ in try handler() }) | ||
} | ||
|
||
public func register(_ process: TSCBasic.Process) -> RegistrationKey? { | ||
self.register(name: "\(process.arguments.joined(separator: " "))", handler: process.terminate) | ||
} | ||
|
||
public func deregister(_ key: RegistrationKey) { | ||
self.registry[key] = nil | ||
} | ||
|
||
public func cancel(deadline: DispatchTime) throws -> Void { | ||
self._cancel(deadline: deadline) | ||
} | ||
|
||
// marked internal for testing | ||
@discardableResult | ||
internal func _cancel(deadline: DispatchTime? = .none)-> Int { | ||
self.cancelling.put(true) | ||
|
||
self.observabilityScope?.emit(info: "starting cancellation cycle with \(self.registry.count) cancellation handlers registered") | ||
|
||
let deadline = deadline ?? .now() + .seconds(30) | ||
// deadline for individual handlers set slightly before overall deadline | ||
let delta: DispatchTimeInterval = .nanoseconds(abs(deadline.distance(to: .now()).nanoseconds() ?? 0) / 5) | ||
let handlersDeadline = deadline - delta | ||
|
||
let cancellationHandlers = self.registry.get() | ||
let cancelled = ThreadSafeArrayStore<String>() | ||
let group = DispatchGroup() | ||
for (_, (name, handler)) in cancellationHandlers { | ||
self.cancelationQueue.async(group: group) { | ||
do { | ||
self.observabilityScope?.emit(debug: "cancelling '\(name)'") | ||
try handler(handlersDeadline) | ||
cancelled.append(name) | ||
} catch { | ||
self.observabilityScope?.emit(warning: "failed cancelling '\(name)': \(error)") | ||
} | ||
} | ||
} | ||
|
||
if case .timedOut = group.wait(timeout: deadline) { | ||
self.observabilityScope?.emit(warning: "timeout waiting for cancellation with \(cancellationHandlers.count - cancelled.count) cancellation handlers remaining") | ||
} else { | ||
self.observabilityScope?.emit(info: "cancellation cycle completed successfully") | ||
} | ||
|
||
self.cancelling.put(false) | ||
|
||
return cancelled.count | ||
} | ||
} | ||
|
||
public protocol Cancellable { | ||
func cancel(deadline: DispatchTime) throws -> Void | ||
} | ||
|
||
public struct CancellationError: Error, CustomStringConvertible { | ||
public let description = "Operation cancelled" | ||
|
||
public init() {} | ||
} | ||
|
||
extension TSCBasic.Process { | ||
fileprivate func terminate(timeout: DispatchTime) { | ||
// send graceful shutdown signal | ||
self.signal(SIGINT) | ||
|
||
// start a thread to see if we need to terminate more forcibly | ||
let forceKillSemaphore = DispatchSemaphore(value: 0) | ||
let forceKillThread = TSCBasic.Thread { | ||
if case .timedOut = forceKillSemaphore.wait(timeout: timeout) { | ||
// send a force-kill signal | ||
#if os(Windows) | ||
self.signal(SIGTERM) | ||
#else | ||
self.signal(SIGKILL) | ||
#endif | ||
} | ||
} | ||
forceKillThread.start() | ||
_ = try? self.waitUntilExit() | ||
forceKillSemaphore.signal() // let the force-kill thread know we do not need it any more | ||
// join the force-kill thread thread so we don't exit before everything terminates | ||
forceKillThread.join() | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Originally was named "terminator" which is cute but less accurate. Happy to take suggestions for a nicer name