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
35 changes: 25 additions & 10 deletions .github/scripts/ci/fixtures/production-app-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,10 @@ async function verifyApp(bootstrap: Bootstrap): Promise<void> {
assert.ok(typeof manifest.part === 'object' && manifest.part !== null)
assert.equal('kind' in manifest.part && manifest.part.kind, 'manifest')
assert.equal('format' in manifest.part && manifest.part.format, 'rentnerproxy.monitoring')
// The app manager's removal check aborts it, as an uninstall would; built-in monitoring
// is platform-owned again for the rest of the smoke.
// The app manager can inspect an export while this generation still owns it.
await Bun.write(progressFile, 'handoff-begun-' + bootstrap.generation)
await awaitCommand('handoff-aborted-' + bootstrap.generation)
assert.deepEqual(await (await handoff(providerRegistration.profile)).json(), platformOwned)
await awaitCommand('handoff-checked-' + bootstrap.generation)
assert.deepEqual(await (await handoff(providerRegistration.profile)).json(), exported)
// The manifest does not declare dns as a provider profile.
assert.equal((await handoff('dns')).status, 403)

Expand Down Expand Up @@ -341,11 +340,25 @@ async function verifyManager() {
assert.equal(response.status, 204, 'App manager control rejected ' + action)
}
const generationIdentity = (generation: number) => ({ ...identity, generation })
/** Return the monitoring handoff the app began to platform, as the removal check does. */
const abortHandoff = async (generation: number) => {
const expectHandoffs = async (generation: number, openHandoffs: string[]) => {
const response = await controlRequest('removable', {
identity: generationIdentity(generation),
})
assert.equal(response.status, 200)
assert.deepEqual(await response.json(), { openHandoffs, providerDependencies: [] })
}
const checkLiveHandoff = async (generation: number) => {
await awaitProgress('handoff-begun-' + generation)
await control('removable', { identity: generationIdentity(generation) })
await writeFile(commandFile, 'handoff-aborted-' + generation)
await expectHandoffs(generation, [providerRegistration.profile])
const refused = await controlRequest('abort-handoffs', {
identity: generationIdentity(generation),
})
assert.equal(refused.status, 409)
await writeFile(commandFile, 'handoff-checked-' + generation)
}
const abortStoppedHandoff = async (generation: number) => {
await control('abort-handoffs', { identity: generationIdentity(generation) })
await expectHandoffs(generation, [])
}
const grants = (generation: number, provider: boolean) => ({
identity: generationIdentity(generation),
Expand Down Expand Up @@ -439,7 +452,7 @@ async function verifyManager() {
await setManagerStage('activation')
await control('activate', lease)
await setManagerStage('app checks')
await abortHandoff(1)
await checkLiveHandoff(1)
await awaitProgress('ready-1')

await setManagerStage('grant revocation')
Expand All @@ -458,14 +471,15 @@ async function verifyManager() {
assert.equal(await first.exited, 0, 'Lease revocation did not stop the broker')
const staleProviders = { identity, providers: [providerRegistration] }
assert.equal((await controlRequest('providers', staleProviders)).status, 409)
await abortStoppedHandoff(1)

await setManagerStage('update')
await rm(commandFile, { force: true })
await rm(progressFile, { force: true })
const updateLease = await register(2)
const second = await launch(2)
await control('activate', updateLease)
await abortHandoff(2)
await checkLiveHandoff(2)
await awaitProgress('ready-2')
assert.equal((await controlRequest('lease', { identity })).status, 401)
assert.equal((await controlRequest('providers', staleProviders)).status, 409)
Expand All @@ -478,6 +492,7 @@ async function verifyManager() {
await control('retire', { identity: generationIdentity(2) })
const retired = { identity: generationIdentity(2) }
assert.equal((await controlRequest('lease', retired)).status, 401)
await abortStoppedHandoff(2)
} finally {
await Promise.all(
brokers.map(async (broker) => {
Expand Down
6 changes: 6 additions & 0 deletions core/src/app_backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ fn validate_snapshot(snapshot: &Snapshot) -> io::Result<()> {
|| slot
.get("authorityRecorded")
.is_some_and(|v| !v.is_boolean())
|| slot
.get("providerDependenciesUnknown")
.is_some_and(|v| !v.is_boolean())
|| slot.get("desiredRunning").is_some_and(|v| !v.is_boolean())
|| slot["databaseProvisioned"] != false
|| !slot["written"].is_null()
Expand All @@ -220,6 +223,9 @@ fn compatible_inventory(snapshot: &mut Snapshot, inventory: &Value) -> io::Resul
.as_object_mut()
.ok_or_else(|| invalid("Missing snapshot inventory"))?
{
slot.as_object_mut()
.ok_or_else(|| invalid("Invalid snapshot installation"))?
.remove("providerDependenciesUnknown");
if slot.get("authorityRecorded").is_none()
&& inventory[id].get("authorityRecorded").is_some()
{
Expand Down
8 changes: 3 additions & 5 deletions core/src/app_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,9 +537,6 @@ impl Manager {
.await?;
}
slot.written = data;
slot.provider_dependencies_unknown |= package.manifest["providers"]
.as_array()
.is_none_or(|providers| !providers.is_empty());
self.journal.save(id, slot.clone())?;
let mut live = self
.during(
Expand Down Expand Up @@ -666,6 +663,7 @@ impl Manager {
self.fence(id).await?;
let mut slot = self.journal.slot(id)?.clone();
slot.removal = Removal::Installed;
slot.confirmed_provider_dependencies.clear();
self.journal.save(id, slot)?;
} else {
return Err(bad("Installation is reserved for removal or purge"));
Expand All @@ -687,7 +685,7 @@ impl Manager {
self.stage(&installation_id, app_id, version, download, None)
.await?;
}
Command::Remove { installation_id } => self.remove(&installation_id).await?,
Command::Remove { installation_id } => self.remove(&installation_id, None).await?,
Command::Discard {
installation_id,
release,
Expand Down Expand Up @@ -796,7 +794,7 @@ impl Manager {
let mut slot = self.journal.slot(&id)?.clone();
let result = async {
match slot.removal {
Removal::Removing => return self.remove(&id).await,
Removal::Removing => return self.remove(&id, None).await,
Removal::Purging => return self.purge(&id).await,
Removal::Removed | Removal::Purged => {
if slot.pending_fence {
Expand Down
3 changes: 3 additions & 0 deletions core/src/app_manager/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ enum LifecycleFailure {
Conflict,
/// The target release needs an approval of exactly the grants it requests.
ApprovalRequired,
ConfirmationRequired,
/// A proxy host, an app operation or a provider dependency still needs the installation.
DependencyBlocked,
Unavailable,
Expand Down Expand Up @@ -527,6 +528,8 @@ impl Endpoint {
LifecycleFailure::RevokedAppStopped
} else if grants::approval_required(&error) {
LifecycleFailure::ApprovalRequired
} else if super::removal::confirmation_required(&error) {
LifecycleFailure::ConfirmationRequired
} else if let Some(outage) = LifecycleFailure::outage(&error) {
outage
} else {
Expand Down
63 changes: 38 additions & 25 deletions core/src/app_manager/gateway.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use super::{bad, journal::Slot};
use crate::app_ipc::filesystem::{bridge_authorization, connect_peer};
use crate::app_ipc::{filesystem::bridge_authorization, gateway::send_to_peer};
use bytes::Bytes;
use http_body_util::Full;
use http_body_util::{BodyExt, Full, Limited};
use hyper::{
Request, StatusCode,
client::conn::http1,
header::{self, HeaderValue},
};
use hyper_util::rt::TokioIo;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use std::{
io,
Expand Down Expand Up @@ -63,41 +62,48 @@ impl Gateway {
}
}
pub async fn post(&self, action: &'static str, body: Value) -> io::Result<()> {
self.request(action, body, StatusCode::NO_CONTENT)
.await
.map(drop)
}

pub(super) async fn query<T: DeserializeOwned>(
&self,
action: &'static str,
body: Value,
) -> io::Result<T> {
let bytes = self.request(action, body, StatusCode::OK).await?;
serde_json::from_slice(&bytes).map_err(io::Error::from)
}

async fn request(
&self,
action: &'static str,
body: Value,
expected: StatusCode,
) -> io::Result<Bytes> {
timeout(Duration::from_secs(6), async {
let socket = connect_peer(&self.socket, self.uid).await?;
let (mut sender, connection) = http1::Builder::new()
.max_headers(32)
.max_buf_size(16384)
.handshake(TokioIo::new(socket))
.await
.map_err(io::Error::other)?;
let request = Request::post(format!("/internal/v1/app-generations/{action}"))
.header(header::HOST, "localhost")
.header(header::CONNECTION, "close")
.header(header::AUTHORIZATION, &self.authorization)
.header(header::CONTENT_TYPE, "application/json")
.body(Full::new(Bytes::from(serde_json::to_vec(&body)?)))
.map_err(io::Error::other)?;
let response = sender.send_request(request);
tokio::pin!(response);
let response = tokio::select! {
response = &mut response => response,
closed = connection => {
closed.map_err(io::Error::other)?;
response.await
},
}
.map_err(io::Error::other)?;
if response.status() != StatusCode::NO_CONTENT {
let (response, _connection) = send_to_peer(&self.socket, self.uid, request).await?;
if response.status() != expected {
let status = response.status();
let kind = if status.is_server_error()
|| matches!(
status,
StatusCode::REQUEST_TIMEOUT | StatusCode::TOO_MANY_REQUESTS
) {
io::ErrorKind::WouldBlock
} else if matches!(action, "workers-stopped" | "removable" | "purge-data")
&& status == StatusCode::CONFLICT
} else if status == StatusCode::CONFLICT
&& matches!(
action,
"workers-stopped" | "removable" | "abort-handoffs" | "purge-data"
)
{
io::ErrorKind::ResourceBusy
} else {
Expand All @@ -111,7 +117,14 @@ impl Gateway {
),
));
}
Ok(())
if expected == StatusCode::NO_CONTENT {
return Ok(Bytes::new());
}
Limited::new(response.into_body(), 4096)
.collect()
.await
.map(|body| body.to_bytes())
.map_err(io::Error::other)
})
.await?
}
Expand Down
13 changes: 12 additions & 1 deletion core/src/app_manager/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,11 @@ pub(super) struct Slot {
pub recovery_required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grants_uncertain: Option<bool>,
pub provider_dependencies_unknown: bool,
#[serde(default, rename = "providerDependenciesUnknown", skip_serializing)]
pub(super) legacy_provider_dependencies_unknown: Option<bool>,
pub removal: Removal,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub confirmed_provider_dependencies: BTreeSet<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub removed_release: Option<ReleaseSelection>,
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -487,8 +490,13 @@ impl Journal {
return Err(bad("Invalid manager journal version"));
}
validate_installations(&state.installations)?;
let mut migrated = false;
for slot in state.installations.values_mut() {
slot.authority_recorded.get_or_insert(slot.generation > 0);
migrated |= slot.legacy_provider_dependencies_unknown.take().is_some();
}
if migrated {
persist_state(directory, &encode_state(&state)?, || Ok(()))?;
}
Ok(Self {
directory: directory.to_owned(),
Expand Down Expand Up @@ -628,6 +636,9 @@ fn validate_installations(installations: &BTreeMap<String, Slot>) -> io::Result<
|| !uids.insert(slot.uid)
|| slot.generation > super::MAX_GENERATION
|| slot.pending_fence && slot.generation == 0
|| !super::removal::valid_domains(&slot.confirmed_provider_dependencies)
|| slot.removal != Removal::Removing
&& !slot.confirmed_provider_dependencies.is_empty()
|| slot
.approvals
.values()
Expand Down
41 changes: 40 additions & 1 deletion core/src/app_manager/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ enum Action {
Rollback,
Reinstall,
Purge,
AbortHandoffs,
/// Withdraw approved grants from the installation without a restart.
Revoke,
}
Expand Down Expand Up @@ -74,6 +75,8 @@ pub(super) struct Request {
/// The grants a revocation withdraws. Receipts never repeat them.
#[serde(default, skip_serializing)]
grants: Option<Vec<RevokedGrant>>,
#[serde(default, skip_serializing)]
confirmed_provider_dependencies: Option<BTreeSet<String>>,
}

impl Request {
Expand Down Expand Up @@ -105,6 +108,14 @@ impl Request {
(Action::Revoke, None) | (_, Some(_)) => false,
(_, None) => true,
}
&& self
.confirmed_provider_dependencies
.as_ref()
.is_none_or(|domains| {
self.action == Action::Uninstall
&& !domains.is_empty()
&& super::removal::valid_domains(domains)
})
}
}

Expand All @@ -128,6 +139,7 @@ enum InstallationState {
Running,
Disabled,
RecoveryRequired,
Interrupted,
Removing,
Removed,
Purging,
Expand Down Expand Up @@ -222,6 +234,14 @@ impl Installation {
return None;
}
let state = match slot.removal {
Removal::Installed | Removal::Removed
if slot.active.is_none()
&& slot.removed_release.is_none()
&& slot.authority_recorded == Some(true)
&& !running =>
{
State::Interrupted
}
Removal::Installed if slot.desired_running && running && !slot.recovery_required => {
State::Running
}
Expand All @@ -237,6 +257,7 @@ impl Installation {
Removal::Purged => return None,
};
let (release, grants) = match state {
State::Interrupted => (slot.candidate.as_ref()?.into(), None),
State::Removed | State::Purging => {
let removed = slot.removed_release.clone()?;
// A removed release has no manifest digest. Reinstalling decides again from
Expand Down Expand Up @@ -397,6 +418,15 @@ impl Installation {
}
Action::Reinstall => self.state == State::Removed && request.target.is_some(),
Action::Purge => matches!(self.state, State::Removed | State::Purging),
Action::AbortHandoffs => {
matches!(
self.state,
State::Disabled
| State::RecoveryRequired
| State::Interrupted
| State::Removed
)
}
Action::Revoke => {
matches!(
self.state,
Expand Down Expand Up @@ -580,7 +610,7 @@ impl Manager {
Action::Reactivate | Action::Recover => Command::Start {
installation_id: id.clone(),
},
Action::Uninstall => Command::Remove {
Action::Uninstall | Action::AbortHandoffs => Command::Remove {
installation_id: id.clone(),
},
Action::Rollback => Command::Rollback {
Expand All @@ -601,6 +631,15 @@ impl Manager {
.revoke(id, request.grants.as_deref().unwrap_or_default())
.await;
}
if request.action == Action::Uninstall {
self.settle_exit(id).await?;
return self
.remove(id, request.confirmed_provider_dependencies.as_ref())
.await;
}
if request.action == Action::AbortHandoffs {
return self.abort_handoffs(id).await;
}
if matches!(request.action, Action::Update | Action::Reinstall) {
let target = request.target.as_ref().ok_or_else(conflict)?;
let app = current.app_id;
Expand Down
Loading