Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions changelog.d/cluster-service-restart-after-update.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
### A pair's cluster service runs the installed release after `darkbloom update`

- A pair that serves only on its local API (or a Mac whose cluster service
serves alone) kept its cluster service on the earlier release after
`darkbloom update` on both Macs: the service's supervisor does not drain
such a pair for an update, so it never restarted into the installed
release, and `darkbloom restart` restarted only the pair's parts (0.10.12
W1). The parts ran the installed release; the service's own changes, and
the version it reports to the other Mac, waited for the next login.
- Now the first part the service starts from a newer installed release
restarts the service's launchd job once, before it takes a request: the
pair stops on that Mac and starts again on the installed release, as after
a login. Only for the build's own job, only when its supervisor runs an
older release than the part, and once per release in 6 hours; the part's
log says so (`cluster part: this Mac's cluster service still runs …`). It
runs in the parts of this release, so it also covers the update to it.
11 changes: 11 additions & 0 deletions docs/provider/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1753,6 +1753,17 @@ does: a check 5 minutes after it starts, then every 30 minutes; it downloads
while serving, lets your requests finish, then restarts into the release
(`StandaloneServer+AutoUpdate`).

On a `darkbloom cluster` Mac it asks the cluster service to restart into the
release together with the other Mac. A pair that serves only on its local API,
or a Mac whose cluster service serves alone, doesn't drain for that, so its
service keeps the earlier release while the pair sets itself up again on the
installed one. The first part the service starts from the installed release
(`darkbloom start` or `darkbloom cluster link-follower`, started by the
service) then restarts the service's launchd job once, before it takes a
request, and says so in the part's log: `cluster part: this Mac's cluster
service still runs v<earlier> while v<installed> is installed …`
([the coordinated update](./cluster-always-on.md#the-pairs-coordinated-update)).

Until an installed release is promoted (600 s of fresh heartbeats of it from one
provider process), the watchdog counts a failed start for a crash (the job
loaded and the provider gone through the restart grace) and for a provider that
Expand Down
21 changes: 20 additions & 1 deletion docs/provider/cluster-always-on.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,25 @@ The rules each Mac applies to the other's progress are in
otherwise (the leader's local API server, a Mac serving alone) does not, so
the update defers while it serves. A service whose status says so
(`localOnly`, a solo part) gives the release up before downloading it.
`darkbloom update` installs before it asks, so after it ran on both Macs
such a pair sets itself up again on the installed release
(`ClusterOnboardingUpdate`) while the supervisor and the cluster service keep
the release they started with. The first part a service starts from a newer
installed release restarts the service's launchd job once, before it takes a
request (`launchctl kickstart -k`;
`provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterServiceStaleRestart.swift`):
only when its supervisor's state file names an earlier release (compared as
releases: 0.10.9 is older than 0.10.12, and a DevNet build by its number),
the part's parent is the service that supervisor runs, that supervisor is the
process launchd's job runs, and no part asked for this release in the last 6
hours. It asks only once that is recorded (`service-restart-asked.json`); a
record it can't write means no restart. The part's log says `cluster part:
this Mac's cluster service still runs v<earlier> while v<installed> is
installed …`. It then starts nothing for up to 20 s, with SIGTERM and SIGINT
at their default action, so the service's stop ends it at once (a `start`
part otherwise takes both for its own drain); a part that nothing stopped
gets its handlers back and starts as before. From 0.10.12, which also covers
the update to 0.10.12: its parts run 0.10.12.
5. A Mac whose partner has automatic updates off gives the slot's release up
before downloading it. A Mac with automatic updates off reports `disabled`
whenever no cycle runs on it, except for the minute after a cycle that
Expand Down Expand Up @@ -434,7 +453,7 @@ system setting:
| Follower never connects; log shows `Local network prohibited` | **Privacy & Security → Local Network** | Turn on Darkbloom; an ad-hoc build needs this per build |
| A firewall alert after an update | `codesign -dv` on the listening binary | The binary is not Developer-ID signed; install the release build |
| Install or provider log says `permissions: not asked once` | The listed reasons | Install the signed release (a locally built binary is ad-hoc signed and outside `Darkbloom.app`) |
| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone. `failed its start check`: the release did not start on this Mac, which keeps its previous release and does not install that release again; the other Mac follows it back ([a rollback on one Mac](#a-rollback-on-one-mac)), and a newer release updates both. `not following the other Mac's rollback` or `the other Mac still runs`: see [a rollback on one Mac](#a-rollback-on-one-mac) |
| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone; after `darkbloom update` on both Macs it serves the installed release once it set itself up again, and its first part restarts the cluster service into it (`cluster part:` in the part's log; [the coordinated update](#the-pairs-coordinated-update), step 4). `failed its start check`: the release did not start on this Mac, which keeps its previous release and does not install that release again; the other Mac follows it back ([a rollback on one Mac](#a-rollback-on-one-mac)), and a newer release updates both. `not following the other Mac's rollback` or `the other Mac still runs`: see [a rollback on one Mac](#a-rollback-on-one-mac) |

## Developer: a coordinator-paired member as a service

Expand Down
5 changes: 4 additions & 1 deletion docs/provider/two-mac-cluster.md
Original file line number Diff line number Diff line change
Expand Up @@ -1643,7 +1643,10 @@ runs a GPU benchmark beside the model
([device profile](../architecture/inference.md#automatic-local-cluster-batching)).
A pair that serves on the leader's local API, or a Mac that serves alone, is not
drained for an update yet: its update waits while it serves (the log says
`this Mac's part does not drain for an update`).
`this Mac's part does not drain for an update`). After `darkbloom update` on
both Macs, such a pair sets itself up again on the installed release, and its
first part restarts this Mac's cluster service once so the service runs that
release too (from 0.10.12; [the coordinated update](cluster-always-on.md#the-pairs-coordinated-update)).

## When something is in the way

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import Foundation
#if canImport(Darwin)
import Darwin
#endif

/// A cluster service left on an earlier release after an update, restarted once from its part (0.10.12 W1-D2).
///
/// `darkbloom update` installs a release and asks the cluster service's supervisor to restart into it together with
/// the other Mac (`ClusterPairUpdateCycle`). A pair that serves only on its local API, or a Mac whose service serves
/// alone, does not drain for an update (`ClusterPairUpdateCycle.livePart`), so that restart never comes: the supervisor
/// and the service keep running the release they started with, while every part they start runs the installed one.
/// Only a login, a crash of the supervisor or a `launchctl kickstart -k` replaced them. The release that decides an
/// update is the one being updated from, so the installed release can't change that refusal for its own update.
///
/// The part is the first process of the installed release such a Mac runs. At its start, before it holds a request, it
/// compares the release its supervisor runs (`service-supervisor.json`) with its own. When the supervisor's is older,
/// it asks launchd to restart the service's job (`launchctl kickstart -k`): the service stops its part as at a logout,
/// keeping the pair's saved start, and the supervisor starts again from the installed binary. It asks once per
/// installed release within `onceEverySeconds`, and only once that is recorded in the service's folder (`fileName`), so
/// a supervisor that still reported an older release afterwards would never be restarted in a loop.
public enum ClusterServiceStaleRestart {
/// The restart a part asked for, kept in the service's folder.
public struct Asked: Codable, Equatable, Sendable {
public var from: String
public var to: String
public var supervisorPID: Int32
public var at: Double

public init(from: String, to: String, supervisorPID: Int32, at: Double) {
self.from = from; self.to = to; self.supervisorPID = supervisorPID; self.at = at
}
}

public enum Decision: Equatable, Sendable {
case nothing
/// The supervisor runs `from`, older than this part's `to`: its job is restarted.
case restart(from: String, to: String)
}

public static let fileName = "service-restart-asked.json"
/// The same release is asked for at most once in this long.
public static let onceEverySeconds: Double = 6 * 3600

/// - `parentPID`: this part's parent, which must be the service the supervisor runs now (`supervisor.current`).
/// - `jobPID`: the process launchd's job for this build's cluster service runs, which must be the supervisor: a
/// supervisor started from a terminal has no job to restart.
/// - `asked`: the last restart a part asked for.
public static func decide(thisVersion: String, parentPID: Int32, supervisor: ClusterMemberSupervisorState?,
jobPID: Int32?, asked: Asked?, now: Double) -> Decision {
guard let supervisor, olderSupervisor(supervisor, than: thisVersion),
let service = supervisor.current?.pid, service == parentPID,
let jobPID, jobPID == supervisor.supervisorPID else { return .nothing }
if let asked, asked.to == thisVersion, now - asked.at < onceEverySeconds { return .nothing }
return .restart(from: supervisor.version, to: thisVersion)
}

/// Whether the supervisor runs a release older than `thisVersion` (both read as releases; any other text is not).
static func olderSupervisor(_ supervisor: ClusterMemberSupervisorState, than thisVersion: String) -> Bool {
guard let running = SemanticVersion(supervisor.version), let installed = SemanticVersion(thisVersion) else { return false }
return running < installed
}

/// The service folder of a part that a supervised cluster service started: the folder of its heartbeat file
/// (`ClusterService.partEnvironment`). Nil for any other process, the service itself included.
public static func partServiceDirectory(environment: [String: String]) -> URL? {
guard let path = environment[ClusterSupervisionFiles.healthPathEnvironmentKey], !path.isEmpty else { return nil }
let file = URL(fileURLWithPath: path)
let directory = file.deletingLastPathComponent()
guard file.lastPathComponent == ClusterServiceAgent.partHealthPath(serviceDirectory: directory).lastPathComponent else { return nil }
return directory
}

/// How long a part that asked waits for the restart to stop it before it starts as it would have.
public static let waitForStopSeconds: Double = 20

/// At the start of a cluster part: the check, and the restart when it is due. `say` gets a line when it asks, and
/// one more if launchctl refuses. After asking, the part starts nothing for `waitForStopSeconds` (`waitForStop`),
/// so the restart's stop of the service, which stops this part with SIGTERM, ends it before it loads a model only to
/// release it again. A part that is still running after the wait starts as before.
@discardableResult
public static func restartIfStale(say: @escaping @Sendable (String) -> Void) -> Decision {
let decision = restartIfStale(environment: ProcessInfo.processInfo.environment,
executablePath: LaunchctlControl.currentExecutablePath(),
thisVersion: ProviderCore.version, parentPID: getppid(),
now: Date().timeIntervalSince1970, say: say)
if case .restart = decision { waitForStop(seconds: waitForStopSeconds) }
return decision
}

/// Sleeps `seconds` with SIGTERM and SIGINT at their default action, then gives them back what they had. A `start`
/// part runs under the AppKit host, which has already taken both for the provider's own drain before `Start.run()`
/// (`ProviderSignalHandler`: ignored, read by dispatch sources); a SIGTERM would only be noted there, and the part
/// would sleep the whole wait and carry on starting. With their default action the stop ends it at once, as it ends
/// `cluster link-follower`, which has set no handler yet.
static func waitForStop(seconds: Double) {
var saved: [(number: Int32, action: sigaction)] = []
for number in [SIGTERM, SIGINT] {
var standard = sigaction()
standard.__sigaction_u.__sa_handler = SIG_DFL
var previous = sigaction()
if sigaction(number, &standard, &previous) == 0 { saved.append((number, previous)) }
}
Thread.sleep(forTimeInterval: seconds)
for entry in saved {
var action = entry.action
sigaction(entry.number, &action, nil)
}
}

static func restartIfStale(environment: [String: String], executablePath: String, thisVersion: String,
parentPID: Int32, now: Double,
printJob: (String) -> LaunchctlControl.Output = { LaunchctlControl.printOutput(label: $0) },
kick: (String, @escaping @Sendable (String) -> Void) -> Void = { kickInBackground($0, say: $1) },
say: @escaping @Sendable (String) -> Void) -> Decision {
guard let directory = partServiceDirectory(environment: environment),
let supervisor = ClusterSupervisionFiles.read(ClusterMemberSupervisorState.self,
from: ClusterServiceAgent.supervisorStatePath(serviceDirectory: directory)),
olderSupervisor(supervisor, than: thisVersion) else { return .nothing }
// Only past the version check: reading the job asks launchctl.
let label = ClusterServiceAgentPlan.label(executablePath: executablePath)
let printed = printJob(label)
let askedPath = directory.appendingPathComponent(fileName)
let decision = decide(thisVersion: thisVersion, parentPID: parentPID, supervisor: supervisor,
jobPID: printed.succeeded ? jobPID(launchctlPrint: printed.stdout) : nil,
asked: ClusterSupervisionFiles.read(Asked.self, from: askedPath), now: now)
guard case .restart(let from, let to) = decision else { return decision }
// Recorded before the ask, and asked only once recorded: the restart ends this process too, and the record is
// what keeps the next part's start from asking again.
guard ClusterSupervisionFiles.write(Asked(from: from, to: to, supervisorPID: supervisor.supervisorPID, at: now),
to: askedPath) else {
say("could not record the restart in \(askedPath.path), so this Mac's cluster service is not restarted: "
+ "it still runs v\(from), and runs v\(to) after the next login")
return .nothing
}
say("this Mac's cluster service still runs v\(from) while v\(to) is installed (its update did not restart it): "
+ "restarting it once (launchctl kickstart -k \(label)); it starts the pair again on v\(to)")
kick(LaunchctlControl.target(label: label), say)
return decision
}

/// Not waited for: launchd stops this part with the service, and nothing that stop waits for may wait on launchctl.
static func kickInBackground(_ target: String, say: @escaping @Sendable (String) -> Void,
run: @escaping @Sendable ([String]) -> LaunchctlControl.Output
= { LaunchctlControl.run($0, captureStderr: true) }) {
Thread.detachNewThread {
let result = run(["kickstart", "-k", target])
guard !result.succeeded else { return }
say("could not restart this Mac's cluster service (\(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))); "
+ "it runs the installed release after the next login")
}
}

/// The `pid = N` line of `launchctl print` for a running job.
static func jobPID(launchctlPrint output: String) -> Int32? {
guard let expression = try? NSRegularExpression(pattern: #"(?m)^\s*pid\s*=\s*([1-9][0-9]*)\s*$"#),
let match = expression.firstMatch(in: output, range: NSRange(output.startIndex..., in: output)),
let range = Range(match.range(at: 1), in: output) else { return nil }
return Int32(output[range])
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ extension Cluster {

mutating func run() throws {
Darkbloom.ensureLogging()
// This Mac's part of a pair: a cluster service its update left on an earlier release restarts once.
ClusterServiceStaleRestart.restartIfStale { text in
FileHandle.standardOutput.write(Data("\(ISO8601DateFormatter().string(from: Date())) cluster part: \(text)\n".utf8))
}
let providerPath = try configOptions.config.map { URL(fileURLWithPath: $0) } ?? ConfigManager.defaultConfigPath()
let selected = try ClusterConfigurationStore.installedReference(providerConfiguration: providerPath)
// The owner this member launches reads the default setup: both must be the same.
Expand Down
2 changes: 2 additions & 0 deletions provider-swift/Sources/darkbloom/Start/StartCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,8 @@ struct Start: AsyncParsableCommand {
// Line-buffer stdout: in a log or a pipe (`start … > log`, nohup) it is block-buffered, and a start that serves
// never exits, so its banner, "Listening on" and the tool lines would wait in the buffer.
setvbuf(stdout, nil, _IOLBF, 0)
// A part of this Mac's cluster service whose update left the service on an earlier release restarts it once.
ClusterServiceStaleRestart.restartIfStale { print("\(ISO8601DateFormatter().string(from: Date())) cluster part: \($0)") }
// From here on, a service's child is the --foreground service (`isServiceChild`).
foreground = Self.isServiceChild(local: local, foreground: foreground, distributed: distributed,
startedByAService: Self.startedByAService)
Expand Down
Loading
Loading