A virtual machine on any Cloud as a sandbox-api sandbox.
A sandbox's id is its key. The key the caller chooses
(jevgent/lmjtfy-3fa2) is written on the cloud as a label on the machine
and on every image saved from it (key_labels), so the cloud itself says
what the key holds and nothing needs remembering on this machine. That is
what lets a rest delete the machine and keep the key: the key then holds an
image, and waking makes a new machine from it.
Where a key is, from what the cloud holds under its label:
| The cloud holds | State |
|---|---|
| a machine, running | Running (its address set) |
| a machine, being made or powered on | Starting |
| a machine, shutting down, or an image being saved | Resting |
| a machine, powered off | Stopped |
| no machine, an image | Stopped (raw_state image) |
| two machines | Error: something other than Vm made one |
| nothing | Gone |
Rest is the cloud's cheapest idle state (Idle): power off where a
machine that is off is billed only for its disk, else save the disk as an
image and delete the machine. In that order, never another: the machine is
deleted only once its image is available, and an older image is deleted
only once a newer one is, so at every moment one complete copy of the disk
exists. A rest that is interrupted is finished by the next one.
Wake powers the machine on, or makes it again from the newest image
with the size and region the image recorded (the next of
VmConfig::fallback_sizes when the cloud has none of that size left).
A restored machine boots with no user data: its first boot's cloud-init
wrote what keeps its keys (crate::boot). The image is kept while the
machine runs and replaced at the next rest, so it is billed alongside it.
36use crate::cloud::{Cloud, Idle, Image, ImageState, Labels, Launch, Machine, MachineState}; 37use sandbox_api::{ 38 Allowance, Cost, Create, Error, ErrorKind, Io, Isolation, Kept, Keyed, Money, Profile, Rest, Sandbox, 39 SandboxId, Sandboxes, Snapshot, SnapshotRef, State, StateModel, Stop, Usage, Wait, wait_for, 40}; 41use sha2::{Digest, Sha256}; 42use std::time::Duration;
On every machine and image Vm makes: which key it belongs to.
45pub const KEY_LABEL: &str = "sandbox-vm-key";
On an image saved by a rest: the size and region to make the machine again with, and when.
On an image saved by Snapshot::snapshot: its name. Such an image is not
a rest's, so a rest never deletes it.
52pub const SAVED_LABEL: &str = "sandbox-vm-saved";
How a Vm makes, waits for and rests its machines. Unset fields are the
cloud's own defaults (crate::CloudProfile).
Sizes to try, in order, when the cloud has none of the one asked for left.
62 pub fallback_sizes: Vec<String>,
The way to rest; the cloud's cheapest when unset.
64 pub idle: Option<Idle>,
How long a machine may take to start, power on or off.
66 pub wait: Wait,
How long saving an image may take (minutes per GB on some clouds).
68 pub image_wait: Wait,
73impl Default for VmConfig { 74 fn default() -> VmConfig { 75 VmConfig { 76 image: None, 77 size: None, 78 region: None, 79 fallback_sizes: vec![], 80 idle: None, 81 wait: Wait { timeout: Duration::from_secs(300), every: Duration::from_secs(3) }, 82 image_wait: Wait { timeout: Duration::from_secs(3600), every: Duration::from_secs(10) }, 83 shutdown_grace: Duration::from_secs(90), 84 } 85 } 86}
A VM cloud as sandboxes. I is only for waiting and the clock; every
request goes through the cloud's own client.
The labels that say a machine or image belongs to key: a hash, so any key
fits every cloud's rules for label values (lower-case, at most 63).
k and 24 hex characters of SHA-256 of the key.
A host name for key's machine: its readable part, then 8 hex of the tag,
[a-z0-9-], at most 63 characters.
110pub fn machine_name(key: &str) -> String { 111 let mut readable: String = key 112 .to_ascii_lowercase() 113 .chars() 114 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) 115 .collect(); 116 while readable.contains("--") { 117 readable = readable.replace("--", "-"); 118 } 119 let readable: String = readable.trim_matches('-').chars().take(50).collect(); 120 let readable = readable.trim_end_matches('-'); 121 let tag = &key_tag(key)[1..9]; 122 if readable.is_empty() { format!("sandbox-{tag}") } else { format!("{readable}-{tag}") } 123}
A label value every cloud accepts: [a-z0-9_-], at most 63.
136impl View { 137 fn newest(&self, state: ImageState) -> Option<&Image> { 138 self.images.iter().rev().find(|i| i.state == state) 139 } 140} 141 142fn at_of(i: &Image) -> u64 { 143 i.labels.get(AT_LABEL).and_then(|v| v.parse().ok()).or(i.created_ms).unwrap_or(0) 144} 145 146fn sandbox_of(key: &SandboxId, v: &View) -> Sandbox { 147 let mut s = Sandbox { 148 id: key.clone(), 149 state: State::Gone, 150 raw_state: "none".into(), 151 size: None, 152 name: Some(key.0.clone()), 153 stops_at_ms: None, 154 address: None, 155 }; 156 let saving = v.newest(ImageState::Creating).is_some(); 157 match v.machines.as_slice() { 158 [] => { 159 if saving { 160 (s.state, s.raw_state) = (State::Resting, "saving image".into()); 161 } else if let Some(i) = v.newest(ImageState::Available) { 162 (s.state, s.raw_state) = (State::Stopped, "image".into()); 163 s.size = i.labels.get(SIZE_LABEL).cloned(); 164 } else if !v.images.is_empty() { 165 (s.state, s.raw_state) = (State::Error, "every image of it failed".into()); 166 } 167 } 168 [m] => { 169 s.size = Some(m.size.clone()); 170 s.raw_state = m.raw_state.clone(); 171 s.state = if saving { 172 s.raw_state = format!("{} (saving image)", m.raw_state); 173 State::Resting 174 } else { 175 match m.state { 176 MachineState::Running => State::Running, 177 MachineState::Starting | MachineState::Other => State::Starting, 178 MachineState::Stopping | MachineState::Deleting => State::Resting, 179 MachineState::Off => State::Stopped, 180 MachineState::Error => State::Error, 181 } 182 }; 183 if s.state == State::Running { 184 s.address = m.ipv4.clone().or_else(|| m.ipv6.clone()); 185 } 186 } 187 many => { 188 s.state = State::Error; 189 s.raw_state = format!( 190 "{} machines carry this key ({}); only one may", 191 many.len(), 192 many.iter().map(|m| m.id.as_str()).collect::<Vec<_>>().join(", ") 193 ); 194 } 195 } 196 s 197} 198 199impl<C: Cloud, I: Io> Vm<C, I> { 200 pub fn new(cloud: C, io: I) -> Vm<C, I> { 201 Vm { cloud, io, config: VmConfig::default() } 202 } 203 204 pub fn with_config(mut self, config: VmConfig) -> Vm<C, I> { 205 self.config = config; 206 self 207 }
The way this Vm rests machines.
214 fn size(&self, spec: Option<&str>) -> String { 215 spec.map(str::to_string) 216 .or_else(|| self.config.size.clone()) 217 .unwrap_or_else(|| self.cloud.profile().size.to_string()) 218 } 219 220 fn region(&self) -> Option<String> { 221 self.config.region.clone().or_else(|| self.cloud.profile().region.map(str::to_string)) 222 } 223 224 async fn view(&self, key: &str) -> Result<View, Error> { 225 let labels = key_labels(key); 226 let machines = self.cloud.machines(&labels).await?; 227 let mut images: Vec<Image> = self 228 .cloud 229 .images(&labels) 230 .await? 231 .into_iter() 232 .filter(|i| !i.labels.contains_key(SAVED_LABEL)) 233 .collect(); 234 images.sort_by_key(at_of); 235 Ok(View { machines, images }) 236 }
The one machine under key, or a State error saying why there is none to act on.
239 async fn the_machine(&self, key: &SandboxId) -> Result<Option<Machine>, Error> { 240 let v = self.view(&key.0).await?; 241 match v.machines.len() { 242 0 | 1 => Ok(v.machines.into_iter().next()), 243 _ => Err(Error::new(ErrorKind::State { retryable: false }, sandbox_of(key, &v).raw_state)), 244 } 245 }
Ask for the machine until done says yes about its state.
248 async fn wait_machine(&self, id: &str, wait: Wait, done: impl Fn(MachineState) -> bool) -> Result<Option<Machine>, Error> { 249 let start = self.io.now_ms(); 250 loop { 251 let m = self.cloud.machine(id).await?; 252 match &m { 253 None => return Ok(None), 254 Some(m) if done(m.state) => return Ok(Some(m.clone())), 255 Some(m) if m.state == MachineState::Error => { 256 return Err(Error::new(ErrorKind::State { retryable: false }, format!("machine {id} is in error ({})", m.raw_state))); 257 } 258 Some(_) => {} 259 } 260 if self.io.now_ms().saturating_sub(start) >= wait.timeout.as_millis() as u64 { 261 return Ok(m); 262 } 263 self.io.sleep(wait.every).await; 264 } 265 }
Shut it down, and cut the power if it has not gone off within the grace.
268 async fn power_down(&self, m: &Machine) -> Result<(), Error> { 269 if m.state == MachineState::Off { 270 return Ok(()); 271 } 272 if m.state != MachineState::Stopping { 273 self.cloud.shutdown(&m.id).await?; 274 } 275 let grace = Wait { timeout: self.config.shutdown_grace, every: self.config.wait.every }; 276 match self.wait_machine(&m.id, grace, |s| s == MachineState::Off).await? { 277 None => return Err(Error::new(ErrorKind::NotFound, format!("machine {} went away while shutting down", m.id))), 278 Some(now) if now.state == MachineState::Off => return Ok(()), 279 Some(_) => {} 280 } 281 self.cloud.power_off(&m.id).await?; 282 match self.wait_machine(&m.id, self.config.wait, |s| s == MachineState::Off).await? { 283 Some(now) if now.state == MachineState::Off => Ok(()), 284 Some(now) => Err(Error::new( 285 ErrorKind::State { retryable: true }, 286 format!("machine {} still {} after the power was cut", m.id, now.raw_state), 287 )), 288 None => Err(Error::new(ErrorKind::NotFound, format!("machine {} went away while powering off", m.id))), 289 } 290 }
Wait for an image to be saved, by asking for the key's images.
293 async fn wait_image(&self, key: &str, id: &str) -> Result<Image, Error> { 294 let start = self.io.now_ms(); 295 let wait = self.config.image_wait; 296 loop { 297 let found = self.cloud.images(&key_labels(key)).await?.into_iter().find(|i| i.id == id); 298 match found { 299 Some(i) if i.state == ImageState::Available => return Ok(i), 300 Some(i) if i.state == ImageState::Error => { 301 return Err(Error::new(ErrorKind::Service { retryable: true }, format!("saving image {id} failed ({})", i.raw_state))); 302 } 303 None => return Err(Error::new(ErrorKind::NotFound, format!("image {id} disappeared while being saved"))), 304 Some(i) => { 305 if self.io.now_ms().saturating_sub(start) >= wait.timeout.as_millis() as u64 { 306 return Err(Error::new( 307 ErrorKind::State { retryable: true }, 308 format!("image {id} still {} after {} s", i.raw_state, wait.timeout.as_secs()), 309 )); 310 } 311 } 312 } 313 self.io.sleep(wait.every).await; 314 } 315 }
Make the machine again from image, at its recorded size, else the fallbacks.
318 async fn restore(&self, key: &SandboxId, image: &Image) -> Result<Machine, Error> { 319 let first = image.labels.get(SIZE_LABEL).cloned().unwrap_or_else(|| self.size(None)); 320 let region = image.labels.get(REGION_LABEL).cloned().or_else(|| self.region()); 321 let launch = Launch { 322 name: machine_name(&key.0), 323 size: first, 324 region, 325 image: image.id.clone(), 326 labels: key_labels(&key.0), 327 user_data: None, 328 }; 329 self.launch_any_size(launch).await 330 }
Launch at launch.size, else at each fallback size in turn while the
cloud says the size is sold out or over a limit; any other error stops.
334 async fn launch_any_size(&self, launch: Launch) -> Result<Machine, Error> { 335 let mut sizes = vec![launch.size.clone()]; 336 for f in &self.config.fallback_sizes { 337 if !sizes.contains(f) { 338 sizes.push(f.clone()); 339 } 340 } 341 let mut last = None; 342 for size in sizes { 343 match self.cloud.launch(&Launch { size, ..launch.clone() }).await { 344 Ok(m) => return Ok(m), 345 Err(e) if matches!(e.kind, ErrorKind::Limit { .. }) => last = Some(e), 346 Err(e) => return Err(e), 347 } 348 } 349 Err(last.unwrap_or_else(|| Error::new(ErrorKind::Invalid, "no size to make the machine with"))) 350 } 351}
spec.name is the key and is required. from is a base image or a
saved one; user_data is the first boot's (see crate::Boot).
367 async fn create(&self, spec: &Create) -> Result<Sandbox, Error> { 368 let Some(key) = spec.name.clone() else { 369 return Err(Error::new(ErrorKind::Invalid, "a VM sandbox needs a name: it is the key that finds it again")); 370 }; 371 if !spec.env.is_empty() { 372 return Err(Error::new(ErrorKind::Unsupported, "a VM takes environment per command (Command::env), not per machine")); 373 } 374 if spec.auto_stop.is_some() { 375 return Err(Error::new( 376 ErrorKind::Unsupported, 377 "VM clouds never stop a machine by themselves; the caller rests it (Rest::rest)", 378 )); 379 } 380 for (k, v) in &spec.labels { 381 if !label_value_ok(k) || !label_value_ok(v) || k.starts_with("sandbox-vm") { 382 return Err(Error::new( 383 ErrorKind::Invalid, 384 format!("label {k}={v}: keys and values are [a-z0-9_-], at most 63, and sandbox-vm* is this crate's"), 385 )); 386 } 387 } 388 let id = SandboxId(key.clone()); 389 let before = self.view(&key).await?; 390 if !before.machines.is_empty() || !before.images.is_empty() { 391 return Err(Error::new( 392 ErrorKind::State { retryable: false }, 393 format!("{key} already holds {}", sandbox_of(&id, &before).raw_state), 394 )); 395 } 396 let mut labels = spec.labels.clone(); 397 labels.extend(key_labels(&key)); 398 let launch = Launch { 399 name: machine_name(&key), 400 size: self.size(spec.size.as_deref()), 401 region: self.region(), 402 image: spec 403 .from 404 .clone() 405 .or_else(|| self.config.image.clone()) 406 .unwrap_or_else(|| self.cloud.profile().image.to_string()), 407 labels, 408 user_data: spec.user_data.clone(), 409 }; 410 let m = self.launch_any_size(launch).await?; 411 Ok(sandbox_of(&id, &View { machines: vec![m], images: vec![] })) 412 }
Every machine and every rest's image under the key. An image saved with
Snapshot::snapshot is kept: it was asked for by name.
432impl<C: Cloud, I: Io> Keyed for Vm<C, I> { 433 async fn open(&self, key: &str, spec: &Create) -> Result<Sandbox, Error> { 434 let id = SandboxId(key.to_string()); 435 let s = self.get(&id).await?; 436 match s.state { 437 State::Gone => { 438 let mut spec = spec.clone(); 439 spec.name = Some(key.to_string()); 440 self.create(&spec).await?; 441 } 442 State::Stopped | State::Suspended => self.wake(&id).await?, 443 State::Resting => { 444 wait_for(self, &self.io, &id, self.config.image_wait, State::at_rest).await?; 445 self.wake(&id).await?; 446 } 447 State::Starting | State::Running => {} 448 State::Error => { 449 return Err(Error::new(ErrorKind::State { retryable: false }, format!("{key}: {}", s.raw_state))); 450 } 451 } 452 wait_for(self, &self.io, &id, self.config.wait, |st| st == State::Running).await 453 } 454 455 async fn lookup(&self, key: &str) -> Result<Option<Sandbox>, Error> { 456 let s = self.get(&SandboxId(key.to_string())).await?; 457 Ok(Some(s).filter(|s| s.state != State::Gone)) 458 } 459} 460 461impl<C: Cloud, I: Io> Stop for Vm<C, I> {
Shut the machine down and keep it, whatever the cloud bills for that (on Hetzner, DigitalOcean and Lightsail, as much as running). Returns once it is off.
Returns once the machine is at rest (the module docs say how). Resting one that already rests does nothing.
482 async fn rest(&self, id: &SandboxId) -> Result<(), Error> { 483 let v = self.view(&id.0).await?; 484 let m = match v.machines.as_slice() { 485 [] => return Ok(()), 486 [m] => m.clone(), 487 _ => return Err(Error::new(ErrorKind::State { retryable: false }, sandbox_of(id, &v).raw_state)), 488 }; 489 self.power_down(&m).await?; 490 if self.idle() == Idle::PowerOff { 491 return Ok(()); 492 } 493 // A rest interrupted while its image was being saved: wait for that one. 494 let image = match v.newest(ImageState::Creating) { 495 Some(saving) => saving.clone(), 496 None => { 497 let at = self.io.now_ms(); 498 let mut labels = key_labels(&id.0); 499 if label_value_ok(&m.size) { 500 labels.insert(SIZE_LABEL.into(), m.size.clone()); 501 } 502 if let Some(r) = m.region.as_deref().filter(|r| label_value_ok(r)) { 503 labels.insert(REGION_LABEL.into(), r.to_string()); 504 } 505 labels.insert(AT_LABEL.into(), at.to_string()); 506 self.cloud.snapshot(&m.id, &format!("{}-{at}", machine_name(&id.0)), &labels).await? 507 } 508 }; 509 let image = self.wait_image(&id.0, &image.id).await.map_err(|mut e| { 510 e.message = format!("{}; the machine is kept, powered off, with its disk", e.message); 511 e 512 })?; 513 self.cloud.delete_machine(&m.id).await?; 514 for old in self.view(&id.0).await?.images.iter().filter(|i| i.id != image.id) { 515 self.cloud.delete_image(&old.id).await?; 516 } 517 Ok(()) 518 }
Returns once the cloud has the machine starting; wait_for waits for it to run.
521 async fn wake(&self, id: &SandboxId) -> Result<(), Error> { 522 let v = self.view(&id.0).await?; 523 match v.machines.as_slice() { 524 [m] if m.state == MachineState::Off => self.cloud.power_on(&m.id).await, 525 [_] => Ok(()), 526 [] => match v.newest(ImageState::Available) { 527 Some(image) => self.restore(id, image).await.map(|_| ()), 528 None => Err(Error::new(ErrorKind::NotFound, format!("{id} holds no machine and no image to make one from"))), 529 }, 530 _ => Err(Error::new(ErrorKind::State { retryable: false }, sandbox_of(id, &v).raw_state)), 531 } 532 } 533}
535impl<C: Cloud, I: Io> Snapshot for Vm<C, I> {
An image of the machine as it is now, named, which no rest deletes.
537 async fn snapshot(&self, id: &SandboxId, name: &str) -> Result<SnapshotRef, Error> { 538 let Some(m) = self.the_machine(id).await? else { 539 return Err(Error::new(ErrorKind::NotFound, format!("{id} has no machine to save"))); 540 }; 541 let tag: String = name 542 .to_ascii_lowercase() 543 .chars() 544 .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }) 545 .take(63) 546 .collect(); 547 let mut labels = key_labels(&id.0); 548 labels.insert(SAVED_LABEL.into(), tag); 549 let image = self.cloud.snapshot(&m.id, name, &labels).await?; 550 Ok(SnapshotRef { from: image.id }) 551 } 552}
The machine that runs now, from when it was made: its hours at its price. Earlier machines under the key (before a rest) and the images' storage are not in it; the cloud's own invoice is the whole account.
566 async fn cost(&self, id: &SandboxId) -> Result<Cost, Error> { 567 let Some(m) = self.the_machine(id).await? else { 568 return Ok(Cost::default()); 569 }; 570 let running = m 571 .created_ms 572 .map(|c| Duration::from_millis(self.io.now_ms().saturating_sub(c))) 573 .unwrap_or_default(); 574 let price = self.cloud.price(&m.size, m.region.as_deref()).await?; 575 let amount = price.per_hour * running.as_secs_f64() / 3600.0; 576 Ok(Cost { 577 running, 578 usd: (price.currency == "USD").then_some(amount), 579 charge: Some(Money { amount, currency: price.currency }), 580 }) 581 } 582}