|
| 1 | +/* |
| 2 | + This source file is part of the Swift.org open source project |
| 3 | + |
| 4 | + Copyright (c) 2022 Apple Inc. and the Swift project authors |
| 5 | + Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | + |
| 7 | + See http://swift.org/LICENSE.txt for license information |
| 8 | + See http://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | + */ |
| 10 | + |
| 11 | +import Dispatch |
| 12 | +import Foundation |
| 13 | +import TSCBasic |
| 14 | + |
| 15 | +public typealias CancellationHandler = (DispatchTime) throws -> Void |
| 16 | + |
| 17 | +public class Cancellator: Cancellable { |
| 18 | + public typealias RegistrationKey = String |
| 19 | + |
| 20 | + private let observabilityScope: ObservabilityScope? |
| 21 | + private let registry = ThreadSafeKeyValueStore<String, (name: String, handler: CancellationHandler)>() |
| 22 | + private let cancelationQueue = DispatchQueue(label: "org.swift.swiftpm.cancellator", qos: .userInteractive, attributes: .concurrent) |
| 23 | + private let cancelling = ThreadSafeBox<Bool>(false) |
| 24 | + |
| 25 | + public init(observabilityScope: ObservabilityScope?) { |
| 26 | + self.observabilityScope = observabilityScope |
| 27 | + } |
| 28 | + |
| 29 | + @discardableResult |
| 30 | + public func register(name: String, handler: @escaping CancellationHandler) -> RegistrationKey? { |
| 31 | + if self.cancelling.get(default: false) { |
| 32 | + self.observabilityScope?.emit(debug: "not registering '\(name)' with terminator, termination in progress") |
| 33 | + return .none |
| 34 | + } |
| 35 | + let key = UUID().uuidString |
| 36 | + self.observabilityScope?.emit(debug: "registering '\(name)' with terminator") |
| 37 | + self.registry[key] = (name: name, handler: handler) |
| 38 | + return key |
| 39 | + } |
| 40 | + |
| 41 | + @discardableResult |
| 42 | + public func register(name: String, handler: Cancellable) -> RegistrationKey? { |
| 43 | + self.register(name: name, handler: handler.cancel(deadline:)) |
| 44 | + } |
| 45 | + |
| 46 | + @discardableResult |
| 47 | + public func register(name: String, handler: @escaping () throws -> Void) -> RegistrationKey? { |
| 48 | + self.register(name: name, handler: { _ in try handler() }) |
| 49 | + } |
| 50 | + |
| 51 | + public func register(_ process: TSCBasic.Process) -> RegistrationKey? { |
| 52 | + self.register(name: "\(process.arguments.joined(separator: " "))", handler: process.terminate) |
| 53 | + } |
| 54 | + |
| 55 | + public func deregister(_ key: RegistrationKey) { |
| 56 | + self.registry[key] = nil |
| 57 | + } |
| 58 | + |
| 59 | + public func cancel(deadline: DispatchTime) throws -> Void { |
| 60 | + self._cancel(deadline: deadline) |
| 61 | + } |
| 62 | + |
| 63 | + // marked internal for testing |
| 64 | + @discardableResult |
| 65 | + internal func _cancel(deadline: DispatchTime? = .none)-> Int { |
| 66 | + self.cancelling.put(true) |
| 67 | + |
| 68 | + self.observabilityScope?.emit(info: "starting cancellation cycle with \(self.registry.count) cancellation handlers registered") |
| 69 | + |
| 70 | + let deadline = deadline ?? .now() + .seconds(30) |
| 71 | + // deadline for individual handlers set slightly before overall deadline |
| 72 | + let delta: DispatchTimeInterval = .nanoseconds(abs(deadline.distance(to: .now()).nanoseconds() ?? 0) / 5) |
| 73 | + let handlersDeadline = deadline - delta |
| 74 | + |
| 75 | + let cancellationHandlers = self.registry.get() |
| 76 | + let cancelled = ThreadSafeArrayStore<String>() |
| 77 | + let group = DispatchGroup() |
| 78 | + for (_, (name, handler)) in cancellationHandlers { |
| 79 | + self.cancelationQueue.async(group: group) { |
| 80 | + do { |
| 81 | + self.observabilityScope?.emit(debug: "cancelling '\(name)'") |
| 82 | + try handler(handlersDeadline) |
| 83 | + cancelled.append(name) |
| 84 | + } catch { |
| 85 | + self.observabilityScope?.emit(warning: "failed cancelling '\(name)': \(error)") |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if case .timedOut = group.wait(timeout: deadline) { |
| 91 | + self.observabilityScope?.emit(warning: "timeout waiting for cancellation with \(cancellationHandlers.count - cancelled.count) cancellation handlers remaining") |
| 92 | + } else { |
| 93 | + self.observabilityScope?.emit(info: "cancellation cycle completed successfully") |
| 94 | + } |
| 95 | + |
| 96 | + self.cancelling.put(false) |
| 97 | + |
| 98 | + return cancelled.count |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +public protocol Cancellable { |
| 103 | + func cancel(deadline: DispatchTime) throws -> Void |
| 104 | +} |
| 105 | + |
| 106 | +public struct CancellationError: Error, CustomStringConvertible { |
| 107 | + public let description = "Operation cancelled" |
| 108 | + |
| 109 | + public init() {} |
| 110 | +} |
| 111 | + |
| 112 | +extension TSCBasic.Process { |
| 113 | + fileprivate func terminate(timeout: DispatchTime) { |
| 114 | + // send graceful shutdown signal |
| 115 | + self.signal(SIGINT) |
| 116 | + |
| 117 | + // start a thread to see if we need to terminate more forcibly |
| 118 | + let forceKillSemaphore = DispatchSemaphore(value: 0) |
| 119 | + let forceKillThread = TSCBasic.Thread { |
| 120 | + if case .timedOut = forceKillSemaphore.wait(timeout: timeout) { |
| 121 | + // send a force-kill signal |
| 122 | + #if os(Windows) |
| 123 | + self.signal(SIGTERM) |
| 124 | + #else |
| 125 | + self.signal(SIGKILL) |
| 126 | + #endif |
| 127 | + } |
| 128 | + } |
| 129 | + forceKillThread.start() |
| 130 | + _ = try? self.waitUntilExit() |
| 131 | + forceKillSemaphore.signal() // let the force-kill thread know we do not need it any more |
| 132 | + // join the force-kill thread thread so we don't exit before everything terminates |
| 133 | + forceKillThread.join() |
| 134 | + } |
| 135 | +} |
0 commit comments