agentmux_srv_core/backend/container/
session_files.rs1use std::collections::HashMap;
17use std::io::{Seek, SeekFrom, Write};
18use std::path::{Component, Path};
19use std::time::Duration;
20
21use bollard::container::{Config, CreateContainerOptions, DownloadFromContainerOptions, RemoveContainerOptions, StartContainerOptions};
22use bollard::models::{HostConfig, Mount, MountTypeEnum};
23use futures_util::StreamExt as _;
24
25use super::mounts::claude_volume_name;
26use super::{ContainerManager, CONTAINER_CLAUDE_DIR};
27use crate::backend::transcript::provider_end::valid_sid;
28
29pub const HELPER_LABEL: &str = "agentmux.session-end";
31const REMOVE_LIMIT: Duration = Duration::from_secs(60);
33const STAGE_LIMIT: u64 = 4 << 30;
35
36pub fn valid_project(project: &str) -> bool {
39 !project.is_empty() && project.len() <= 200 && project != "." && project != ".." && project.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct SessionPaths {
45 pub jsonl: String,
46 pub folder: String,
47}
48
49pub fn session_paths(project: &str, sid: &str) -> Option<SessionPaths> {
51 (valid_project(project) && valid_sid(sid)).then(|| {
52 let base = format!("{CONTAINER_CLAUDE_DIR}/projects/{project}");
53 SessionPaths { jsonl: format!("{base}/{sid}.jsonl"), folder: format!("{base}/{sid}") }
54 })
55}
56
57pub fn remove_argv(paths: &SessionPaths) -> Vec<String> {
59 ["rm", "-rf", "--", paths.jsonl.as_str(), paths.folder.as_str()].map(str::to_string).to_vec()
60}
61
62pub fn helper_config(image: &str, user: Option<&str>, volume: &str, paths: &SessionPaths) -> Config<String> {
64 let argv = remove_argv(paths);
65 Config {
66 image: Some(image.to_string()),
67 entrypoint: Some(vec![argv[0].clone()]),
68 cmd: Some(argv[1..].to_vec()),
69 user: user.filter(|u| !u.is_empty()).map(str::to_string),
70 network_disabled: Some(true),
71 tty: Some(false),
72 open_stdin: Some(false),
73 labels: Some(HashMap::from([(HELPER_LABEL.to_string(), "1".to_string())])),
74 host_config: Some(HostConfig {
75 network_mode: Some("none".to_string()),
76 readonly_rootfs: Some(true),
77 cap_drop: Some(vec!["ALL".to_string()]),
79 cap_add: Some(vec!["DAC_OVERRIDE".to_string()]),
80 security_opt: Some(vec!["no-new-privileges".to_string()]),
81 memory: Some(128 * 1024 * 1024),
82 memory_swap: Some(128 * 1024 * 1024),
83 pids_limit: Some(32),
84 init: Some(true),
85 mounts: Some(vec![Mount {
86 target: Some(CONTAINER_CLAUDE_DIR.to_string()),
87 source: Some(volume.to_string()),
88 typ: Some(MountTypeEnum::VOLUME),
89 read_only: Some(false),
90 ..Default::default()
91 }]),
92 ..Default::default()
93 }),
94 ..Default::default()
95 }
96}
97
98pub fn extract(archive: impl std::io::Read, top: &str, dest: &Path) -> Result<u64, String> {
102 let mut archive = tar::Archive::new(archive);
103 archive.set_preserve_permissions(false);
104 archive.set_unpack_xattrs(false);
105 let mut written = 0u64;
106 for entry in archive.entries().map_err(|e| format!("the archive: {e}"))? {
107 let mut entry = entry.map_err(|e| format!("the archive: {e}"))?;
108 let kind = entry.header().entry_type();
109 if !(kind.is_file() || kind.is_dir()) {
110 return Err("the session holds a link or a special file".to_string());
111 }
112 let path = entry.path().map_err(|e| format!("the archive: {e}"))?.into_owned();
113 let mut parts = path.components();
114 if !matches!(parts.next(), Some(Component::Normal(first)) if first == top) || !parts.all(|c| matches!(c, Component::Normal(_))) {
115 return Err("the archive names a file outside the session".to_string());
116 }
117 written += entry.header().size().unwrap_or(0);
118 if written > STAGE_LIMIT {
119 return Err("the session is too large to stage".to_string());
120 }
121 if !entry.unpack_in(dest).map_err(|e| format!("the archive: {e}"))? {
122 return Err("the archive names a file outside the session".to_string());
123 }
124 }
125 Ok(written)
126}
127
128fn is_missing(e: &bollard::errors::Error) -> bool {
129 matches!(e, bollard::errors::Error::DockerResponseServerError { status_code: 404, .. })
130}
131
132impl ContainerManager {
133 pub async fn session_files_stage_out(&self, container_name: &str, project: &str, sid: &str, dest: &Path) -> Result<(), String> {
137 let paths = session_paths(project, sid).ok_or("not a session this can name")?;
138 self.inner.docker.inspect_container(container_name, None).await.map_err(|e| format!("couldn't inspect the container: {e}"))?;
141 for (path, top) in [(&paths.jsonl, format!("{sid}.jsonl")), (&paths.folder, sid.to_string())] {
142 let mut stream = self.inner.docker.download_from_container(container_name, Some(DownloadFromContainerOptions { path: path.as_str() }));
143 let mut spool = tempfile::tempfile().map_err(|e| format!("a place to stage: {e}"))?;
145 let mut got = 0u64;
146 while let Some(chunk) = stream.next().await {
147 match chunk {
148 Ok(bytes) => {
149 got += bytes.len() as u64;
150 if got > STAGE_LIMIT + (1 << 20) {
151 return Err("the session is too large to stage".to_string());
152 }
153 spool.write_all(&bytes).map_err(|e| format!("a place to stage: {e}"))?;
154 }
155 Err(e) if is_missing(&e) => {
156 got = 0;
157 break;
158 }
159 Err(e) => return Err(format!("couldn't read the container's files: {e}")),
160 }
161 }
162 if got == 0 {
163 continue;
164 }
165 spool.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
166 extract(std::io::BufReader::new(spool), &top, dest)?;
167 }
168 Ok(())
169 }
170
171 pub async fn session_files_remove(&self, container_name: &str, project: &str, sid: &str) -> Result<(), String> {
174 let paths = session_paths(project, sid).ok_or("not a session this can name")?;
175 let info = self.inner.docker.inspect_container(container_name, None).await.map_err(|e| format!("couldn't inspect the container: {e}"))?;
176 if info.state.as_ref().and_then(|s| s.running) == Some(true) {
177 let out = self.exec_collect(container_name, &remove_argv(&paths), REMOVE_LIMIT).await.map_err(|e| format!("couldn't remove the files: {e}"))?;
178 return match (out.timed_out, out.exit) {
179 (false, Some(0)) => Ok(()),
180 (true, _) => Err("removing the files took too long".to_string()),
181 (false, code) => Err(format!("removing the files failed ({code:?})")),
182 };
183 }
184 let config = info.config.as_ref();
185 let image = config.and_then(|c| c.image.clone()).filter(|i| !i.is_empty()).ok_or("the container names no image")?;
186 let user = config.and_then(|c| c.user.clone());
187 let name = format!("agentmux-session-end-{}", uuid::Uuid::new_v4().simple());
188 let docker = &self.inner.docker;
189 docker
190 .create_container(Some(CreateContainerOptions { name: name.as_str(), platform: None }), helper_config(&image, user.as_deref(), &claude_volume_name(container_name), &paths))
191 .await
192 .map_err(|e| format!("couldn't create the helper container: {e}"))?;
193 let ran = async {
194 docker.start_container(&name, None::<StartContainerOptions<String>>).await.map_err(|e| format!("couldn't start the helper container: {e}"))?;
195 match tokio::time::timeout(REMOVE_LIMIT, super::oneshot::wait(docker, &name)).await {
196 Ok(Ok(0)) => Ok(()),
197 Ok(Ok(code)) => Err(format!("removing the files failed ({code})")),
198 Ok(Err(e)) => Err(e),
199 Err(_) => Err("removing the files took too long".to_string()),
200 }
201 }
202 .await;
203 let _ = docker.remove_container(&name, Some(RemoveContainerOptions { force: true, v: true, ..Default::default() })).await;
204 ran
205 }
206}
207
208#[cfg(test)]
209#[path = "session_files_tests.rs"]
210mod tests;