1use std::ffi::OsStr;
21use std::fs::{self, DirBuilder, File};
22use std::hash::{BuildHasher, RandomState};
23use std::io::{self, Write};
24use std::os::unix::fs::DirBuilderExt;
25use std::path::{Path, PathBuf};
26
27use chrono::{DateTime, Local, Utc};
28use flate2::Compression;
29use flate2::write::GzEncoder;
30use tar::{Builder, Header, HeaderMode};
31
32pub const RUNTIME_IMAGE: &str = "gcr.io/distroless/cc-debian12";
34pub const TARGET_DIR: &str = "/gadk-target";
36
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
39pub struct BuilderStage {
40 pub image: String,
42 pub workdir: String,
44 pub package: String,
46 pub bin: String,
48}
49
50pub fn dockerfile(builder: &BuilderStage, server_port: i64, cmd_tail: &str) -> String {
59 let BuilderStage {
60 image,
61 workdir,
62 package,
63 bin,
64 } = builder;
65 format!(
66 "
67FROM {image} AS builder
68WORKDIR /app/{workdir}
69COPY . /app/
70RUN cargo build --release --locked --target-dir {TARGET_DIR} -p {package} --bin {bin}
71
72FROM {RUNTIME_IMAGE}
73
74COPY --from=builder {TARGET_DIR}/release/{bin} /app/{bin}
75EXPOSE {server_port}
76# Command to run the executable when the container starts
77CMD [\"/app/{bin}\", \"web\", \"-host\", \"0.0.0.0\", \"-port\", \"{server_port}\"{cmd_tail}]"
78 )
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum EntryKind {
84 Dir,
86 File,
88 Symlink,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct Entry {
95 pub path: PathBuf,
97 pub kind: EntryKind,
99}
100
101#[derive(Debug, Clone, Default, PartialEq, Eq)]
104pub struct SourceTree {
105 pub root: PathBuf,
107 pub entries: Vec<Entry>,
109}
110
111const EXCLUDED_NAMES: [&str; 2] = [".git", "target"];
115
116impl SourceTree {
117 pub fn walk(root: &Path, exclude: &[PathBuf]) -> io::Result<SourceTree> {
122 let mut entries = Vec::new();
123 walk_dir(root, Path::new(""), exclude, &mut entries)?;
124 Ok(SourceTree {
125 root: root.to_path_buf(),
126 entries,
127 })
128 }
129
130 pub fn copy_into(&self, dir: &Path) -> io::Result<()> {
133 for entry in &self.entries {
134 let src = self.root.join(&entry.path);
135 let dst = dir.join(&entry.path);
136 match entry.kind {
137 EntryKind::Dir => fs::create_dir_all(&dst)?,
138 EntryKind::File => {
139 fs::copy(&src, &dst)?;
140 }
141 EntryKind::Symlink => std::os::unix::fs::symlink(fs::read_link(&src)?, &dst)?,
142 }
143 }
144 Ok(())
145 }
146
147 pub fn write_tar_gz(&self, path: &Path, extra: &[(&str, &[u8])]) -> io::Result<()> {
152 let mut tar = Builder::new(GzEncoder::new(File::create(path)?, Compression::default()));
153 tar.mode(HeaderMode::Deterministic);
154 tar.follow_symlinks(false);
155 for entry in &self.entries {
156 tar.append_path_with_name(self.root.join(&entry.path), &entry.path)?;
157 }
158 for (name, data) in extra {
159 let mut header = Header::new_gnu();
160 header.set_size(data.len() as u64);
161 header.set_mode(0o644);
162 header.set_mtime(tar::DETERMINISTIC_TIMESTAMP);
163 header.set_cksum();
164 tar.append_data(&mut header, name, *data)?;
165 }
166 let mut file = tar.into_inner()?.finish()?;
167 file.flush()
168 }
169}
170
171fn walk_dir(root: &Path, rel: &Path, exclude: &[PathBuf], out: &mut Vec<Entry>) -> io::Result<()> {
173 let mut children: Vec<(PathBuf, fs::FileType)> = fs::read_dir(root.join(rel))?
174 .map(|e| e.and_then(|e| Ok((rel.join(e.file_name()), e.file_type()?))))
175 .collect::<io::Result<_>>()?;
176 children.sort_by(|a, b| a.0.cmp(&b.0));
177 for (path, file_type) in children {
178 let name = path.file_name().unwrap_or(OsStr::new(""));
179 if EXCLUDED_NAMES.iter().any(|n| name == *n) || exclude.contains(&root.join(&path)) {
180 continue;
181 }
182 if file_type.is_symlink() {
183 out.push(Entry {
184 path,
185 kind: EntryKind::Symlink,
186 });
187 } else if file_type.is_dir() {
188 out.push(Entry {
189 path: path.clone(),
190 kind: EntryKind::Dir,
191 });
192 walk_dir(root, &path, exclude, out)?;
193 } else if file_type.is_file() {
194 out.push(Entry {
195 path,
196 kind: EntryKind::File,
197 });
198 }
199 }
200 Ok(())
201}
202
203pub fn make_temp(base: &Path, prefix: &str, now: DateTime<Utc>) -> io::Result<PathBuf> {
207 let stamp = now.with_timezone(&Local).format("%Y%m%d_%H%M%S__");
208 let random = RandomState::new();
209 let mut builder = DirBuilder::new();
210 builder.mode(0o700);
211 for attempt in 0u64..10_000 {
212 let suffix = random.hash_one(attempt) as u32;
214 let dir = base.join(format!("{prefix}{stamp}{suffix}"));
215 match builder.create(&dir) {
216 Ok(()) => return Ok(dir),
217 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
218 Err(e) => return Err(e),
219 }
220 }
221 Err(io::Error::new(
222 io::ErrorKind::AlreadyExists,
223 format!(
224 "mkdirtemp {}: file exists",
225 base.join(format!("{prefix}{stamp}*")).display()
226 ),
227 ))
228}
229
230#[cfg(test)]
231mod tests {
232 use std::fs;
233 use std::io::Read;
234 use std::os::unix::fs::{PermissionsExt, symlink};
235 use std::path::{Path, PathBuf};
236
237 use chrono::{DateTime, Local, Utc};
238 use flate2::read::GzDecoder;
239 use pretty_assertions::assert_eq;
240
241 use super::*;
242 use crate::testutil::default_now;
243
244 #[test]
245 fn dockerfile_golden_cloud_run_shape() {
246 let builder = BuilderStage {
247 image: "rust:1.99.1-bookworm".into(),
248 workdir: String::new(),
249 package: "my-agent".into(),
250 bin: "agent".into(),
251 };
252 let tail = r#", "api", "-webui_address", "127.0.0.1:8081", "a2a", "--a2a_agent_url", "http://127.0.0.1:8081", "webui", "--api_server_address", "http://127.0.0.1:8081/api""#;
253
254 let got = dockerfile(&builder, 8080, tail);
255
256 assert_eq!(
257 got,
258 r#"
259FROM rust:1.99.1-bookworm AS builder
260WORKDIR /app/
261COPY . /app/
262RUN cargo build --release --locked --target-dir /gadk-target -p my-agent --bin agent
263
264FROM gcr.io/distroless/cc-debian12
265
266COPY --from=builder /gadk-target/release/agent /app/agent
267EXPOSE 8080
268# Command to run the executable when the container starts
269CMD ["/app/agent", "web", "-host", "0.0.0.0", "-port", "8080", "api", "-webui_address", "127.0.0.1:8081", "a2a", "--a2a_agent_url", "http://127.0.0.1:8081", "webui", "--api_server_address", "http://127.0.0.1:8081/api"]"#
270 );
271 }
272
273 #[test]
274 fn dockerfile_golden_agent_engine_shape() {
275 let builder = BuilderStage {
276 image: "rust:bookworm".into(),
277 workdir: "ws".into(),
278 package: "agent".into(),
279 bin: "agent".into(),
280 };
281
282 let got = dockerfile(&builder, 9090, r#", "agentengine""#);
283
284 assert_eq!(
285 got,
286 r#"
287FROM rust:bookworm AS builder
288WORKDIR /app/ws
289COPY . /app/
290RUN cargo build --release --locked --target-dir /gadk-target -p agent --bin agent
291
292FROM gcr.io/distroless/cc-debian12
293
294COPY --from=builder /gadk-target/release/agent /app/agent
295EXPOSE 9090
296# Command to run the executable when the container starts
297CMD ["/app/agent", "web", "-host", "0.0.0.0", "-port", "9090", "agentengine"]"#
298 );
299 }
300
301 #[test]
302 fn dockerfile_without_tail_closes_the_cmd_array() {
303 let got = dockerfile(&BuilderStage::default(), 8080, "");
304
305 assert!(
306 got.ends_with(r#"CMD ["/app/", "web", "-host", "0.0.0.0", "-port", "8080"]"#),
307 "{got}"
308 );
309 }
310
311 fn source_root() -> tempfile::TempDir {
318 let dir = tempfile::tempdir().unwrap();
319 let r = dir.path();
320 for d in [
321 ".git",
322 "target/debug",
323 "a",
324 "crates/c/src",
325 "crates/c/target",
326 "tmp/cloudrun_x",
327 "empty",
328 ] {
329 fs::create_dir_all(r.join(d)).unwrap();
330 }
331 for (f, body) in [
332 ("Cargo.toml", "[workspace]\n"),
333 ("Cargo.lock", "version = 4\n"),
334 ("Dockerfile", "FROM user\n"),
335 ("a.txt", "a\n"),
336 ("a/b.rs", "b\n"),
337 (".git/HEAD", "ref\n"),
338 ("target/debug/x", "x\n"),
339 ("crates/c/Cargo.toml", "[package]\n"),
340 ("crates/c/Dockerfile", "FROM nested\n"),
341 ("crates/c/.git", "gitdir: x\n"),
342 ("crates/c/target/y", "y\n"),
343 ("crates/c/src/main.rs", "fn main() {}\n"),
344 ("tmp/cloudrun_x/staged", "s\n"),
345 ] {
346 fs::write(r.join(f), body).unwrap();
347 }
348 fs::set_permissions(
349 r.join("crates/c/src/main.rs"),
350 fs::Permissions::from_mode(0o755),
351 )
352 .unwrap();
353 symlink("Cargo.toml", r.join("README")).unwrap();
354 dir
355 }
356
357 fn entry(path: &str, kind: EntryKind) -> Entry {
358 Entry {
359 path: PathBuf::from(path),
360 kind,
361 }
362 }
363
364 #[test]
365 fn walk_sorts_and_excludes() {
366 let dir = source_root();
367 let r = dir.path();
368
369 let tree = SourceTree::walk(r, &[r.join("tmp/cloudrun_x"), r.join("Dockerfile")]).unwrap();
370
371 assert_eq!(tree.root, r);
372 assert_eq!(
373 tree.entries,
374 vec![
375 entry("Cargo.lock", EntryKind::File),
376 entry("Cargo.toml", EntryKind::File),
377 entry("README", EntryKind::Symlink),
378 entry("a", EntryKind::Dir),
379 entry("a/b.rs", EntryKind::File),
380 entry("a.txt", EntryKind::File),
381 entry("crates", EntryKind::Dir),
382 entry("crates/c", EntryKind::Dir),
383 entry("crates/c/Cargo.toml", EntryKind::File),
384 entry("crates/c/Dockerfile", EntryKind::File),
385 entry("crates/c/src", EntryKind::Dir),
386 entry("crates/c/src/main.rs", EntryKind::File),
387 entry("empty", EntryKind::Dir),
388 entry("tmp", EntryKind::Dir),
389 ]
390 );
391 }
392
393 #[test]
394 fn walk_without_excludes_keeps_the_root_dockerfile() {
395 let dir = source_root();
396 let r = dir.path();
397
398 let tree = SourceTree::walk(r, &[]).unwrap();
399 let paths: Vec<&Path> = tree.entries.iter().map(|e| e.path.as_path()).collect();
400
401 assert!(paths.contains(&Path::new("Dockerfile")));
402 assert!(paths.contains(&Path::new("tmp/cloudrun_x/staged")));
403 assert!(
404 !paths
405 .iter()
406 .any(|p| p.starts_with(".git") || p.starts_with("target"))
407 );
408 }
409
410 #[test]
411 fn walk_of_a_missing_root_is_an_error() {
412 let dir = tempfile::tempdir().unwrap();
413
414 assert!(SourceTree::walk(&dir.path().join("missing"), &[]).is_err());
415 }
416
417 #[test]
418 fn copy_into_reproduces_the_tree() {
419 let dir = source_root();
420 let r = dir.path();
421 let out = tempfile::tempdir().unwrap();
422 let tree = SourceTree::walk(r, &[r.join("tmp/cloudrun_x")]).unwrap();
423
424 tree.copy_into(out.path()).unwrap();
425
426 let copied = SourceTree::walk(out.path(), &[]).unwrap();
427 assert_eq!(copied.entries, tree.entries);
428 assert_eq!(
429 fs::read_to_string(out.path().join("crates/c/src/main.rs")).unwrap(),
430 "fn main() {}\n"
431 );
432 assert_eq!(
433 fs::metadata(out.path().join("crates/c/src/main.rs"))
434 .unwrap()
435 .permissions()
436 .mode()
437 & 0o777,
438 0o755
439 );
440 assert_eq!(
441 fs::read_link(out.path().join("README")).unwrap(),
442 PathBuf::from("Cargo.toml")
443 );
444 assert_eq!(
445 fs::read_to_string(out.path().join("Dockerfile")).unwrap(),
446 "FROM user\n"
447 );
448 assert!(out.path().join("empty").is_dir());
449 }
450
451 fn read_archive(path: &Path) -> Vec<(String, tar::EntryType, u32, u64, String)> {
453 let mut archive = tar::Archive::new(GzDecoder::new(fs::File::open(path).unwrap()));
454 archive
455 .entries()
456 .unwrap()
457 .map(|e| {
458 let mut e = e.unwrap();
459 let name = e.path().unwrap().to_string_lossy().into_owned();
460 let header = e.header().clone();
461 let mut body = String::new();
462 e.read_to_string(&mut body).unwrap();
463 (
464 name,
465 header.entry_type(),
466 header.mode().unwrap(),
467 header.mtime().unwrap(),
468 body,
469 )
470 })
471 .collect()
472 }
473
474 #[test]
475 fn write_tar_gz_sorted_entries_then_extra_files() {
476 let dir = source_root();
477 let r = dir.path();
478 let out = tempfile::tempdir().unwrap();
479 let archive = out.path().join("archive.tgz");
480 let tree = SourceTree::walk(r, &[r.join("tmp/cloudrun_x"), r.join("Dockerfile")]).unwrap();
481
482 tree.write_tar_gz(&archive, &[("Dockerfile", b"\nFROM generated")])
483 .unwrap();
484
485 let members = read_archive(&archive);
486 let names: Vec<&str> = members.iter().map(|m| m.0.as_str()).collect();
487 assert_eq!(
488 names,
489 vec![
490 "Cargo.lock",
491 "Cargo.toml",
492 "README",
493 "a",
494 "a/b.rs",
495 "a.txt",
496 "crates",
497 "crates/c",
498 "crates/c/Cargo.toml",
499 "crates/c/Dockerfile",
500 "crates/c/src",
501 "crates/c/src/main.rs",
502 "empty",
503 "tmp",
504 "Dockerfile",
505 ]
506 );
507 let by_name = |n: &str| members.iter().find(|m| m.0 == n).unwrap().clone();
508 let readme = by_name("README");
509 assert_eq!(readme.1, tar::EntryType::Symlink);
510 let main = by_name("crates/c/src/main.rs");
511 assert_eq!((main.2, main.3), (0o755, tar::DETERMINISTIC_TIMESTAMP));
512 assert_eq!(main.4, "fn main() {}\n");
513 assert_eq!(by_name("Cargo.toml").2, 0o644);
514 assert_eq!(by_name("a").1, tar::EntryType::Directory);
515 let dockerfile = members.last().unwrap();
516 assert_eq!(
517 dockerfile,
518 &(
519 "Dockerfile".to_string(),
520 tar::EntryType::Regular,
521 0o644,
522 tar::DETERMINISTIC_TIMESTAMP,
523 "\nFROM generated".to_string()
524 )
525 );
526 }
527
528 #[test]
529 fn make_temp_uses_go_pattern_in_local_time() {
530 let base = tempfile::tempdir().unwrap();
531 let now: DateTime<Utc> = default_now();
532
533 let a = make_temp(base.path(), "cloudrun_", now).unwrap();
534 let b = make_temp(base.path(), "cloudrun_", now).unwrap();
535
536 let prefix = format!(
537 "cloudrun_{}",
538 now.with_timezone(&Local).format("%Y%m%d_%H%M%S__")
539 );
540 for dir in [&a, &b] {
541 assert_eq!(dir.parent(), Some(base.path()));
542 let name = dir.file_name().unwrap().to_string_lossy().into_owned();
543 let suffix = name
544 .strip_prefix(&prefix)
545 .unwrap_or_else(|| panic!("{name}"));
546 assert!(
547 !suffix.is_empty() && suffix.bytes().all(|c| c.is_ascii_digit()),
548 "{name}"
549 );
550 let meta = fs::metadata(dir).unwrap();
551 assert!(meta.is_dir());
552 assert_eq!(meta.permissions().mode() & 0o777, 0o700);
553 }
554 assert_ne!(a, b);
555 }
556
557 #[test]
558 fn make_temp_in_a_missing_base_is_an_error() {
559 let base = tempfile::tempdir().unwrap();
560
561 let err =
562 make_temp(&base.path().join("missing"), "agentEngine_", default_now()).unwrap_err();
563
564 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
565 }
566}