Skip to content
Open
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
24 changes: 24 additions & 0 deletions crates/openshell-sdk/tests/client_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,30 @@ impl OpenShell for TestOpenShell {
Err(Status::unimplemented("not used by this test server"))
}

async fn peer_publish_sandbox_events(
&self,
_request: tonic::Request<proto::PeerPublishSandboxEventsRequest>,
) -> Result<Response<proto::PeerPublishSandboxEventsResponse>, Status> {
Err(Status::unimplemented("not used by this test server"))
}

async fn peer_get_sandbox_logs(
&self,
_request: tonic::Request<proto::PeerGetSandboxLogsRequest>,
) -> Result<Response<proto::GetSandboxLogsResponse>, Status> {
Err(Status::unimplemented("not used by this test server"))
}

type PeerWatchSandboxStream =
tokio_stream::wrappers::ReceiverStream<Result<proto::SandboxStreamEvent, Status>>;

async fn peer_watch_sandbox(
&self,
_request: tonic::Request<proto::PeerWatchSandboxRequest>,
) -> Result<Response<Self::PeerWatchSandboxStream>, Status> {
Err(Status::unimplemented("not used by this test server"))
}

async fn peer_notify_config_update(
&self,
_request: tonic::Request<proto::PeerNotifyConfigUpdateRequest>,
Expand Down
3 changes: 3 additions & 0 deletions crates/openshell-server/src/auth/method_authz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ mod tests {
"/openshell.v1.OpenShell/PeerReportEndpointStatus",
"/openshell.v1.OpenShell/PeerGetSandboxProviderStatus",
"/openshell.v1.OpenShell/PeerNotifyConfigUpdate",
"/openshell.v1.OpenShell/PeerPublishSandboxEvents",
"/openshell.v1.OpenShell/PeerGetSandboxLogs",
"/openshell.v1.OpenShell/PeerWatchSandbox",
] {
assert!(!is_user_callable(path));
assert!(is_peer_callable(path));
Expand Down
5 changes: 4 additions & 1 deletion crates/openshell-server/src/auth/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,9 @@ mod tests {
"/openshell.v1.OpenShell/PeerReportEndpointStatus",
"/openshell.v1.OpenShell/PeerGetSandboxProviderStatus",
"/openshell.v1.OpenShell/PeerNotifyConfigUpdate",
"/openshell.v1.OpenShell/PeerPublishSandboxEvents",
"/openshell.v1.OpenShell/PeerGetSandboxLogs",
"/openshell.v1.OpenShell/PeerWatchSandbox",
] {
assert!(matches!(
auth.authenticate(&headers, path).await.unwrap(),
Expand All @@ -860,7 +863,7 @@ mod tests {
.principal()
.is_none()
);
assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 5);
assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 8);
}

fn identity() -> ResolvedGatewayPeerIdentity {
Expand Down
3 changes: 3 additions & 0 deletions crates/openshell-server/src/compute/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6986,6 +6986,9 @@ impl ComputeRuntime {
)
.await
.map_err(|e| format!("delete sandbox settings: {e}"))?;
crate::log_routing::delete_home(&self.store, sandbox.object_id())
.await
.map_err(|e| format!("delete sandbox log home: {e}"))?;

for (object_type, label) in [
(POLICY_OBJECT_TYPE, "policy revisions"),
Expand Down
35 changes: 35 additions & 0 deletions crates/openshell-server/src/gateway_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ pub const MUTATION_LOCK_TIMEOUTS_TOTAL: &str = "openshell_server_mutation_lock_t
pub const MUTATION_LOCK_ERRORS_TOTAL: &str = "openshell_server_mutation_lock_errors_total";
pub const PROVISIONING_DEADLINE_SKIPS_TOTAL: &str =
"openshell_server_provisioning_deadline_skips_total";
pub const SANDBOX_LOG_EVENTS_DROPPED_TOTAL: &str =
"openshell_server_sandbox_log_events_dropped_total";
// Histograms (explicit buckets, see BUCKETED_HISTOGRAMS)
pub const RELAY_CLAIM_DURATION_SECONDS: &str = "openshell_server_relay_claim_duration_seconds";
pub const PEER_REQUEST_DURATION_SECONDS: &str = "openshell_server_peer_request_duration_seconds";
Expand Down Expand Up @@ -133,6 +135,24 @@ impl RelayRejection {
}
}

/// Why a sandbox log line or platform event bound for its log home was dropped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogEventDrop {
QueueFull,
ForwardFailed,
}

impl LogEventDrop {
pub const ALL: [Self; 2] = [Self::QueueFull, Self::ForwardFailed];

pub const fn label(self) -> &'static str {
match self {
Self::QueueFull => "queue_full",
Self::ForwardFailed => "forward_failed",
}
}
}

/// Routed operation. For a peer request, the owning replica records the matching gRPC method in
/// `openshell_server_grpc_requests_total`, for example `PeerRelay` for `relay`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -346,6 +366,11 @@ pub fn describe_and_initialize(relay: RelayCapacity, mutation_lock_connections:
Unit::Count,
"Times the provisioning deadline scan skipped a sandbox because its local mutation locks were busy."
);
describe_counter!(
SANDBOX_LOG_EVENTS_DROPPED_TOTAL,
Unit::Count,
"Sandbox log lines and platform events this replica dropped instead of buffering them on the sandbox's log home replica."
);
describe_histogram!(
RELAY_CLAIM_DURATION_SECONDS,
Unit::Seconds,
Expand Down Expand Up @@ -400,6 +425,9 @@ pub fn describe_and_initialize(relay: RelayCapacity, mutation_lock_connections:
counter!(RELAY_REJECTED_TOTAL, LABEL_REASON => reason.label()).increment(0);
}
counter!(RELAY_EXPIRED_TOTAL).increment(0);
for reason in LogEventDrop::ALL {
counter!(SANDBOX_LOG_EVENTS_DROPPED_TOTAL, LABEL_REASON => reason.label()).increment(0);
}
for scope in LockScope::ALL {
counter!(MUTATION_LOCK_TIMEOUTS_TOTAL, LABEL_SCOPE => scope.label()).increment(0);
counter!(MUTATION_LOCK_ERRORS_TOTAL, LABEL_SCOPE => scope.label()).increment(0);
Expand Down Expand Up @@ -495,6 +523,13 @@ pub fn record_relay_expired(count: usize) {
}
}

pub fn record_log_events_dropped(reason: LogEventDrop, count: usize) {
if count > 0 {
counter!(SANDBOX_LOG_EVENTS_DROPPED_TOTAL, LABEL_REASON => reason.label())
.increment(count as u64);
}
}

pub fn record_relay_claimed(waited: Duration) {
histogram!(RELAY_CLAIM_DURATION_SECONDS).record(waited);
}
Expand Down
32 changes: 28 additions & 4 deletions crates/openshell-server/src/grpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,11 @@ use openshell_core::proto::{
ListSandboxesRequest, ListSandboxesResponse, ListServicesRequest, ListServicesResponse,
ListWorkspaceMembersRequest, ListWorkspaceMembersResponse, ListWorkspacesRequest,
ListWorkspacesResponse, MemoryResourceCapabilities, NegotiatedExtensionInfo,
PeerNotifyConfigUpdateRequest, PeerNotifyConfigUpdateResponse, PeerRelayFrame,
ProviderProfileResponse, ProviderResponse, PushSandboxLogsRequest, PushSandboxLogsResponse,
RefreshSandboxTokenRequest, RefreshSandboxTokenResponse, RejectDraftChunkRequest,
RejectDraftChunkResponse, RelayFrame, RemoveWorkspaceMemberRequest,
PeerGetSandboxLogsRequest, PeerNotifyConfigUpdateRequest, PeerNotifyConfigUpdateResponse,
PeerPublishSandboxEventsRequest, PeerPublishSandboxEventsResponse, PeerRelayFrame,
PeerWatchSandboxRequest, ProviderProfileResponse, ProviderResponse, PushSandboxLogsRequest,
PushSandboxLogsResponse, RefreshSandboxTokenRequest, RefreshSandboxTokenResponse,
RejectDraftChunkRequest, RejectDraftChunkResponse, RelayFrame, RemoveWorkspaceMemberRequest,
RemoveWorkspaceMemberResponse, ReportEndpointStatusRequest, ReportEndpointStatusResponse,
ReportMainProcessExitRequest, ReportMainProcessExitResponse, ReportPolicyStatusRequest,
ReportPolicyStatusResponse, ReportProviderReadinessRequest, ReportProviderReadinessResponse,
Expand Down Expand Up @@ -1387,6 +1388,29 @@ impl OpenShell for OpenShellService {
) -> Result<Response<PeerNotifyConfigUpdateResponse>, Status> {
crate::config_delivery::handle_peer_notify_config_update(&self.state, request)
}

async fn peer_publish_sandbox_events(
&self,
request: Request<PeerPublishSandboxEventsRequest>,
) -> Result<Response<PeerPublishSandboxEventsResponse>, Status> {
policy::handle_peer_publish_sandbox_events(&self.state, request)
}

async fn peer_get_sandbox_logs(
&self,
request: Request<PeerGetSandboxLogsRequest>,
) -> Result<Response<GetSandboxLogsResponse>, Status> {
policy::handle_peer_get_sandbox_logs(&self.state, request)
}

type PeerWatchSandboxStream = sandbox::WatchSandboxStream;

async fn peer_watch_sandbox(
&self,
request: Request<PeerWatchSandboxRequest>,
) -> Result<Response<Self::PeerWatchSandboxStream>, Status> {
sandbox::handle_peer_watch_sandbox(&self.state, request)
}
}

fn public_extension_info(extension: &NegotiatedExtension) -> NegotiatedExtensionInfo {
Expand Down
55 changes: 54 additions & 1 deletion crates/openshell-server/src/grpc/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ use openshell_core::proto::{
L7DenyRule, L7Rule, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, Provider, Sandbox,
SandboxPolicy as ProtoSandboxPolicy, StaticCredentialEndpointBinding,
};
use openshell_core::proto::{
PeerGetSandboxLogsRequest, PeerPublishSandboxEventsRequest, PeerPublishSandboxEventsResponse,
};
use openshell_core::telemetry::{
LifecycleOperation, LifecycleResource, PolicyDecisionOperation, TelemetryOutcome,
};
Expand Down Expand Up @@ -5499,6 +5502,56 @@ pub(super) async fn handle_get_sandbox_logs(
.await?;
let sandbox_id = sandbox.object_id();

if let Some(endpoint) = crate::supervisor_session::log_home_peer(state, sandbox_id).await {
let request = PeerGetSandboxLogsRequest {
sandbox_id: sandbox_id.to_string(),
request: Some(req.clone()),
};
match crate::supervisor_session::forward_sandbox_logs_to_peer(state, &endpoint, request)
.await
{
Ok(response) => return Ok(Response::new(response)),
Err(status) => {
debug!(endpoint, error = %status, "log home unreachable; serving local sandbox logs");
}
}
}
sandbox_logs_here(state, sandbox_id, req).map(Response::new)
}

pub(super) fn handle_peer_get_sandbox_logs(
state: &Arc<ServerState>,
request: Request<PeerGetSandboxLogsRequest>,
) -> Result<Response<GetSandboxLogsResponse>, Status> {
super::provider_readiness::ensure_peer_request(&request)?;
let PeerGetSandboxLogsRequest {
sandbox_id,
request,
} = request.into_inner();
let req = request.ok_or_else(|| Status::invalid_argument("request is required"))?;
sandbox_logs_here(state, &sandbox_id, req).map(Response::new)
}

pub(super) fn handle_peer_publish_sandbox_events(
state: &Arc<ServerState>,
request: Request<PeerPublishSandboxEventsRequest>,
) -> Result<Response<PeerPublishSandboxEventsResponse>, Status> {
super::provider_readiness::ensure_peer_request(&request)?;
for routed in request.into_inner().events {
if let Some(event) = routed.event {
state
.tracing_log_bus
.publish_here(&routed.sandbox_id, event);
}
}
Ok(Response::new(PeerPublishSandboxEventsResponse {}))
}

fn sandbox_logs_here(
state: &ServerState,
sandbox_id: &str,
req: GetSandboxLogsRequest,
) -> Result<GetSandboxLogsResponse, Status> {
let lines = if req.lines == 0 { 2000 } else { req.lines };
let tail = state.tracing_log_bus.tail(sandbox_id, lines as usize);

Expand Down Expand Up @@ -5537,7 +5590,7 @@ pub(super) async fn handle_get_sandbox_logs(
})
.collect();

Ok(Response::new(GetSandboxLogsResponse { logs, buffer_total }))
Ok(GetSandboxLogsResponse { logs, buffer_total })
}

/// How often an open push stream re-reads its sandbox record to detect that
Expand Down
2 changes: 1 addition & 1 deletion crates/openshell-server/src/grpc/provider_readiness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ async fn handle_report_provider_readiness_inner(
}))
}

fn ensure_peer_request<T>(request: &Request<T>) -> Result<(), Status> {
pub(super) fn ensure_peer_request<T>(request: &Request<T>) -> Result<(), Status> {
if matches!(
request
.extensions()
Expand Down
58 changes: 52 additions & 6 deletions crates/openshell-server/src/grpc/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ use openshell_core::proto::{
ExecSandboxEvent, ExecSandboxExit, ExecSandboxInput, ExecSandboxRequest, ExecSandboxStderr,
ExecSandboxStdout, GetSandboxRequest, GetSandboxTemplateRequest, ListSandboxProvidersRequest,
ListSandboxProvidersResponse, ListSandboxTemplatesRequest, ListSandboxTemplatesResponse,
ListSandboxesRequest, ListSandboxesResponse, Provider, ProviderMutationKind,
ResourceRequirements, ResumeSandboxRequest, RevokeSshSessionRequest, RevokeSshSessionResponse,
SandboxResources, SandboxResponse, SandboxSpec, SandboxStreamEvent, SandboxTemplateResponse,
SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SshRelayTarget,
StartSandboxRequest, StopSandboxRequest, SuspendSandboxRequest, TcpForwardFrame,
TcpForwardInit, TcpRelayTarget, WatchSandboxRequest, relay_open, tcp_forward_init,
ListSandboxesRequest, ListSandboxesResponse, PeerWatchSandboxRequest, Provider,
ProviderMutationKind, ResourceRequirements, ResumeSandboxRequest, RevokeSshSessionRequest,
RevokeSshSessionResponse, SandboxResources, SandboxResponse, SandboxSpec, SandboxStreamEvent,
SandboxTemplateResponse, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance,
SshRelayTarget, StartSandboxRequest, StopSandboxRequest, SuspendSandboxRequest,
TcpForwardFrame, TcpForwardInit, TcpRelayTarget, WatchSandboxRequest, relay_open,
tcp_forward_init,
};
use openshell_core::proto::{
BeginRootfsTarStagingRequest, BeginRootfsTarStagingResponse, Sandbox, SandboxPhase,
Expand Down Expand Up @@ -2213,6 +2214,51 @@ pub(super) async fn handle_watch_sandbox(
.await?;
let sandbox_id = sandbox.object_id().to_string();

if (req.follow_logs || req.follow_events)
&& let Some(endpoint) = crate::supervisor_session::log_home_peer(state, &sandbox_id).await
{
let request = PeerWatchSandboxRequest {
sandbox_id: sandbox_id.clone(),
request: Some(req.clone()),
};
match crate::supervisor_session::open_peer_watch(state, &endpoint, request).await {
Ok(mut upstream) => {
let (tx, rx) = mpsc::channel(256);
let producer = tokio::spawn(async move {
while let Some(item) = futures::StreamExt::next(&mut upstream).await {
if tx.send(item).await.is_err() {
return;
}
}
});
return Ok(Response::new(WatchSandboxStream::new(rx, producer)));
}
Err(status) => {
debug!(endpoint, error = %status, "log home unreachable; watching locally");
}
}
}
watch_sandbox_here(state, sandbox_id, req)
}

pub(super) fn handle_peer_watch_sandbox(
state: &Arc<ServerState>,
request: Request<PeerWatchSandboxRequest>,
) -> Result<Response<WatchSandboxStream>, Status> {
super::provider_readiness::ensure_peer_request(&request)?;
let PeerWatchSandboxRequest {
sandbox_id,
request,
} = request.into_inner();
let req = request.ok_or_else(|| Status::invalid_argument("request is required"))?;
watch_sandbox_here(state, sandbox_id, req)
}

fn watch_sandbox_here(
state: &Arc<ServerState>,
sandbox_id: String,
req: WatchSandboxRequest,
) -> Result<Response<WatchSandboxStream>, Status> {
let follow_status = req.follow_status;
let follow_logs = req.follow_logs;
let follow_events = req.follow_events;
Expand Down
2 changes: 2 additions & 0 deletions crates/openshell-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ mod gateway_ocsf;
mod gateway_ring;
mod grpc;
mod http;
mod log_routing;
mod middleware;
mod multiplex;
mod network_trust;
Expand Down Expand Up @@ -1353,6 +1354,7 @@ pub(crate) async fn run_server(
state.tracing_log_bus.clone(),
shutdown_rx.clone(),
);
log_routing::spawn(state.clone(), shutdown_rx.clone());
}
let membership_worker = gateway_members::spawn_membership_worker(
state.clone(),
Expand Down
Loading
Loading