Skip to content

Commit 863d98c

Browse files
committed
fix(docker): bind CDI context read-only
Signed-off-by: Evan Lezar <elezar@nvidia.com>
1 parent 116cc68 commit 863d98c

2 files changed

Lines changed: 156 additions & 131 deletions

File tree

‎crates/openshell-driver-docker/src/lib.rs‎

Lines changed: 133 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@ use bollard::models::{
1818
use bollard::query_parameters::{
1919
CreateContainerOptionsBuilder, CreateImageOptions, DownloadFromContainerOptionsBuilder,
2020
ListContainersOptionsBuilder, RemoveContainerOptionsBuilder, StopContainerOptionsBuilder,
21-
UploadToContainerOptionsBuilder,
2221
};
23-
use bollard::{Docker, body_full};
2422
use bytes::Bytes;
2523
use futures::{Stream, StreamExt};
2624
use openshell_core::cdi::{CdiContext, CdiSpecDirectory, cdi_spec_mount_path};
@@ -63,7 +61,6 @@ use openshell_core::{Config, Error, Result as CoreResult};
6361
use opentelemetry::trace::TraceContextExt as _;
6462
use std::collections::{HashMap, HashSet};
6563
use std::future::Future;
66-
use std::io::Cursor;
6764
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
6865
use std::path::{Path, PathBuf};
6966
use std::pin::Pin;
@@ -1063,6 +1060,22 @@ impl DockerComputeDriver {
10631060
.map_err(|status| {
10641061
DockerProvisioningFailure::new("ContainerCreateFailed", status.message())
10651062
})?;
1063+
if let Some(cdi_context) = cdi_context.as_ref()
1064+
&& let Err(status) = write_cdi_context_file(sandbox, &self.config, cdi_context)
1065+
{
1066+
cleanup_cdi_context_file(sandbox, &self.config);
1067+
return Err(DockerProvisioningFailure::new(
1068+
"CdiContextWriteFailed",
1069+
status.message(),
1070+
));
1071+
}
1072+
if let Err(status) = write_sandbox_token_file(sandbox, &self.config).await {
1073+
cleanup_cdi_context_file(sandbox, &self.config);
1074+
return Err(DockerProvisioningFailure::new(
1075+
"SandboxTokenWriteFailed",
1076+
status.message(),
1077+
));
1078+
}
10661079
async {
10671080
openshell_otel::record_error_result(
10681081
self.docker
@@ -1076,9 +1089,7 @@ impl DockerComputeDriver {
10761089
)
10771090
.await
10781091
.map_err(|err| {
1079-
if token_file_created {
1080-
cleanup_sandbox_token_file(sandbox, &self.config);
1081-
}
1092+
cleanup_sandbox_state_files(sandbox, &self.config);
10821093
DockerProvisioningFailure::from_status(
10831094
"ContainerCreateFailed",
10841095
create_status_from_docker_error("create docker sandbox container", err),
@@ -1101,24 +1112,6 @@ impl DockerComputeDriver {
11011112
HashMap::from([("container_name".to_string(), container_name.clone())]),
11021113
);
11031114

1104-
if let Some(cdi_context) = cdi_context
1105-
&& let Err(err) = self.upload_cdi_context(&container_name, &cdi_context).await
1106-
{
1107-
self.cleanup_created_container_after_failure(
1108-
&sandbox.id,
1109-
&container_name,
1110-
"CDI context upload failure",
1111-
)
1112-
.await;
1113-
if token_file_created {
1114-
cleanup_sandbox_token_file(sandbox, &self.config);
1115-
}
1116-
return Err(DockerProvisioningFailure::from_status(
1117-
"CdiContextUploadFailed",
1118-
err,
1119-
));
1120-
}
1121-
11221115
let start_result = async {
11231116
openshell_otel::record_error_result(
11241117
self.docker.start_container(&container_name, None).await,
@@ -1139,9 +1132,7 @@ impl DockerComputeDriver {
11391132
"container start failure",
11401133
)
11411134
.await;
1142-
if token_file_created {
1143-
cleanup_sandbox_token_file(sandbox, &self.config);
1144-
}
1135+
cleanup_sandbox_state_files(sandbox, &self.config);
11451136
return Err(DockerProvisioningFailure::from_status(
11461137
"ContainerStartFailed",
11471138
create_status_from_docker_error("start docker sandbox container", err),
@@ -1191,27 +1182,6 @@ impl DockerComputeDriver {
11911182
}
11921183
}
11931184

1194-
async fn upload_cdi_context(
1195-
&self,
1196-
container_name: &str,
1197-
context: &CdiContext,
1198-
) -> Result<(), Status> {
1199-
let archive = build_cdi_context_archive(context).map_err(Status::internal)?;
1200-
self.docker
1201-
.upload_to_container(
1202-
container_name,
1203-
Some(
1204-
UploadToContainerOptionsBuilder::default()
1205-
.path("/run")
1206-
.no_overwrite_dir_non_dir("true")
1207-
.build(),
1208-
),
1209-
body_full(Bytes::from(archive)),
1210-
)
1211-
.await
1212-
.map_err(|err| internal_status("upload CDI context to Docker container", err))
1213-
}
1214-
12151185
async fn delete_sandbox_inner(
12161186
&self,
12171187
sandbox_id: &str,
@@ -1239,11 +1209,11 @@ impl DockerComputeDriver {
12391209
.await
12401210
{
12411211
Ok(()) => {
1242-
cleanup_sandbox_token_file(&record.sandbox, &self.config);
1212+
cleanup_sandbox_state_files(&record.sandbox, &self.config);
12431213
return Ok(true);
12441214
}
12451215
Err(err) if is_not_found_error(&err) => {
1246-
cleanup_sandbox_token_file(&record.sandbox, &self.config);
1216+
cleanup_sandbox_state_files(&record.sandbox, &self.config);
12471217
return Ok(true);
12481218
}
12491219
Err(err) => {
@@ -1266,11 +1236,11 @@ impl DockerComputeDriver {
12661236
.await
12671237
{
12681238
Ok(()) => {
1269-
cleanup_sandbox_token_file_for_delete(sandbox_id, pending.as_ref(), &self.config);
1239+
cleanup_sandbox_state_files_for_delete(sandbox_id, pending.as_ref(), &self.config);
12701240
Ok(true)
12711241
}
12721242
Err(err) if is_not_found_error(&err) => {
1273-
cleanup_sandbox_token_file_for_delete(sandbox_id, pending.as_ref(), &self.config);
1243+
cleanup_sandbox_state_files_for_delete(sandbox_id, pending.as_ref(), &self.config);
12741244
Ok(pending.is_some())
12751245
}
12761246
Err(err) => Err(internal_status("delete docker sandbox container", err)),
@@ -1286,7 +1256,7 @@ impl DockerComputeDriver {
12861256
if let Some(task) = record.task {
12871257
task.abort();
12881258
}
1289-
cleanup_sandbox_token_file(&record.sandbox, &self.config);
1259+
cleanup_sandbox_state_files(&record.sandbox, &self.config);
12901260
self.publish_deleted(record.sandbox.id);
12911261
return Ok(());
12921262
}
@@ -1463,7 +1433,7 @@ impl DockerComputeDriver {
14631433
sandbox: &DriverSandbox,
14641434
failure: &DockerProvisioningFailure,
14651435
) {
1466-
cleanup_sandbox_token_file(sandbox, &self.config);
1436+
cleanup_sandbox_state_files(sandbox, &self.config);
14671437
let snapshot = pending_sandbox_snapshot(
14681438
sandbox,
14691439
&self.config.sandbox_namespace,
@@ -2768,6 +2738,7 @@ fn docker_volume_is_bind_backed(volume: &bollard::models::Volume) -> bool {
27682738
fn build_binds(
27692739
sandbox: &DriverSandbox,
27702740
config: &DockerDriverRuntimeConfig,
2741+
gpu_device_ids: Option<&[String]>,
27712742
) -> Result<Vec<String>, Status> {
27722743
let mut binds = vec![format!(
27732744
"{}:{}:ro,z",
@@ -2794,6 +2765,13 @@ fn build_binds(
27942765
SANDBOX_TOKEN_MOUNT_PATH
27952766
));
27962767
}
2768+
if cdi_context_requested(gpu_device_ids) {
2769+
binds.push(format!(
2770+
"{}:{}:ro,z",
2771+
cdi_context_host_path(sandbox, config)?.display(),
2772+
openshell_core::cdi::CDI_CONTEXT_PATH
2773+
));
2774+
}
27972775
Ok(binds)
27982776
}
27992777

@@ -2820,6 +2798,57 @@ fn sandbox_token_host_path_by_id(
28202798
})
28212799
}
28222800

2801+
fn cdi_context_host_path(
2802+
sandbox: &DriverSandbox,
2803+
config: &DockerDriverRuntimeConfig,
2804+
) -> Result<PathBuf, Status> {
2805+
cdi_context_host_path_by_id(&sandbox.id, config)
2806+
}
2807+
2808+
fn cdi_context_host_path_by_id(
2809+
sandbox_id: &str,
2810+
config: &DockerDriverRuntimeConfig,
2811+
) -> Result<PathBuf, Status> {
2812+
openshell_core::driver_utils::sandbox_token_path(
2813+
"docker-cdi-contexts",
2814+
Some(&config.sandbox_namespace),
2815+
sandbox_id,
2816+
)
2817+
.map(|path| path.with_file_name(openshell_core::cdi::CDI_CONTEXT_FILE_NAME))
2818+
.map_err(|err| Status::internal(format!("resolve CDI context state directory failed: {err}")))
2819+
}
2820+
2821+
fn write_cdi_context_file(
2822+
sandbox: &DriverSandbox,
2823+
config: &DockerDriverRuntimeConfig,
2824+
context: &CdiContext,
2825+
) -> Result<(), Status> {
2826+
let path = cdi_context_host_path(sandbox, config)?;
2827+
if let Some(parent) = path.parent() {
2828+
openshell_core::paths::create_dir_restricted(parent).map_err(|err| {
2829+
Status::internal(format!(
2830+
"create CDI context directory {} failed: {err}",
2831+
parent.display()
2832+
))
2833+
})?;
2834+
}
2835+
let json = serde_json::to_vec(context)
2836+
.map_err(|err| Status::internal(format!("encode CDI context failed: {err}")))?;
2837+
std::fs::write(&path, json).map_err(|err| {
2838+
Status::internal(format!(
2839+
"write CDI context file {} failed: {err}",
2840+
path.display()
2841+
))
2842+
})?;
2843+
openshell_core::paths::set_file_owner_only(&path).map_err(|err| {
2844+
Status::internal(format!(
2845+
"restrict CDI context file {} failed: {err}",
2846+
path.display()
2847+
))
2848+
})?;
2849+
Ok(())
2850+
}
2851+
28232852
async fn write_sandbox_token_file(
28242853
sandbox: &DriverSandbox,
28252854
config: &DockerDriverRuntimeConfig,
@@ -2860,6 +2889,15 @@ fn cleanup_sandbox_token_file(sandbox: &DriverSandbox, config: &DockerDriverRunt
28602889
cleanup_sandbox_token_file_by_id(&sandbox.id, config);
28612890
}
28622891

2892+
fn cleanup_cdi_context_file(sandbox: &DriverSandbox, config: &DockerDriverRuntimeConfig) {
2893+
cleanup_cdi_context_file_by_id(&sandbox.id, config);
2894+
}
2895+
2896+
fn cleanup_sandbox_state_files(sandbox: &DriverSandbox, config: &DockerDriverRuntimeConfig) {
2897+
cleanup_sandbox_token_file(sandbox, config);
2898+
cleanup_cdi_context_file(sandbox, config);
2899+
}
2900+
28632901
fn cleanup_sandbox_token_file_for_delete(
28642902
sandbox_id: &str,
28652903
pending: Option<&PendingSandboxRecord>,
@@ -2872,6 +2910,27 @@ fn cleanup_sandbox_token_file_for_delete(
28722910
}
28732911
}
28742912

2913+
fn cleanup_cdi_context_file_for_delete(
2914+
sandbox_id: &str,
2915+
pending: Option<&PendingSandboxRecord>,
2916+
config: &DockerDriverRuntimeConfig,
2917+
) {
2918+
if !sandbox_id.is_empty() {
2919+
cleanup_cdi_context_file_by_id(sandbox_id, config);
2920+
} else if let Some(record) = pending {
2921+
cleanup_cdi_context_file(&record.sandbox, config);
2922+
}
2923+
}
2924+
2925+
fn cleanup_sandbox_state_files_for_delete(
2926+
sandbox_id: &str,
2927+
pending: Option<&PendingSandboxRecord>,
2928+
config: &DockerDriverRuntimeConfig,
2929+
) {
2930+
cleanup_sandbox_token_file_for_delete(sandbox_id, pending, config);
2931+
cleanup_cdi_context_file_for_delete(sandbox_id, pending, config);
2932+
}
2933+
28752934
fn cleanup_sandbox_token_file_by_id(sandbox_id: &str, config: &DockerDriverRuntimeConfig) {
28762935
let Ok(path) = sandbox_token_host_path_by_id(sandbox_id, config) else {
28772936
return;
@@ -2891,6 +2950,25 @@ fn cleanup_sandbox_token_file_by_id(sandbox_id: &str, config: &DockerDriverRunti
28912950
}
28922951
}
28932952

2953+
fn cleanup_cdi_context_file_by_id(sandbox_id: &str, config: &DockerDriverRuntimeConfig) {
2954+
let Ok(path) = cdi_context_host_path_by_id(sandbox_id, config) else {
2955+
return;
2956+
};
2957+
if let Err(err) = std::fs::remove_file(&path)
2958+
&& err.kind() != std::io::ErrorKind::NotFound
2959+
{
2960+
warn!(
2961+
sandbox_id = %sandbox_id,
2962+
path = %path.display(),
2963+
error = %err,
2964+
"Failed to remove Docker CDI context file"
2965+
);
2966+
}
2967+
if let Some(dir) = path.parent() {
2968+
let _ = std::fs::remove_dir(dir);
2969+
}
2970+
}
2971+
28942972
#[cfg(test)]
28952973
fn build_environment(
28962974
sandbox: &DriverSandbox,
@@ -3063,64 +3141,6 @@ fn cdi_context_requested(gpu_device_ids: Option<&[String]>) -> bool {
30633141
gpu_device_ids.is_some_and(|device_ids| !device_ids.is_empty())
30643142
}
30653143

3066-
fn build_cdi_context_archive(context: &CdiContext) -> Result<Vec<u8>, String> {
3067-
let json = serde_json::to_vec_pretty(context).map_err(|err| err.to_string())?;
3068-
let mut archive = DockerTarArchiveBuilder::new();
3069-
archive.append_dir("openshell", 0o700)?;
3070-
archive.append_dir("openshell/supervisor", 0o700)?;
3071-
archive.append_file(
3072-
&format!(
3073-
"openshell/supervisor/{}",
3074-
openshell_core::cdi::CDI_CONTEXT_FILE_NAME
3075-
),
3076-
0o600,
3077-
json,
3078-
)?;
3079-
archive.into_inner()
3080-
}
3081-
3082-
struct DockerTarArchiveBuilder {
3083-
inner: tar::Builder<Vec<u8>>,
3084-
}
3085-
3086-
impl DockerTarArchiveBuilder {
3087-
fn new() -> Self {
3088-
Self {
3089-
inner: tar::Builder::new(Vec::new()),
3090-
}
3091-
}
3092-
3093-
fn append_dir(&mut self, path: &str, mode: u32) -> Result<(), String> {
3094-
let mut header = tar::Header::new_gnu();
3095-
header.set_entry_type(tar::EntryType::Directory);
3096-
header.set_size(0);
3097-
header.set_mode(mode);
3098-
header.set_uid(0);
3099-
header.set_gid(0);
3100-
header.set_cksum();
3101-
self.inner
3102-
.append_data(&mut header, path, std::io::empty())
3103-
.map_err(|err| err.to_string())
3104-
}
3105-
3106-
fn append_file(&mut self, path: &str, mode: u32, contents: Vec<u8>) -> Result<(), String> {
3107-
let mut header = tar::Header::new_gnu();
3108-
header.set_entry_type(tar::EntryType::Regular);
3109-
header.set_size(u64::try_from(contents.len()).map_err(|err| err.to_string())?);
3110-
header.set_mode(mode);
3111-
header.set_uid(0);
3112-
header.set_gid(0);
3113-
header.set_cksum();
3114-
self.inner
3115-
.append_data(&mut header, path, Cursor::new(contents))
3116-
.map_err(|err| err.to_string())
3117-
}
3118-
3119-
fn into_inner(self) -> Result<Vec<u8>, String> {
3120-
self.inner.into_inner().map_err(|err| err.to_string())
3121-
}
3122-
}
3123-
31243144
#[cfg(test)]
31253145
fn build_container_create_body(
31263146
sandbox: &DriverSandbox,
@@ -3274,7 +3294,7 @@ fn build_container_create_body_for_image(
32743294
pids_limit: docker_pids_limit(config.sandbox_pids_limit)?,
32753295
device_requests,
32763296
binds: {
3277-
let mut binds = build_binds(sandbox, config)?;
3297+
let mut binds = build_binds(sandbox, config, gpu_device_ids)?;
32783298
binds.extend(config.gpu.cdi_spec_bind_strings(gpu_device_ids)?);
32793299
binds.extend(user_bind_strings);
32803300
Some(binds)

0 commit comments

Comments
 (0)