hyprstream_workers/runtime/sandbox.rs
1//! Pod Sandbox types and lifecycle
2//!
3//! A PodSandbox represents an isolated execution environment that can host
4//! multiple containers. The actual isolation mechanism is provided by a
5//! `SandboxBackend` (Kata VM, systemd-nspawn, etc.).
6
7use chrono::{DateTime, Utc};
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use super::admission::ReservationRecord;
12use super::backend::SandboxHandle;
13use hyprstream_rpc_std::worker_client::PodSandboxMetadata;
14use hyprstream_rpc_std::worker_client::{KeyValue, LinuxContainerResources, PodSandboxState};
15
16/// Runtime representation of a pod sandbox
17///
18/// The sandbox stores an opaque `backend_handle` from the `SandboxBackend`
19/// that started it. Callers can downcast to the concrete handle type
20/// (e.g. `KataHandle`, `NspawnHandle`) via `as_any()`.
21#[derive(Debug)]
22pub struct PodSandbox {
23 /// Unique sandbox ID
24 pub id: String,
25 /// Sandbox metadata
26 pub metadata: PodSandboxMetadata,
27 /// Current state
28 pub state: PodSandboxState,
29 /// Creation timestamp
30 pub created_at: DateTime<Utc>,
31 /// Labels
32 pub labels: Vec<KeyValue>,
33 /// Annotations
34 pub annotations: Vec<KeyValue>,
35 /// Runtime handler (e.g., "kata", "nspawn")
36 pub runtime_handler: String,
37
38 // ─────────────────────────────────────────────────────────────────────────
39 // Backend-managed state
40 // ─────────────────────────────────────────────────────────────────────────
41 /// Opaque handle from the `SandboxBackend` (holds hypervisor, PIDs, etc.)
42 pub(crate) backend_handle: Option<Arc<dyn SandboxHandle>>,
43
44 /// Path to sandbox runtime directory
45 pub(crate) sandbox_path: PathBuf,
46
47 /// Image ID being served to this sandbox
48 pub(crate) image_id: Option<String>,
49
50 /// Serial console UNIX socket path — set by the backend when the VM starts.
51 /// For Cloud Hypervisor: path to the API socket (or a dedicated serial socket).
52 /// For nspawn: path to the console socket (if enabled).
53 pub(crate) console_socket: Option<PathBuf>,
54
55 /// The `LinuxContainerResources` last actually applied to this sandbox by
56 /// the backend (via `start()` or `update_resources()`) — the physical
57 /// truth, independent of any pool bookkeeping. `Default` (all-zero /
58 /// CRI-"unspecified") for a freshly-booted warm sandbox that has never
59 /// had a caller's resources applied.
60 ///
61 /// #519 fix: `SandboxPool::acquire` compares an incoming request's
62 /// `config.linux.resources` against this field before handing out a
63 /// warm sandbox, and calls `update_resources` (updating this field in
64 /// turn) on a mismatch — instead of silently reusing whatever size the
65 /// sandbox happened to be booted with. Deliberately **not** reset when a
66 /// sandbox is returned to the warm pool (`reset_sandbox`): resetting it
67 /// to `Default` would be a lie (the backend's `reset()` does not resize
68 /// the sandbox back down), and the next `acquire()`'s comparison depends
69 /// on this reflecting the sandbox's actual current size.
70 pub(crate) applied_resources: LinuxContainerResources,
71
72 /// The admission reservation (#525 P2) this sandbox is holding, if it was
73 /// obtained through `SandboxPool::acquire`'s admission-controlled path.
74 /// `None` for sandboxes constructed outside that path (e.g. `from_info`,
75 /// or a warm sandbox that has not yet been claimed). `SandboxPool::release`
76 /// gives this back to the `AdmissionTracker` so per-Subject/per-group
77 /// counters and resource reservations are released precisely.
78 pub(crate) reservation: Option<ReservationRecord>,
79}
80
81impl Clone for PodSandbox {
82 fn clone(&self) -> Self {
83 Self {
84 id: self.id.clone(),
85 metadata: self.metadata.clone(),
86 state: self.state,
87 created_at: self.created_at,
88 labels: self.labels.clone(),
89 annotations: self.annotations.clone(),
90 runtime_handler: self.runtime_handler.clone(),
91 backend_handle: self.backend_handle.clone(),
92 sandbox_path: self.sandbox_path.clone(),
93 image_id: self.image_id.clone(),
94 console_socket: self.console_socket.clone(),
95 applied_resources: self.applied_resources.clone(),
96 reservation: self.reservation.clone(),
97 }
98 }
99}
100
101impl PodSandbox {
102 /// Create a new pod sandbox from configuration
103 ///
104 /// The sandbox is created in the NotReady state. The `SandboxBackend`
105 /// will populate `backend_handle` when it starts the sandbox.
106 pub fn new(
107 id: String,
108 config: &hyprstream_rpc_std::worker_client::PodSandboxConfig,
109 sandbox_path: PathBuf,
110 ) -> Self {
111 Self {
112 id,
113 metadata: config.metadata.clone(),
114 state: PodSandboxState::SandboxNotReady,
115 created_at: Utc::now(),
116 labels: config.labels.clone(),
117 annotations: config.annotations.clone(),
118 runtime_handler: "kata".to_owned(),
119 backend_handle: None,
120 sandbox_path,
121 image_id: None,
122 console_socket: None,
123 applied_resources: LinuxContainerResources::default(),
124 reservation: None,
125 }
126 }
127
128 /// Create a pod sandbox from RPC response info
129 ///
130 /// Used when parsing list_pod_sandbox response from WorkerService.
131 pub fn from_info(
132 id: String,
133 metadata: PodSandboxMetadata,
134 state: PodSandboxState,
135 created_at: DateTime<Utc>,
136 labels: Vec<KeyValue>,
137 annotations: Vec<KeyValue>,
138 runtime_handler: String,
139 ) -> Self {
140 Self {
141 id,
142 metadata,
143 state,
144 created_at,
145 labels,
146 annotations,
147 runtime_handler,
148 backend_handle: None,
149 sandbox_path: PathBuf::new(),
150 image_id: None,
151 console_socket: None,
152 applied_resources: LinuxContainerResources::default(),
153 reservation: None,
154 }
155 }
156
157 /// Check if sandbox is ready
158 pub fn is_ready(&self) -> bool {
159 self.state == PodSandboxState::SandboxReady
160 }
161
162 /// Get the backend handle (for downcasting to concrete type)
163 pub fn backend_handle(&self) -> Option<&Arc<dyn SandboxHandle>> {
164 self.backend_handle.as_ref()
165 }
166
167 /// Set the backend handle
168 pub fn set_backend_handle(&mut self, handle: Arc<dyn SandboxHandle>) {
169 self.backend_handle = Some(handle);
170 }
171
172 /// Set the image id this sandbox's tenant VFS is composed from.
173 ///
174 /// Normally populated by the worker runtime from the `CreateSandbox` RPC.
175 /// Exposed (doc-hidden) as the seam an out-of-crate boot harness (#721)
176 /// needs so that [`KataBackend::start`](super::kata_backend::KataBackend)
177 /// composes + serves + attaches the per-sandbox tenant VFS as the guest's
178 /// virtio-fs rootfs share — instead of booting the bare VM rootfs with no
179 /// container filesystem. When unset, `start()` attaches no share and the
180 /// container has no rootfs (the failure #721 fixes).
181 #[doc(hidden)]
182 pub fn set_image_id(&mut self, image_id: impl Into<String>) {
183 self.image_id = Some(image_id.into());
184 }
185
186 /// Mark sandbox as ready
187 pub fn mark_ready(&mut self) {
188 self.state = PodSandboxState::SandboxReady;
189 }
190
191 /// Mark sandbox as not ready
192 pub fn mark_not_ready(&mut self) {
193 self.state = PodSandboxState::SandboxNotReady;
194 }
195
196 /// Get the sandbox runtime directory path
197 pub fn sandbox_path(&self) -> &PathBuf {
198 &self.sandbox_path
199 }
200
201 /// Path to the VM serial console UNIX socket, if set by the backend.
202 pub fn console_socket(&self) -> Option<&std::path::Path> {
203 self.console_socket.as_deref()
204 }
205}