-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathdriver.rs
More file actions
5771 lines (5286 loc) · 201 KB
/
Copy pathdriver.rs
File metadata and controls
5771 lines (5286 loc) · 201 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
use crate::gpu::{
GpuInventory, SubnetAllocator, allocate_vsock_cid, mac_from_sandbox_id, tap_device_name,
};
use crate::rootfs::{
clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, create_rootfs_image_from_dir,
extract_rootfs_archive_to, prepare_sandbox_rootfs_from_image_root, sandbox_guest_init_path,
set_rootfs_image_file_mode, write_rootfs_image_file,
};
use bollard::Docker;
use bollard::errors::Error as BollardError;
use bollard::models::ContainerCreateBody;
use bollard::query_parameters::{CreateContainerOptionsBuilder, RemoveContainerOptionsBuilder};
use flate2::read::GzDecoder;
use futures::{Stream, StreamExt, TryStreamExt};
use nix::errno::Errno;
use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
use oci_client::client::{Client as OciClient, ClientConfig};
use oci_client::manifest::{
ImageIndexEntry, OCI_IMAGE_MEDIA_TYPE, OciDescriptor, OciImageManifest,
};
use oci_client::secrets::RegistryAuth;
use oci_client::{Reference, RegistryOperation};
use openshell_core::progress::{
PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, PROGRESS_STEP_STARTING_SANDBOX,
mark_progress_active, mark_progress_complete, mark_progress_detail,
};
use openshell_core::proto::compute::v1::{
CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse,
DriverCondition as SandboxCondition, DriverPlatformEvent as PlatformEvent,
DriverSandbox as Sandbox, DriverSandboxStatus as SandboxStatus, GetCapabilitiesRequest,
GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest,
ListSandboxesResponse, StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest,
ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, WatchSandboxesEvent,
WatchSandboxesPlatformEvent, WatchSandboxesRequest, WatchSandboxesSandboxEvent,
compute_driver_server::ComputeDriver, watch_sandboxes_event,
};
use openshell_vfio::SysfsRoot;
use prost::Message;
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Read;
use std::net::Ipv4Addr;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::process::{Child, Command};
use tokio::sync::{Mutex, broadcast, mpsc};
use tokio::task::JoinHandle;
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status};
use tracing::{info, warn};
use url::{Host, Url};
const DRIVER_NAME: &str = "openshell-driver-vm";
const WATCH_BUFFER: usize = 256;
const DEFAULT_VCPUS: u8 = 2;
const DEFAULT_MEM_MIB: u32 = 2048;
const DEFAULT_OVERLAY_DISK_MIB: u64 = 4096;
const DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 4;
const MAX_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 16;
/// gvproxy host-loopback IP — gvproxy's TCP/UDP/ICMP forwarder NAT-rewrites
/// this destination to the host's `127.0.0.1` and dials out from the host
/// process. This is the only address that transparently reaches host-bound
/// services without explicit `expose` rules.
///
/// See gvisor-tap-vsock `cmd/gvproxy/config.go` (default NAT entry
/// `HostIP -> 127.0.0.1`) and `pkg/services/forwarder/tcp.go` (NAT lookup
/// before `net.Dial`).
///
/// Code paths route via `GVPROXY_HOST_LOOPBACK_ALIAS` (DNS / /etc/hosts)
/// instead so logs stay readable; this constant is kept for documentation
/// and parity with the guest init script.
#[allow(dead_code)]
const GVPROXY_HOST_LOOPBACK_IP: &str = "192.168.127.254";
const OPENSHELL_HOST_GATEWAY_ALIAS: &str = "host.openshell.internal";
/// Hostname gvproxy resolves (via its embedded DNS) to the host-loopback IP.
///
/// We rewrite loopback URLs to this hostname rather than the bare IP because:
/// * the guest init script seeds /etc/hosts with the same mapping, so it
/// resolves even when gvproxy's DNS is not in resolv.conf;
/// * keeping a recognisable hostname makes log messages clearer than a bare
/// 192.168.127.254 reference;
/// * package-managed gateway certificates include this SAN for guest mTLS.
///
/// Both names ultimately route through the gvproxy NAT path on
/// `GVPROXY_HOST_LOOPBACK_IP` — they do **not** go through the gateway IP.
const GVPROXY_HOST_LOOPBACK_ALIAS: &str = OPENSHELL_HOST_GATEWAY_ALIAS;
const GUEST_SSH_SOCKET_PATH: &str = "/run/openshell/ssh.sock";
const GUEST_TLS_CA_PATH: &str = "/opt/openshell/tls/ca.crt";
const GUEST_TLS_CERT_PATH: &str = "/opt/openshell/tls/tls.crt";
const GUEST_TLS_KEY_PATH: &str = "/opt/openshell/tls/tls.key";
const GUEST_SANDBOX_TOKEN_PATH: &str = "/opt/openshell/auth/sandbox.jwt";
const IMAGE_CACHE_ROOT_DIR: &str = "images";
const IMAGE_CACHE_ROOTFS_IMAGE: &str = "rootfs.ext4";
const OVERLAY_TEMPLATE_CACHE_DIR: &str = "overlay-templates";
const OVERLAY_TEMPLATE_CACHE_LAYOUT_VERSION: &str = "sandbox-overlay-ext4-v1";
const SANDBOX_OVERLAY_IMAGE: &str = "overlay.ext4";
const SANDBOX_REQUEST_FILE: &str = "sandbox.pb";
const GUEST_IMAGE_CONFIG_DIR: &str = "openshell-image";
const GUEST_IMAGE_OCI_LAYOUT_DIR: &str = "oci";
const GUEST_IMAGE_OCI_REF: &str = "openshell";
const IMAGE_EXPORT_ROOTFS_ARCHIVE: &str = "source-rootfs.tar";
const BOOTSTRAP_IMAGE_CACHE_LAYOUT_VERSION: &str = "sandbox-bootstrap-rootfs-ext4-v3";
const PREPARED_IMAGE_CACHE_LAYOUT_VERSION: &str = "sandbox-prepared-rootfs-ext4-umoci-v3";
const IMAGE_IDENTITY_FILE: &str = "image-identity";
const IMAGE_REFERENCE_FILE: &str = "image-reference";
const IMAGE_PREP_INIT_MODE: &str = "image-prep";
static IMAGE_CACHE_BUILD_COUNTER: AtomicU64 = AtomicU64::new(0);
#[derive(Debug, Clone)]
struct VmDriverTlsPaths {
ca: PathBuf,
cert: PathBuf,
key: PathBuf,
}
#[derive(Debug, Clone)]
struct RuntimeImagePlan {
root_disk: PathBuf,
image_disk: Option<PathBuf>,
image_identity: String,
bootstrap_image_identity: String,
}
#[derive(Debug, Clone)]
struct PreparedImageDisk {
image_identity: String,
disk_path: PathBuf,
}
#[derive(Debug, Clone)]
struct GuestImagePayload {
image_ref: String,
image_identity: String,
source: GuestImagePayloadSource,
}
#[derive(Debug, Clone)]
enum GuestImagePayloadSource {
RegistryOciLayout { layout_dir: PathBuf },
LocalDocker { rootfs_archive: PathBuf },
}
#[derive(Debug, Clone)]
pub struct VmDriverConfig {
pub openshell_endpoint: String,
pub state_dir: PathBuf,
pub launcher_bin: Option<PathBuf>,
pub default_image: String,
pub bootstrap_image: String,
pub log_level: String,
pub krun_log_level: u32,
pub vcpus: u8,
pub mem_mib: u32,
pub overlay_disk_mib: u64,
pub guest_tls_ca: Option<PathBuf>,
pub guest_tls_cert: Option<PathBuf>,
pub guest_tls_key: Option<PathBuf>,
pub gpu_enabled: bool,
pub gpu_mem_mib: u32,
pub gpu_vcpus: u8,
}
impl Default for VmDriverConfig {
fn default() -> Self {
Self {
openshell_endpoint: String::new(),
state_dir: PathBuf::from("target/openshell-vm-driver"),
launcher_bin: None,
default_image: String::new(),
bootstrap_image: String::new(),
log_level: "info".to_string(),
krun_log_level: 1,
vcpus: DEFAULT_VCPUS,
mem_mib: DEFAULT_MEM_MIB,
overlay_disk_mib: DEFAULT_OVERLAY_DISK_MIB,
guest_tls_ca: None,
guest_tls_cert: None,
guest_tls_key: None,
gpu_enabled: false,
gpu_mem_mib: 8192,
gpu_vcpus: 4,
}
}
}
impl VmDriverConfig {
fn requires_tls_materials(&self) -> bool {
self.openshell_endpoint.starts_with("https://")
}
fn tls_paths(&self) -> Result<Option<VmDriverTlsPaths>, String> {
let provided = [
self.guest_tls_ca.as_ref(),
self.guest_tls_cert.as_ref(),
self.guest_tls_key.as_ref(),
];
if provided.iter().all(Option::is_none) {
return if self.requires_tls_materials() {
Err(
"https:// openshell endpoint requires OPENSHELL_VM_TLS_CA, OPENSHELL_VM_TLS_CERT, and OPENSHELL_VM_TLS_KEY so sandbox VMs can authenticate to the gateway"
.to_string(),
)
} else {
Ok(None)
};
}
let Some(ca) = self.guest_tls_ca.clone() else {
return Err(
"OPENSHELL_VM_TLS_CA is required when TLS materials are configured".to_string(),
);
};
let Some(cert) = self.guest_tls_cert.clone() else {
return Err(
"OPENSHELL_VM_TLS_CERT is required when TLS materials are configured".to_string(),
);
};
let Some(key) = self.guest_tls_key.clone() else {
return Err(
"OPENSHELL_VM_TLS_KEY is required when TLS materials are configured".to_string(),
);
};
for path in [&ca, &cert, &key] {
if !path.is_file() {
return Err(format!(
"TLS material '{}' does not exist or is not a file",
path.display()
));
}
}
Ok(Some(VmDriverTlsPaths { ca, cert, key }))
}
}
fn validate_openshell_endpoint(endpoint: &str) -> Result<(), String> {
let url = Url::parse(endpoint)
.map_err(|err| format!("invalid openshell endpoint '{endpoint}': {err}"))?;
let Some(host) = url.host() else {
return Err(format!("openshell endpoint '{endpoint}' is missing a host"));
};
let invalid_from_vm = match host {
Host::Domain(_) => false,
Host::Ipv4(ip) => ip.is_unspecified(),
Host::Ipv6(ip) => ip.is_unspecified(),
};
if invalid_from_vm {
return Err(format!(
"openshell endpoint '{endpoint}' is not reachable from sandbox VMs; use a concrete host such as 127.0.0.1, {OPENSHELL_HOST_GATEWAY_ALIAS}, or another routable address"
));
}
Ok(())
}
#[derive(Debug)]
struct VmProcess {
child: Child,
deleting: bool,
}
struct SandboxRecord {
snapshot: Sandbox,
state_dir: PathBuf,
process: Option<Arc<Mutex<VmProcess>>>,
provisioning_task: Option<JoinHandle<()>>,
gpu_bdf: Option<String>,
deleting: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OverlayPreparation {
Fresh,
PreserveExisting,
}
#[derive(Clone)]
pub struct VmDriver {
config: VmDriverConfig,
launcher_bin: PathBuf,
registry: Arc<Mutex<HashMap<String, SandboxRecord>>>,
image_cache_lock: Arc<Mutex<()>>,
events: broadcast::Sender<WatchSandboxesEvent>,
gpu_inventory: Option<Arc<std::sync::Mutex<GpuInventory>>>,
subnet_allocator: Arc<std::sync::Mutex<SubnetAllocator>>,
}
impl VmDriver {
pub async fn new(config: VmDriverConfig) -> Result<Self, String> {
if config.openshell_endpoint.trim().is_empty() {
return Err("openshell endpoint is required".to_string());
}
validate_openshell_endpoint(&config.openshell_endpoint)?;
let _ = config.tls_paths()?;
#[cfg(target_os = "linux")]
if config.gpu_enabled {
check_gpu_privileges()?;
tokio::task::spawn_blocking(crate::cleanup_stale_tap_interfaces)
.await
.map_err(|e| format!("cleanup stale TAP interfaces panicked: {e}"))?;
}
let state_root = sandboxes_root_dir(&config.state_dir);
create_private_dir_all(&state_root).await.map_err(|err| {
format!(
"failed to create state dir '{}': {err}",
state_root.display()
)
})?;
let image_cache_root = image_cache_root_dir(&config.state_dir);
tokio::fs::create_dir_all(&image_cache_root)
.await
.map_err(|err| {
format!(
"failed to create state dir '{}': {err}",
image_cache_root.display()
)
})?;
let launcher_bin = if let Some(path) = config.launcher_bin.clone() {
path
} else {
std::env::current_exe()
.map_err(|err| format!("failed to resolve vm driver executable: {err}"))?
};
let gpu_inventory = if config.gpu_enabled {
let sysfs = SysfsRoot::system();
let inventory = GpuInventory::new(sysfs, &config.state_dir);
tracing::info!(
gpu_count = inventory.gpu_count(),
"GPU inventory initialized"
);
Some(Arc::new(std::sync::Mutex::new(inventory)))
} else {
None
};
let subnet_allocator = Arc::new(std::sync::Mutex::new(SubnetAllocator::new(
Ipv4Addr::new(10, 0, 128, 0),
17,
)));
let (events, _) = broadcast::channel(WATCH_BUFFER);
let driver = Self {
config,
launcher_bin,
registry: Arc::new(Mutex::new(HashMap::new())),
image_cache_lock: Arc::new(Mutex::new(())),
events,
gpu_inventory,
subnet_allocator,
};
driver.restore_persisted_sandboxes().await;
Ok(driver)
}
#[must_use]
pub fn capabilities(&self) -> GetCapabilitiesResponse {
let gpu_count = self
.gpu_inventory
.as_ref()
.and_then(|inv| inv.lock().ok())
.map_or(0, |inv| inv.gpu_count());
GetCapabilitiesResponse {
driver_name: DRIVER_NAME.to_string(),
driver_version: openshell_core::VERSION.to_string(),
default_image: self.config.default_image.clone(),
supports_gpu: self.gpu_inventory.is_some(),
gpu_count,
}
}
// `tonic::Status` is large but is the standard error type across the
// gRPC API surface; boxing here would diverge from every other handler.
#[allow(clippy::result_large_err)]
pub fn validate_sandbox(&self, sandbox: &Sandbox) -> Result<(), Status> {
validate_vm_sandbox(sandbox, self.config.gpu_enabled)?;
if self.resolved_sandbox_image(sandbox).is_none() {
return Err(Status::failed_precondition(
"vm sandboxes require template.image or a configured default sandbox image",
));
}
Ok(())
}
// `tonic::Status` is large but is the standard error type across the
// gRPC API surface; boxing here would diverge from every other handler.
#[allow(clippy::result_large_err)]
pub async fn create_sandbox(&self, sandbox: &Sandbox) -> Result<CreateSandboxResponse, Status> {
info!(
sandbox_id = %sandbox.id,
sandbox_name = %sandbox.name,
"vm driver: create_sandbox received"
);
validate_vm_sandbox(sandbox, self.config.gpu_enabled)?;
let state_dir = sandbox_state_dir(&self.config.state_dir, &sandbox.id)?;
let image_ref = self.resolved_sandbox_image(sandbox).ok_or_else(|| {
Status::failed_precondition(
"vm sandboxes require template.image or a configured default sandbox image",
)
})?;
info!(
sandbox_id = %sandbox.id,
image_ref = %image_ref,
state_dir = %state_dir.display(),
"vm driver: resolved image ref, preparing disks"
);
let snapshot = sandbox_snapshot(sandbox, provisioning_condition(), false);
{
let mut registry = self.registry.lock().await;
if registry.contains_key(&sandbox.id) {
return Err(Status::already_exists("sandbox already exists"));
}
registry.insert(
sandbox.id.clone(),
SandboxRecord {
snapshot: snapshot.clone(),
state_dir: state_dir.clone(),
process: None,
provisioning_task: None,
gpu_bdf: None,
deleting: false,
},
);
}
let tls_paths = match self.config.tls_paths() {
Ok(paths) => paths,
Err(err) => {
let mut registry = self.registry.lock().await;
registry.remove(&sandbox.id);
return Err(Status::failed_precondition(err));
}
};
if let Err(err) = create_private_dir_all(&state_dir).await {
let mut registry = self.registry.lock().await;
registry.remove(&sandbox.id);
return Err(Status::internal(format!("create state dir failed: {err}")));
}
if let Err(err) = write_sandbox_request(&state_dir, sandbox).await {
let mut registry = self.registry.lock().await;
registry.remove(&sandbox.id);
let _ = tokio::fs::remove_dir_all(&state_dir).await;
return Err(Status::internal(format!(
"write sandbox resume metadata failed: {err}"
)));
}
self.publish_platform_event(
sandbox.id.clone(),
platform_event(
"vm",
"Normal",
"Scheduled",
format!("Sandbox accepted by vm driver to image \"{image_ref}\""),
),
);
self.publish_snapshot(snapshot);
let driver = self.clone();
let sandbox_for_task = sandbox.clone();
let sandbox_id = sandbox.id.clone();
let image_ref_for_task = image_ref.clone();
let state_dir_for_task = state_dir.clone();
let task = tokio::spawn(async move {
driver
.provision_sandbox(
sandbox_for_task,
image_ref_for_task,
state_dir_for_task,
tls_paths,
OverlayPreparation::Fresh,
)
.await;
});
let mut registry = self.registry.lock().await;
if let Some(record) = registry.get_mut(&sandbox_id) {
if record.deleting {
task.abort();
} else {
record.provisioning_task = Some(task);
}
} else {
task.abort();
}
Ok(CreateSandboxResponse {})
}
async fn provision_sandbox(
&self,
sandbox: Sandbox,
image_ref: String,
state_dir: PathBuf,
tls_paths: Option<VmDriverTlsPaths>,
overlay_preparation: OverlayPreparation,
) {
let sandbox_id = sandbox.id.clone();
if let Err(err) = self
.provision_sandbox_inner(
sandbox,
image_ref,
state_dir.clone(),
tls_paths,
overlay_preparation,
)
.await
{
if err.code() == tonic::Code::Cancelled {
if overlay_preparation == OverlayPreparation::Fresh {
let _ = tokio::fs::remove_dir_all(&state_dir).await;
}
return;
}
warn!(
sandbox_id = %sandbox_id,
error = %err.message(),
"vm driver: sandbox provisioning failed"
);
self.fail_provisioning(
&sandbox_id,
&state_dir,
"ProvisioningFailed",
err.message(),
overlay_preparation == OverlayPreparation::Fresh,
)
.await;
}
}
#[allow(clippy::result_large_err)]
async fn provision_sandbox_inner(
&self,
sandbox: Sandbox,
image_ref: String,
state_dir: PathBuf,
tls_paths: Option<VmDriverTlsPaths>,
overlay_preparation: OverlayPreparation,
) -> Result<(), Status> {
self.ensure_provisioning_active(&sandbox.id).await?;
self.publish_platform_event(
sandbox.id.clone(),
platform_event(
"vm",
"Normal",
"ResolvingImage",
format!("Resolving VM sandbox image \"{image_ref}\""),
),
);
let image_plan = self.prepare_runtime_images(&sandbox.id, &image_ref).await?;
let image_identity = image_plan.image_identity.clone();
self.ensure_provisioning_active(&sandbox.id).await?;
info!(
sandbox_id = %sandbox.id,
image_identity = %image_identity,
bootstrap_image_identity = %image_plan.bootstrap_image_identity,
image_disk = image_plan.image_disk.as_ref().map(|path| path.display().to_string()).unwrap_or_default(),
"vm driver: sandbox root disk plan resolved"
);
let disk_paths = sandbox_runtime_disk_paths(&state_dir);
let root_disk = image_plan.root_disk;
let image_disk = image_plan.image_disk;
let overlay_disk = disk_paths.overlay_disk;
self.publish_platform_event(
sandbox.id.clone(),
platform_event(
"vm",
"Normal",
"PreparingOverlay",
"Preparing writable VM overlay disk".to_string(),
),
);
if let Err(err) = self
.prepare_runtime_overlay(
&overlay_disk,
tls_paths.as_ref(),
sandbox
.spec
.as_ref()
.map(|spec| spec.sandbox_token.as_str())
.filter(|token| !token.is_empty()),
overlay_preparation,
)
.await
{
return Err(Status::internal(format!(
"prepare guest overlay disk failed: {err}"
)));
}
self.ensure_provisioning_active(&sandbox.id).await?;
if let Err(err) =
write_sandbox_image_metadata(&state_dir, &image_ref, &image_identity).await
{
return Err(Status::internal(format!(
"write sandbox image metadata failed: {err}"
)));
}
let spec = sandbox.spec.as_ref();
let is_gpu = spec.is_some_and(|s| s.gpu);
let gpu_device = spec.map_or("", |s| s.gpu_device.as_str());
let gpu_bdf = if is_gpu {
Some(self.assign_gpu_to_record(&sandbox.id, gpu_device).await?)
} else {
None
};
let console_output = state_dir.join("rootfs-console.log");
let mut command = Command::new(&self.launcher_bin);
command.kill_on_drop(true);
command.stdin(Stdio::null());
command.stdout(Stdio::inherit());
command.stderr(Stdio::inherit());
command.arg("--internal-run-vm");
command.arg("--vm-root-disk").arg(&root_disk);
command.arg("--vm-overlay-disk").arg(&overlay_disk);
if let Some(image_disk) = &image_disk {
command.arg("--vm-image-disk").arg(image_disk);
}
command.arg("--vm-exec").arg(sandbox_guest_init_path());
command.arg("--vm-workdir").arg("/");
command.arg("--vm-console-output").arg(&console_output);
// Compute the endpoint override before building the env so
// there is a single OPENSHELL_ENDPOINT value in the env list.
let endpoint_override = if let Some(bdf) = gpu_bdf.as_ref() {
let subnet = match self
.subnet_allocator
.lock()
.map_err(|e| Status::internal(format!("subnet allocator lock poisoned: {e}")))
.and_then(|mut alloc| {
alloc
.allocate(&sandbox.id)
.map_err(Status::failed_precondition)
}) {
Ok(s) => s,
Err(err) => {
self.release_gpu_and_subnet(&sandbox.id);
return Err(err);
}
};
let vsock_cid = allocate_vsock_cid();
let mac = mac_from_sandbox_id(&sandbox.id);
let mac_str = format!(
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
);
let tap = tap_device_name(&sandbox.id);
let tap_endpoint = guest_visible_openshell_endpoint_for_tap(
&self.config.openshell_endpoint,
&subnet.host_ip.to_string(),
);
command.arg("--vm-backend").arg("qemu");
command
.arg("--vm-vcpus")
.arg(self.config.gpu_vcpus.to_string());
command
.arg("--vm-mem-mib")
.arg(self.config.gpu_mem_mib.to_string());
command.arg("--vm-gpu-bdf").arg(bdf);
command.arg("--vm-tap-device").arg(&tap);
command
.arg("--vm-guest-ip")
.arg(subnet.guest_ip.to_string());
command.arg("--vm-host-ip").arg(subnet.host_ip.to_string());
command.arg("--vm-vsock-cid").arg(vsock_cid.to_string());
command.arg("--vm-guest-mac").arg(&mac_str);
if let Some(port) = gateway_port_from_endpoint(&self.config.openshell_endpoint) {
command.arg("--vm-gateway-port").arg(port.to_string());
}
Some(tap_endpoint)
} else {
command.arg("--vm-vcpus").arg(self.config.vcpus.to_string());
command
.arg("--vm-mem-mib")
.arg(self.config.mem_mib.to_string());
None
};
self.ensure_provisioning_active(&sandbox.id).await?;
command
.arg("--vm-krun-log-level")
.arg(self.config.krun_log_level.to_string());
for env in build_guest_environment(&sandbox, &self.config, endpoint_override.as_deref()) {
command.arg("--vm-env").arg(env);
}
info!(
sandbox_id = %sandbox.id,
launcher = %self.launcher_bin.display(),
console_output = %console_output.display(),
"vm driver: spawning VM launcher"
);
let child = match command.spawn() {
Ok(child) => child,
Err(err) => {
warn!(
sandbox_id = %sandbox.id,
error = %err,
"vm driver: launcher spawn failed"
);
if gpu_bdf.is_some() {
self.release_gpu_and_subnet(&sandbox.id);
}
return Err(Status::internal(format!(
"failed to launch vm helper '{}': {err}",
self.launcher_bin.display()
)));
}
};
info!(
sandbox_id = %sandbox.id,
launcher_pid = child.id().unwrap_or(0),
"vm driver: launcher spawned"
);
let process = Arc::new(Mutex::new(VmProcess {
child,
deleting: false,
}));
let mut process_to_stop = None;
let mut snapshot_to_publish = None;
{
let mut registry = self.registry.lock().await;
match registry.get_mut(&sandbox.id) {
Some(record) if !record.deleting => {
record.process = Some(process.clone());
record.gpu_bdf.clone_from(&gpu_bdf);
record.provisioning_task = None;
snapshot_to_publish = Some(record.snapshot.clone());
}
_ => {
process_to_stop = Some(process.clone());
}
}
}
if let Some(process) = process_to_stop {
{
let mut process = process.lock().await;
process.deleting = true;
terminate_vm_process(&mut process.child)
.await
.map_err(|err| Status::internal(format!("failed to stop vm: {err}")))?;
}
self.release_gpu_and_subnet(&sandbox.id);
return Err(Status::cancelled("sandbox provisioning cancelled"));
}
self.publish_platform_event(
sandbox.id.clone(),
platform_event("vm", "Normal", "Started", "Started VM launcher".to_string()),
);
if let Some(snapshot) = snapshot_to_publish {
self.publish_snapshot(snapshot);
}
tokio::spawn({
let driver = self.clone();
let sandbox_id = sandbox.id.clone();
async move {
driver.monitor_sandbox(sandbox_id).await;
}
});
Ok(())
}
pub async fn delete_sandbox(
&self,
sandbox_id: &str,
sandbox_name: &str,
) -> Result<DeleteSandboxResponse, Status> {
if !sandbox_id.is_empty() {
validate_sandbox_id(sandbox_id)?;
}
let record_id = {
let registry = self.registry.lock().await;
if let Some((id, _record)) = registry.get_key_value(sandbox_id) {
Some(id.clone())
} else {
registry
.iter()
.find(|(_, record)| record.snapshot.name == sandbox_name)
.map(|(id, _)| id.clone())
}
};
let Some(record_id) = record_id else {
return Ok(DeleteSandboxResponse { deleted: false });
};
let (state_dir, process, gpu_bdf, provisioning_task) = {
let mut registry = self.registry.lock().await;
let Some(record) = registry.get_mut(&record_id) else {
return Ok(DeleteSandboxResponse { deleted: false });
};
record.deleting = true;
(
record.state_dir.clone(),
record.process.clone(),
record.gpu_bdf.clone(),
record.provisioning_task.take(),
)
};
if let Some(snapshot) = self
.set_snapshot_condition(&record_id, deleting_condition(), true)
.await
{
self.publish_snapshot(snapshot);
}
if let Some(task) = provisioning_task {
task.abort();
}
if let Some(process) = process {
let mut process = process.lock().await;
process.deleting = true;
terminate_vm_process(&mut process.child)
.await
.map_err(|err| Status::internal(format!("failed to stop vm: {err}")))?;
}
if gpu_bdf.is_some() {
self.release_gpu_and_subnet(&record_id);
}
remove_sandbox_state_dir(&self.config.state_dir, &state_dir).await?;
{
let mut registry = self.registry.lock().await;
registry.remove(&record_id);
}
self.publish_deleted(record_id);
Ok(DeleteSandboxResponse { deleted: true })
}
pub async fn get_sandbox(
&self,
sandbox_id: &str,
sandbox_name: &str,
) -> Result<Option<Sandbox>, Status> {
if !sandbox_id.is_empty() {
validate_sandbox_id(sandbox_id)?;
}
let registry = self.registry.lock().await;
let sandbox = if sandbox_id.is_empty() {
registry
.values()
.find(|record| record.snapshot.name == sandbox_name)
.map(|record| record.snapshot.clone())
} else {
registry
.get(sandbox_id)
.map(|record| record.snapshot.clone())
};
Ok(sandbox)
}
pub async fn current_snapshots(&self) -> Vec<Sandbox> {
let registry = self.registry.lock().await;
let mut snapshots = registry
.values()
.map(|record| record.snapshot.clone())
.collect::<Vec<_>>();
snapshots.sort_by(|left, right| left.name.cmp(&right.name));
snapshots
}
async fn restore_persisted_sandboxes(&self) {
let state_root = sandboxes_root_dir(&self.config.state_dir);
let mut entries = match tokio::fs::read_dir(&state_root).await {
Ok(entries) => entries,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
Err(err) => {
warn!(
state_root = %state_root.display(),
error = %err,
"vm driver: failed to scan persisted sandboxes"
);
return;
}
};
loop {
let entry = match entries.next_entry().await {
Ok(Some(entry)) => entry,
Ok(None) => break,
Err(err) => {
warn!(
state_root = %state_root.display(),
error = %err,
"vm driver: failed to continue scanning persisted sandboxes"
);
break;
}
};
let state_dir = entry.path();
let is_dir = match entry.file_type().await {
Ok(file_type) => file_type.is_dir(),
Err(err) => {
warn!(
state_dir = %state_dir.display(),
error = %err,
"vm driver: failed to inspect persisted sandbox state dir"
);
continue;
}
};
if !is_dir {
continue;
}
let request_path = state_dir.join(SANDBOX_REQUEST_FILE);
let sandbox = match read_sandbox_request(&request_path).await {
Ok(sandbox) => sandbox,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
Err(err) => {
warn!(
state_dir = %state_dir.display(),
error = %err,
"vm driver: failed to read persisted sandbox request"
);
continue;
}
};
if let Err(status) =
validate_restored_sandbox_state(&self.config.state_dir, &state_dir, &sandbox)
{
warn!(
sandbox_id = %sandbox.id,
state_dir = %state_dir.display(),
error = %status.message(),
"vm driver: ignoring invalid persisted sandbox state"
);
continue;
}
self.restore_persisted_sandbox(sandbox, state_dir).await;
}
}
async fn restore_persisted_sandbox(&self, sandbox: Sandbox, state_dir: PathBuf) {
let Some(image_ref) = self.resolved_sandbox_image(&sandbox) else {
warn!(
sandbox_id = %sandbox.id,
sandbox_name = %sandbox.name,
"vm driver: cannot restore persisted sandbox without image"
);
return;
};
let tls_paths = match self.config.tls_paths() {
Ok(paths) => paths,
Err(err) => {
warn!(
sandbox_id = %sandbox.id,
sandbox_name = %sandbox.name,
error = %err,
"vm driver: cannot restore persisted sandbox TLS configuration"
);
return;
}
};