team-ljyzipelo

공개

Merge pull request #133 from Team-LJY/fix/spool-fallback-location

목록과 미리보기 임시 파일의 저장 위치를 순서대로 재시도
작성자
LeeJunyoung
작성 시각
커밋
cfe4f77c72d43952f14f78e72b880748dd4cfd47
이 시점의 파일 보기

변경된 파일 8개

+912-50
수정experiments/rust-archive-worker/src/runtime.rs+3-0
@@ -595,6 +595,9 @@ impl<W: Write> Job<W> {
595595 .and_then(|path| Dir::root(&path).ok())
596596 .map(|root| crate::spool::place_in(&root))
597597 .transpose()?,
598추가: Action::List { archive } | Action::Preview { archive, .. } => {
599추가: Some(crate::spool::fallback_for(&archive.to_path()?))
600추가: }
598601 _ => None,
599602 };
600603 if let Some(budget) = &self.budget {
수정experiments/rust-archive-worker/src/split_seven_zip.rs+38-22
@@ -336,6 +336,34 @@ impl Group {
336336 self.matches(part, &named)?;
337337 Ok(hash.finalize().into())
338338 }
339추가: fn capture(
340추가: &mut self,
341추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
342추가: ) -> Result<(File, [u8; 32])> {
343추가: step(Step::Check)?;
344추가: let mut file = crate::spool::temporary()?;
345추가: crate::space::ensure(&file, self.total)?;
346추가: let mut processed = 0;
347추가: let mut whole = Sha256::new();
348추가: let mut reported = Instant::now();
349추가: for index in 0..self.parts.len() {
350추가: let hash = self.read_part(
351추가: &self.parts[index],
352추가: &mut Some(&mut file),
353추가: &mut whole,
354추가: &mut processed,
355추가: &mut reported,
356추가: step,
357추가: )?;
358추가: self.parts[index].hash = hash;
359추가: step(Step::Activity)?;
360추가: }
361추가: step(Step::Read {
362추가: bytes: processed,
363추가: total: self.total,
364추가: })?;
365추가: Ok((file, whole.finalize().into()))
366추가: }
339367 fn manifest(&self) -> Result<[u8; 32]> {
340368 let mut hash = Sha256::new();
341369 hash.update(b"zipelo.split7z.v1\0");
@@ -511,28 +539,16 @@ pub(crate) fn open(
511539 if group.total > limit {
512540 return Err(ErrorCode::Limit.into());
513541 }
514삭제: let mut file = crate::spool::temporary()?;
515삭제: crate::space::ensure(&file, group.total)?;
516삭제: let mut processed = 0;
517삭제: let mut whole = Sha256::new();
518삭제: let mut reported = Instant::now();
519삭제: for index in 0..group.parts.len() {
520삭제: let hash = group.read_part(
521삭제: &group.parts[index],
522삭제: &mut Some(&mut file),
523삭제: &mut whole,
524삭제: &mut processed,
525삭제: &mut reported,
526삭제: step,
527삭제: )?;
528삭제: group.parts[index].hash = hash;
529삭제: step(Step::Activity)?;
530삭제: }
531삭제: step(Step::Read {
532삭제: bytes: processed,
533삭제: total: group.total,
534삭제: })?;
535삭제: let hash = whole.finalize().into();
542추가: let (mut file, hash) = loop {
543추가: match group.capture(step) {
544추가: Err(failure)
545추가: if failure.error == ErrorCode::DiskFull && crate::spool::next_after_full()? =>
546추가: {
547추가: continue;
548추가: }
549추가: result => break result?,
550추가: }
551추가: };
536552 let object = SourceObject::SplitSevenZip {
537553 manifest_sha256: group.manifest()?,
538554 };
수정experiments/rust-archive-worker/src/spool.rs+162-28
@@ -8,27 +8,107 @@ use std::{
88
99type Result<T> = std::result::Result<T, ErrorCode>;
1010
11추가: enum Placement {
12추가: Fixed(filesystem::Dir),
13추가: Fallback {
14추가: source_parent: std::path::PathBuf,
15추가: next: usize,
16추가: other_error: Option<ErrorCode>,
17추가: },
18추가: }
19추가:
1120thread_local! {
12삭제: // 작업 스레드가 지정한 임시 파일 위치. 없으면 시스템 임시 폴더를 사용함.
13삭제: static LOCATION: std::cell::RefCell<Option<filesystem::Dir>> =
21추가: // 작업 스레드의 임시 파일 정책만 보관함.
22추가: static LOCATION: std::cell::RefCell<Option<Placement>> =
1423 const { std::cell::RefCell::new(None) };
1524 // 출력 폴더에 이름 있는 임시 파일을 만든 뒤 이름을 지우지 못했는지 기록함.
1625 static LEFTOVER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1726}
1827
19삭제: /// 해제 작업의 임시 파일을 출력 폴더에 두도록 지정함. 반환값이 사라지면 해제됨.
20삭제: /// 작업은 한 스레드에서 실행되므로 다른 작업이나 시험에 섞이지 않음.
21삭제: pub(crate) struct Location(());
28추가: pub(crate) struct Location(Option<Placement>);
2229impl Drop for Location {
2330 fn drop(&mut self) {
24삭제: LOCATION.with(|location| *location.borrow_mut() = None);
31추가: LOCATION.with(|location| *location.borrow_mut() = self.0.take());
2532 }
2633}
2734pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> {
28삭제: let dir = dir.duplicate()?;
29삭제: LOCATION.with(|location| *location.borrow_mut() = Some(dir));
35추가: let placement = Placement::Fixed(dir.duplicate()?);
36추가: LEFTOVER.with(|leftover| leftover.set(false));
37추가: Ok(LOCATION.with(|location| Location(location.replace(Some(placement)))))
38추가: }
39추가: pub(crate) fn fallback_for(path: &Path) -> Location {
3040 LEFTOVER.with(|leftover| leftover.set(false));
31삭제: Ok(Location(()))
41추가: let placement = Placement::Fallback {
42추가: source_parent: path.parent().unwrap_or(Path::new("")).to_path_buf(),
43추가: next: 0,
44추가: other_error: None,
45추가: };
46추가: LOCATION.with(|location| Location(location.replace(Some(placement))))
47추가: }
48추가:
49추가: #[cfg(target_os = "linux")]
50추가: fn private_directory(path: &Path) -> Result<filesystem::Dir> {
51추가: if !path.is_absolute() {
52추가: return Err(ErrorCode::Io);
53추가: }
54추가: match filesystem::Dir::root(path) {
55추가: Ok(dir) => Ok(dir),
56추가: Err(error) => {
57추가: if !matches!(std::fs::symlink_metadata(path), Err(ref e) if e.kind() == std::io::ErrorKind::NotFound)
58추가: {
59추가: return Err(error);
60추가: }
61추가: let parent = private_directory(path.parent().ok_or(ErrorCode::Io)?)?;
62추가: let name = path
63추가: .file_name()
64추가: .and_then(|n| n.to_str())
65추가: .ok_or(ErrorCode::Io)?;
66추가: parent.child(name, true)?.ok_or(ErrorCode::Io)
67추가: }
68추가: }
69추가: }
70추가: fn cache_directory() -> Result<filesystem::Dir> {
71추가: #[cfg(target_os = "linux")]
72추가: {
73추가: let base = match std::env::var_os("XDG_CACHE_HOME").filter(|p| !p.is_empty()) {
74추가: Some(path) => std::path::PathBuf::from(path),
75추가: None => std::path::PathBuf::from(std::env::var_os("HOME").ok_or(ErrorCode::Io)?)
76추가: .join(".cache"),
77추가: };
78추가: private_directory(&base)?
79추가: .child("zipelo", true)?
80추가: .ok_or(ErrorCode::Io)
81추가: }
82추가: #[cfg(windows)]
83추가: {
84추가: let base = std::path::PathBuf::from(std::env::var_os("LOCALAPPDATA").ok_or(ErrorCode::Io)?);
85추가: if !base.is_absolute() {
86추가: return Err(ErrorCode::Io);
87추가: }
88추가: filesystem::Dir::root(&base)?
89추가: .child("Zipelo", true)?
90추가: .ok_or(ErrorCode::Io)?
91추가: .child("Temp", true)?
92추가: .ok_or(ErrorCode::Io)
93추가: }
94추가: }
95추가: pub(crate) fn next_after_full() -> Result<bool> {
96추가: LOCATION.with(|location| {
97추가: let mut location = location.borrow_mut();
98추가: match location.as_mut() {
99추가: Some(Placement::Fallback {
100추가: next, other_error, ..
101추가: }) => {
102추가: *next += 1;
103추가: if *next >= 3 {
104추가: Err(other_error.unwrap_or(ErrorCode::DiskFull))
105추가: } else {
106추가: Ok(true)
107추가: }
108추가: }
109추가: _ => Ok(false),
110추가: }
111추가: })
32112}
33113
34114/// 출력 폴더에 지우지 못한 임시 파일이 남았음을 기록함. Windows 임시 파일은 닫으면 지워지므로
@@ -43,33 +123,67 @@ pub(crate) fn take_leftover() -> bool {
43123 LEFTOVER.with(|leftover| leftover.replace(false))
44124}
45125
126추가: /// 실패한 단계의 임시 파일이 닫힌 뒤 다음 위치에서 다시 시도함.
127추가: pub(crate) fn retry_full<T>(mut operation: impl FnMut() -> Result<T>) -> Result<T> {
128추가: loop {
129추가: match operation() {
130추가: Err(ErrorCode::DiskFull) if next_after_full()? => continue,
131추가: result => return result,
132추가: }
133추가: }
134추가: }
135추가:
46136pub(crate) fn random_name() -> Result<String> {
47137 let mut random = [0; 16];
48138 crate::crypto::random(&mut random)?;
49139 Ok(random.iter().map(|b| format!("{b:02x}")).collect())
50140}
51141
52삭제: /// 이름 없는 임시 파일을 만듦. 해제 작업에서는 출력 폴더에, 그 외에는 시스템 임시 폴더에 둠.
53삭제: /// 출력 폴더에 두면 공간 판단이 실제 출력 디스크와 같아지고 /tmp 크기나 할당량에 묶이지 않음.
54삭제: /// 출력 폴더에 만들지 못하면(읽기 전용, 공간 부족 등) 이 작업의 남은 임시 파일은 모두
55삭제: /// 기존 시스템 임시 폴더에 둠. 그러면 동작과 오류 우선순위가 이전과 같아지며, 출력 폴더
56삭제: /// 문제는 원래의 출력 확인 지점에서 보고됨.
142추가: /// 지정한 정책에 따라 이름 없는 임시 파일을 만듦.
57143pub(crate) fn temporary() -> Result<File> {
58삭제: let placed =
59삭제: LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary));
60삭제: let destination_full = matches!(&placed, Some(Err(ErrorCode::DiskFull)));
61삭제: match placed {
62삭제: Some(Ok(file)) => return Ok(file),
63삭제: Some(Err(_)) => LOCATION.with(|location| *location.borrow_mut() = None),
64삭제: None => {}
65삭제: }
66삭제: system_temporary().map_err(|error| {
67삭제: if destination_full {
68삭제: ErrorCode::DiskFull
69삭제: } else {
70삭제: error
144추가: let placed = LOCATION.with(|location| {
145추가: let mut location = location.borrow_mut();
146추가: match location.as_mut() {
147추가: Some(Placement::Fixed(dir)) => match dir.temporary() {
148추가: Ok(file) => Some(Ok(file)),
149추가: Err(error) => {
150추가: *location = None;
151추가: Some(system_temporary().map_err(|fallback| {
152추가: if error == ErrorCode::DiskFull {
153추가: ErrorCode::DiskFull
154추가: } else {
155추가: fallback
156추가: }
157추가: }))
158추가: }
159추가: },
160추가: Some(Placement::Fallback {
161추가: source_parent,
162추가: next,
163추가: other_error,
164추가: }) => {
165추가: while *next < 3 {
166추가: let file = match *next {
167추가: 0 => cache_directory().and_then(|dir| dir.temporary()),
168추가: 1 => filesystem::Dir::root(source_parent).and_then(|dir| dir.temporary()),
169추가: _ => system_temporary(),
170추가: };
171추가: match file {
172추가: Ok(file) => return Some(Ok(file)),
173추가: Err(error) => {
174추가: if error != ErrorCode::DiskFull {
175추가: *other_error = Some(ErrorCode::Io);
176추가: }
177추가: *next += 1;
178추가: }
179추가: }
180추가: }
181추가: Some(Err(other_error.unwrap_or(ErrorCode::DiskFull)))
182추가: }
183추가: None => None,
71184 }
72삭제: })
185추가: });
186추가: placed.unwrap_or_else(system_temporary)
73187}
74188
75189fn system_temporary() -> Result<File> {
@@ -204,6 +318,26 @@ impl Snapshot {
204318 source: &mut File,
205319 limit: u64,
206320 step: &mut impl FnMut(Step) -> Result<()>,
321추가: ) -> Result<Self> {
322추가: let original = source.metadata().map_err(|_| ErrorCode::Io)?;
323추가: loop {
324추가: step(Step::Check)?;
325추가: let current = source.metadata().map_err(|_| ErrorCode::Io)?;
326추가: if current.len() != original.len()
327추가: || current.modified().ok() != original.modified().ok()
328추가: {
329추가: return Err(ErrorCode::SourceChanged);
330추가: }
331추가: match Self::capture_once(source, limit, step) {
332추가: Err(ErrorCode::DiskFull) if next_after_full()? => continue,
333추가: result => return result,
334추가: }
335추가: }
336추가: }
337추가: fn capture_once(
338추가: source: &mut File,
339추가: limit: u64,
340추가: step: &mut impl FnMut(Step) -> Result<()>,
207341 ) -> Result<Self> {
208342 let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?;
209343 if !before.is_file() {
수정experiments/rust-archive-worker/src/streaming.rs+13-0
@@ -74,6 +74,19 @@ impl Catalog {
7474 password: Option<&[u8]>,
7575 selected: Option<u32>,
7676 check: &mut impl crate::resources::Monitor,
77추가: ) -> Result<Self> {
78추가: spool::retry_full(|| {
79추가: Self::open_selected_once(source, len, limits, decode, password, selected, check)
80추가: })
81추가: }
82추가: fn open_selected_once(
83추가: source: &mut File,
84추가: len: u64,
85추가: limits: Limits,
86추가: decode: bool,
87추가: password: Option<&[u8]>,
88추가: selected: Option<u32>,
89추가: check: &mut impl crate::resources::Monitor,
7790 ) -> Result<Self> {
7891 let mut magic = [0; 6];
7992 let n = len.min(6) as usize;
수정tests/rust-archive-worker/main.rs+3-0
@@ -1637,3 +1637,6 @@ mod partial_output;
16371637
16381638#[cfg(target_os = "linux")]
16391639mod spool_location;
1640추가:
1641추가: #[cfg(target_os = "linux")]
1642추가: mod spool_fallback;
추가tests/rust-archive-worker/spool_fallback.rs+539-0
@@ -0,0 +1,539 @@
1추가: use super::*;
2추가: use std::{
3추가: io::Read,
4추가: os::unix::fs::{DirBuilderExt, PermissionsExt},
5추가: process::Child,
6추가: sync::mpsc,
7추가: time::Duration,
8추가: };
9추가:
10추가: struct Running(Child);
11추가: impl Drop for Running {
12추가: fn drop(&mut self) {
13추가: let _ = self.0.kill();
14추가: let _ = self.0.wait();
15추가: }
16추가: }
17추가:
18추가: const PAYLOAD: &[u8] = b"spool fallback preview\n";
19추가: struct Case {
20추가: scratch: Scratch,
21추가: archive_names: Vec<String>,
22추가: }
23추가: impl Case {
24추가: fn new() -> Self {
25추가: let scratch = Scratch::new();
26추가: for name in ["cache", "archive", "system"] {
27추가: fs::DirBuilder::new()
28추가: .mode(0o700)
29추가: .create(scratch.0.join(name))
30추가: .unwrap();
31추가: }
32추가: assert!(
33추가: Command::new("python3")
34추가: .arg("-B")
35추가: .arg(
36추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
37추가: .join("../../tests/rust-archive-worker/spool_fallback_cases.py")
38추가: )
39추가: .arg(&scratch.0)
40추가: .status()
41추가: .unwrap()
42추가: .success()
43추가: );
44추가: Self {
45추가: scratch,
46추가: archive_names: vec!["input.7z".into(), "input.zip".into()],
47추가: }
48추가: }
49추가: fn split(&mut self) -> (NativePath, Vec<(PathBuf, Vec<u8>)>) {
50추가: let bytes = fs::read(self.archive("7z").to_path().unwrap()).unwrap();
51추가: let mut originals = Vec::new();
52추가: for (index, chunk) in bytes.chunks(bytes.len().div_ceil(9)).enumerate() {
53추가: let name = format!("split.7z.{:03}", index + 1);
54추가: let path = self.scratch.0.join("archive").join(&name);
55추가: fs::write(&path, chunk).unwrap();
56추가: originals.push((path, chunk.to_vec()));
57추가: self.archive_names.push(name);
58추가: }
59추가: self.archive_names.sort();
60추가: (self.scratch.path("archive/split.7z.001"), originals)
61추가: }
62추가: fn run(&self, action: Action, phase: &str, mask: u8, named: bool) -> Vec<Message> {
63추가: let s = &self.scratch;
64추가: let mut command = s.worker();
65추가: command
66추가: .env("XDG_CACHE_HOME", s.0.join("cache"))
67추가: .env(
68추가: "TMPDIR",
69추가: if phase == "real" {
70추가: PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap())
71추가: } else {
72추가: s.0.join("system")
73추가: },
74추가: )
75추가: .env("HOME", &s.0);
76추가: if phase == "home" {
77추가: command.env_remove("XDG_CACHE_HOME");
78추가: }
79추가: if phase == "changed" {
80추가: command.env(
81추가: "ZIPELO_SPOOL_SOURCE",
82추가: match &action {
83추가: Action::List { archive } | Action::Preview { archive, .. } => {
84추가: archive.to_path().unwrap()
85추가: }
86추가: _ => panic!("source mutation requires an archive"),
87추가: },
88추가: );
89추가: }
90추가: if phase != "real" {
91추가: let library = s.0.join("location.so");
92추가: if !library.exists() {
93추가: assert!(
94추가: Command::new("cc")
95추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
96추가: .arg(
97추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
98추가: .join("../../tests/rust-archive-worker/spool_location_fault.c")
99추가: )
100추가: .args(["-ldl", "-o"])
101추가: .arg(&library)
102추가: .status()
103추가: .unwrap()
104추가: .success()
105추가: );
106추가: }
107추가: command
108추가: .env("LD_PRELOAD", library)
109추가: .env("ZIPELO_SPOOL_PHASE", phase)
110추가: .env("ZIPELO_SPOOL_MASK", mask.to_string())
111추가: .env("ZIPELO_SPOOL_TRACE", s.0.join("trace"));
112추가: if named {
113추가: command.env("ZIPELO_SPOOL_NAMED", "1");
114추가: }
115추가: }
116추가: let mut child = Running(
117추가: command
118추가: .stdin(Stdio::piped())
119추가: .stdout(Stdio::piped())
120추가: .stderr(Stdio::piped())
121추가: .spawn()
122추가: .unwrap(),
123추가: );
124추가: let preview = matches!(action, Action::Preview { .. });
125추가: let start = Start {
126추가: action,
127추가: limits: Limits::default(),
128추가: };
129추가: let message = if preview {
130추가: Message::StartGuarded(GuardedStart {
131추가: start,
132추가: ceiling: Limits::default(),
133추가: interactive: true,
134추가: })
135추가: } else {
136추가: Message::Start(start)
137추가: };
138추가: let mut writer = Some(Writer::new(child.0.stdin.take().unwrap(), 17));
139추가: writer.as_mut().unwrap().send(&message).unwrap();
140추가: let stdout = child.0.stdout.take().unwrap();
141추가: let mut stderr = child.0.stderr.take().unwrap();
142추가: let (send, receive) = mpsc::sync_channel(128);
143추가: let reader = std::thread::spawn(move || {
144추가: let mut reader = Reader::new(stdout);
145추가: loop {
146추가: let frame = reader.read();
147추가: let done = !matches!(frame, Ok(Some(_)));
148추가: if send.send(frame).is_err() || done {
149추가: break;
150추가: }
151추가: }
152추가: });
153추가: let mut events = Vec::new();
154추가: loop {
155추가: let Some((job, _, event)) = receive
156추가: .recv_timeout(Duration::from_secs(30))
157추가: .expect("worker timeout")
158추가: .unwrap()
159추가: else {
160추가: break;
161추가: };
162추가: assert_eq!(job, 17);
163추가: assert!(
164추가: !matches!(
165추가: event,
166추가: Message::ResourceRequired { .. } | Message::PasswordRequired { .. }
167추가: ),
168추가: "{event:?}"
169추가: );
170추가: if matches!(event, Message::Terminal(_)) {
171추가: drop(writer.take());
172추가: }
173추가: events.push(event);
174추가: }
175추가: assert!(child.0.wait().unwrap().success(), "{events:?}");
176추가: let mut errors = Vec::new();
177추가: stderr.read_to_end(&mut errors).unwrap();
178추가: assert!(errors.is_empty(), "{errors:?}");
179추가: reader.join().unwrap();
180추가: assert_eq!(
181추가: events
182추가: .iter()
183추가: .filter(|e| matches!(e, Message::Terminal(_)))
184추가: .count(),
185추가: 1
186추가: );
187추가: self.clean();
188추가: events
189추가: }
190추가: fn archive(&self, format: &str) -> NativePath {
191추가: self.scratch.path(&format!("archive/input.{format}"))
192추가: }
193추가: fn list(&self, format: &str, phase: &str, mask: u8, named: bool) -> Vec<Message> {
194추가: self.run(
195추가: Action::List {
196추가: archive: self.archive(format),
197추가: },
198추가: phase,
199추가: mask,
200추가: named,
201추가: )
202추가: }
203추가: fn clean(&self) {
204추가: let root = &self.scratch.0;
205추가: for directory in ["cache/zipelo", ".cache/zipelo", "system"] {
206추가: let path = root.join(directory);
207추가: if path.is_dir() {
208추가: assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "{path:?}");
209추가: }
210추가: }
211추가: let mut names: Vec<_> = fs::read_dir(root.join("archive"))
212추가: .unwrap()
213추가: .map(|entry| entry.unwrap().file_name().into_string().unwrap())
214추가: .collect();
215추가: names.sort();
216추가: assert_eq!(names, self.archive_names);
217추가: }
218추가: fn preview(&self, format: &str, phase: &str, mask: u8, named: bool) -> Vec<Message> {
219추가: let events = self.list(format, phase, mask, named);
220추가: assert_eq!(
221추가: terminal(&events).outcome,
222추가: Outcome::Completed,
223추가: "{format}/{phase}/{mask}: {events:?}"
224추가: );
225추가: let list_id = events
226추가: .iter()
227추가: .find_map(|e| match e {
228추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
229추가: _ => None,
230추가: })
231추가: .unwrap();
232추가: let entry_id = events
233추가: .iter()
234추가: .find_map(|e| match e {
235추가: Message::Entry(entry) if entry.name == "preview.txt" => Some(entry.entry_id),
236추가: _ => None,
237추가: })
238추가: .unwrap();
239추가: self.run(
240추가: Action::Preview {
241추가: archive: self.archive(format),
242추가: list_id,
243추가: entry_id,
244추가: },
245추가: phase,
246추가: mask,
247추가: named,
248추가: )
249추가: }
250추가: fn assert_preview(&self, format: &str, phase: &str, mask: u8, named: bool) {
251추가: let path = self.scratch.0.join(format!("archive/input.{format}"));
252추가: let original = fs::read(&path).unwrap();
253추가: assert!(original.len() > 16 * 1024 * 1024);
254추가: let events = self.preview(format, phase, mask, named);
255추가: assert_eq!(
256추가: terminal(&events).outcome,
257추가: Outcome::Completed,
258추가: "{format}/{phase}/{mask}: {events:?}"
259추가: );
260추가: let mut preview = Vec::new();
261추가: for event in &events {
262추가: if let Message::PreviewChunk { data, .. } = event {
263추가: preview.extend_from_slice(data);
264추가: }
265추가: }
266추가: assert_eq!(preview, PAYLOAD);
267추가: assert!(
268추가: events
269추가: .iter()
270추가: .any(|e| matches!(e, Message::PreviewEnd { .. }))
271추가: );
272추가: assert_eq!(fs::read(path).unwrap(), original);
273추가: }
274추가: }
275추가: #[test]
276추가: fn cache_source_and_system_locations_retry_creation_space_and_partial_quota_writes() {
277추가: for named in [false, true] {
278추가: for phase in ["create", "space", "write"] {
279추가: for mask in [0, 1, 3] {
280추가: let c = Case::new();
281추가: for format in ["zip", "7z"] {
282추가: c.assert_preview(format, phase, mask, named);
283추가: }
284추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
285추가: let expected = match mask {
286추가: 0 => '0',
287추가: 1 => '1',
288추가: _ => '2',
289추가: };
290추가: assert!(trace.contains(expected), "{phase}/{mask}: {trace}");
291추가: if mask == 0 {
292추가: assert!(!trace.contains('1') && !trace.contains('2'), "{trace}");
293추가: }
294추가: if mask == 1 {
295추가: assert!(!trace.contains('2'), "{trace}");
296추가: }
297추가: }
298추가: }
299추가: }
300추가: }
301추가: #[test]
302추가: fn split_seven_zip_retries_all_locations_after_partial_quota_writes() {
303추가: use sha2::{Digest, Sha256};
304추가: for named in [false, true] {
305추가: for phase in ["write", "space", "create"] {
306추가: for mask in [1, 3, 7] {
307추가: let mut c = Case::new();
308추가: let (archive, originals) = c.split();
309추가: assert_eq!(originals.len(), 9);
310추가: let bytes = fs::read(c.archive("7z").to_path().unwrap()).unwrap();
311추가: let zip = fs::read(c.archive("zip").to_path().unwrap()).unwrap();
312추가: let events = c.run(Action::List { archive }, phase, mask, named);
313추가: if mask == 7 {
314추가: assert_eq!(
315추가: terminal(&events).outcome,
316추가: Outcome::Failed,
317추가: "{phase}/{named}: {events:?}"
318추가: );
319추가: assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}");
320추가: assert!(!events.iter().any(|e| matches!(e, Message::ListEnd { .. })));
321추가: } else {
322추가: assert_eq!(
323추가: terminal(&events).outcome,
324추가: Outcome::Completed,
325추가: "{phase}/{mask}/{named}: {events:?}"
326추가: );
327추가: let id = events
328추가: .iter()
329추가: .find_map(|e| match e {
330추가: Message::ListEnd { list_id, .. } => Some(list_id),
331추가: _ => None,
332추가: })
333추가: .unwrap();
334추가: assert_eq!(id.catalog_version, 2);
335추가: assert_eq!(id.format, Format::SevenZip);
336추가: assert_eq!(id.archive_bytes, bytes.len() as u64);
337추가: assert_eq!(
338추가: id.archive_sha256.as_slice(),
339추가: Sha256::digest(&bytes).as_slice()
340추가: );
341추가: assert!(matches!(
342추가: id.source_object,
343추가: SourceObject::SplitSevenZip { .. }
344추가: ));
345추가: assert!(events.iter().any(
346추가: |e| matches!(e, Message::Entry(entry) if entry.name == "preview.txt")
347추가: ));
348추가: }
349추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
350추가: for at in if mask == 1 {
351추가: &['0', '1'][..]
352추가: } else {
353추가: &['0', '1', '2'][..]
354추가: } {
355추가: assert!(trace.contains(*at), "{phase}/{mask}/{named}: {trace}");
356추가: }
357추가: if mask == 1 {
358추가: assert!(!trace.contains('2'), "{trace}");
359추가: }
360추가: for (path, original) in originals {
361추가: assert_eq!(fs::read(path).unwrap(), original);
362추가: }
363추가: assert_eq!(fs::read(c.archive("7z").to_path().unwrap()).unwrap(), bytes);
364추가: assert_eq!(fs::read(c.archive("zip").to_path().unwrap()).unwrap(), zip);
365추가: }
366추가: }
367추가: }
368추가: }
369추가:
370추가: #[test]
371추가: fn split_source_change_during_failed_copy_prevents_retry_success() {
372추가: for named in [false, true] {
373추가: let mut c = Case::new();
374추가: let (archive, originals) = c.split();
375추가: let events = c.run(Action::List { archive }, "changed", 1, named);
376추가: assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
377추가: assert_eq!(
378추가: terminal(&events).error,
379추가: ErrorCode::SourceChanged,
380추가: "{events:?}"
381추가: );
382추가: assert!(!events.iter().any(|e| matches!(e, Message::ListEnd { .. })));
383추가: for (index, (path, mut bytes)) in originals.into_iter().enumerate() {
384추가: if index == 0 {
385추가: bytes.push(b'x');
386추가: }
387추가: assert_eq!(fs::read(path).unwrap(), bytes);
388추가: }
389추가: }
390추가: }
391추가:
392추가: #[test]
393추가: fn disk_full_requires_exhausting_all_three_locations_and_io_errors_stay_io() {
394추가: for phase in ["create", "space", "write"] {
395추가: let c = Case::new();
396추가: for format in ["zip", "7z"] {
397추가: let events = c.list(format, phase, 7, false);
398추가: assert_eq!(
399추가: terminal(&events).error,
400추가: ErrorCode::DiskFull,
401추가: "{phase}: {events:?}"
402추가: );
403추가: assert_eq!(terminal(&events).outcome, Outcome::Failed);
404추가: assert!(!events.iter().any(|e| matches!(e, Message::ListEnd { .. })));
405추가: }
406추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
407추가: for at in ['0', '1', '2'] {
408추가: assert!(trace.contains(at), "{phase}: {trace}");
409추가: }
410추가: }
411추가: let c = Case::new();
412추가: for phase in ["io", "denied"] {
413추가: let events = c.list("zip", phase, 7, false);
414추가: assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
415추가: }
416추가: }
417추가: #[test]
418추가: fn unsafe_cache_is_skipped_without_following_its_link() {
419추가: use std::os::unix::fs::symlink;
420추가: let c = Case::new();
421추가: fs::DirBuilder::new()
422추가: .mode(0o700)
423추가: .create(c.scratch.0.join("outside"))
424추가: .unwrap();
425추가: symlink(
426추가: c.scratch.0.join("outside"),
427추가: c.scratch.0.join("cache/zipelo"),
428추가: )
429추가: .unwrap();
430추가: let events = c.list("zip", "create", 0, false);
431추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
432추가: assert_eq!(
433추가: fs::read_dir(c.scratch.0.join("outside")).unwrap().count(),
434추가: 0
435추가: );
436추가: fs::remove_file(c.scratch.0.join("cache/zipelo")).unwrap();
437추가: c.clean();
438추가: }
439추가: #[test]
440추가: fn preview_decode_retries_when_snapshot_fits_but_decoded_staging_does_not() {
441추가: for named in [false, true] {
442추가: for phase in ["stage-space", "stage-write"] {
443추가: for mask in [1, 3] {
444추가: let c = Case::new();
445추가: for format in ["zip", "7z"] {
446추가: c.assert_preview(format, phase, mask, named);
447추가: }
448추가: }
449추가: let c = Case::new();
450추가: for format in ["zip", "7z"] {
451추가: let events = c.preview(format, phase, 7, named);
452추가: assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
453추가: assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}");
454추가: assert!(
455추가: !events
456추가: .iter()
457추가: .any(|event| matches!(event, Message::PreviewEnd { .. }))
458추가: );
459추가: }
460추가: }
461추가: }
462추가: }
463추가:
464추가: #[test]
465추가: fn default_home_cache_is_created_privately() {
466추가: let c = Case::new();
467추가: c.assert_preview("zip", "home", 0, false);
468추가: for name in [".cache", ".cache/zipelo"] {
469추가: assert_eq!(
470추가: fs::metadata(c.scratch.0.join(name))
471추가: .unwrap()
472추가: .permissions()
473추가: .mode()
474추가: & 0o777,
475추가: 0o700
476추가: );
477추가: }
478추가: }
479추가:
480추가: #[test]
481추가: fn source_change_during_failed_copy_prevents_retry_success() {
482추가: let c = Case::new();
483추가: let events = c.list("zip", "changed", 1, false);
484추가: assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
485추가: assert_eq!(
486추가: terminal(&events).error,
487추가: ErrorCode::SourceChanged,
488추가: "{events:?}"
489추가: );
490추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
491추가: assert!(
492추가: trace.contains('0') && !trace.contains('1') && !trace.contains('2'),
493추가: "{trace}"
494추가: );
495추가: }
496추가:
497추가: #[test]
498추가: #[ignore = "별도 VM의 작은 tmpfs 경로를 ZIPELO_SPOOL_REAL_TMP로 지정해야 함"]
499추가: fn actual_tmpfs_quota_lists_and_previews_large_zip_and_seven_zip() {
500추가: let path = PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap());
501추가: let filesystem = Command::new("stat")
502추가: .args(["-f", "-c", "%T"])
503추가: .arg(&path)
504추가: .output()
505추가: .unwrap();
506추가: assert_eq!(
507추가: String::from_utf8(filesystem.stdout).unwrap().trim(),
508추가: "tmpfs"
509추가: );
510추가: let capacity = Command::new("stat")
511추가: .args(["-f", "-c", "%S %b"])
512추가: .arg(&path)
513추가: .output()
514추가: .unwrap();
515추가: let fields: Vec<u64> = String::from_utf8(capacity.stdout)
516추가: .unwrap()
517추가: .split_whitespace()
518추가: .map(|value| value.parse().unwrap())
519추가: .collect();
520추가: let bytes = fields[0] * fields[1];
521추가: assert!(bytes > 0 && bytes < 16 * 1024 * 1024, "{bytes}");
522추가: let probe = path.join("capacity-probe");
523추가: let error = fs::write(&probe, vec![0; bytes as usize + 4096]).unwrap_err();
524추가: assert_eq!(error.kind(), std::io::ErrorKind::StorageFull);
525추가: fs::remove_file(probe).unwrap();
526추가: let c = Case::new();
527추가: for format in ["zip", "7z"] {
528추가: c.assert_preview(format, "real", 0, false);
529추가: }
530추가: assert_eq!(fs::read_dir(path).unwrap().count(), 0);
531추가: assert_eq!(
532추가: fs::metadata(c.scratch.0.join("cache/zipelo"))
533추가: .unwrap()
534추가: .permissions()
535추가: .mode()
536추가: & 0o777,
537추가: 0o700
538추가: );
539추가: }
추가tests/rust-archive-worker/spool_fallback_cases.py+18-0
@@ -0,0 +1,18 @@
1추가: """시스템 임시 폴더보다 큰 독립 ZIP과 7z 입력을 만듦."""
2추가: from pathlib import Path
3추가: import sys
4추가: import zipfile
5추가:
6추가: from seven_zip_fixtures import archive
7추가:
8추가: root = Path(sys.argv[1])
9추가: payload = b"spool fallback preview\n"
10추가: filler = bytes(range(256)) * (16 * 1024 * 1024 // 256)
11추가: with zipfile.ZipFile(
12추가: root / "archive" / "input.zip", "w", compression=zipfile.ZIP_STORED
13추가: ) as target:
14추가: target.writestr("preview.txt", payload)
15추가: target.writestr("filler.bin", filler)
16추가: (root / "archive" / "input.7z").write_bytes(
17추가: archive([("preview.txt", payload, 0x20), ("filler.bin", filler, 0x20)], method="copy")
18추가: )
추가tests/rust-archive-worker/spool_location_fault.c+136-0
@@ -0,0 +1,136 @@
1추가: #define _GNU_SOURCE
2추가: #include <dlfcn.h>
3추가: #include <errno.h>
4추가: #include <fcntl.h>
5추가: #include <stdarg.h>
6추가: #include <stdio.h>
7추가: #include <stdlib.h>
8추가: #include <string.h>
9추가: #include <sys/statvfs.h>
10추가: #include <unistd.h>
11추가:
12추가: static int (*original_openat)(int, const char *, int, ...);
13추가: static int (*original_open64)(const char *, int, ...);
14추가: static ssize_t (*original_write)(int, const void *, size_t);
15추가: static int written[3];
16추가: static int snapshot_fd = -1;
17추가:
18추가: __attribute__((constructor)) static void initialize(void) {
19추가: original_openat = dlsym(RTLD_NEXT, "openat");
20추가: original_open64 = dlsym(RTLD_NEXT, "open64");
21추가: original_write = dlsym(RTLD_NEXT, "write");
22추가: }
23추가: static int location(const char *path) {
24추가: if (strstr(path, "/cache/")) return 0;
25추가: if (strstr(path, "/archive/")) return 1;
26추가: if (strstr(path, "/system/")) return 2;
27추가: return -1;
28추가: }
29추가: static int descriptor(int fd, char *path, size_t size) {
30추가: char link[64];
31추가: path[0] = 0;
32추가: snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
33추가: ssize_t length = readlink(link, path, size - 1);
34추가: if (length < 0) return -1;
35추가: path[length] = 0;
36추가: return location(path);
37추가: }
38추가: static int affected(int at) {
39추가: const char *mask = getenv("ZIPELO_SPOOL_MASK");
40추가: return at >= 0 && mask && (atoi(mask) & (1 << at));
41추가: }
42추가: static void trace(int at) {
43추가: const char *path = getenv("ZIPELO_SPOOL_TRACE");
44추가: if (!path || at < 0) return;
45추가: int fd = original_openat(AT_FDCWD, path, O_CREAT | O_WRONLY | O_APPEND, 0600);
46추가: if (fd >= 0) {
47추가: char value = '0' + at;
48추가: original_write(fd, &value, 1);
49추가: close(fd);
50추가: }
51추가: }
52추가: static int reject(int at, int flags) {
53추가: if ((flags & O_TMPFILE) != O_TMPFILE && !(flags & O_CREAT)) return 0;
54추가: trace(at);
55추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
56추가: if (affected(at) && phase && (!strcmp(phase, "create") || !strcmp(phase, "denied"))) {
57추가: errno = !strcmp(phase, "denied") ? EACCES : EDQUOT;
58추가: return 1;
59추가: }
60추가: if (getenv("ZIPELO_SPOOL_NAMED") && (flags & O_TMPFILE) == O_TMPFILE) {
61추가: errno = EOPNOTSUPP;
62추가: return 1;
63추가: }
64추가: return 0;
65추가: }
66추가: int openat(int fd, const char *path, int flags, ...) {
67추가: mode_t mode = 0;
68추가: if ((flags & O_CREAT) || (flags & O_TMPFILE) == O_TMPFILE) {
69추가: va_list args;
70추가: va_start(args, flags);
71추가: mode = va_arg(args, unsigned int);
72추가: va_end(args);
73추가: }
74추가: char parent[4096], full[8192];
75추가: descriptor(fd, parent, sizeof(parent));
76추가: snprintf(full, sizeof(full), "%s/%s", parent, path);
77추가: if (reject(location(full), flags)) return -1;
78추가: int result = original_openat(fd, path, flags, mode);
79추가: if (result >= 0 && snapshot_fd < 0 && location(full) >= 0
80추가: && ((flags & O_TMPFILE) == O_TMPFILE || (flags & O_CREAT))) {
81추가: snapshot_fd = result;
82추가: }
83추가: return result;
84추가: }
85추가: int open64(const char *path, int flags, ...) {
86추가: mode_t mode = 0;
87추가: if ((flags & O_CREAT) || (flags & O_TMPFILE) == O_TMPFILE) {
88추가: va_list args;
89추가: va_start(args, flags);
90추가: mode = va_arg(args, unsigned int);
91추가: va_end(args);
92추가: }
93추가: char full[8192];
94추가: snprintf(full, sizeof(full), "%s/", path);
95추가: if (reject(location(full), flags)) return -1;
96추가: int result = original_open64(path, flags, mode);
97추가: if (result >= 0 && snapshot_fd < 0 && location(full) >= 0
98추가: && ((flags & O_TMPFILE) == O_TMPFILE || (flags & O_CREAT))) {
99추가: snapshot_fd = result;
100추가: }
101추가: return result;
102추가: }
103추가: ssize_t write(int fd, const void *bytes, size_t count) {
104추가: char path[4096];
105추가: int at = descriptor(fd, path, sizeof(path));
106추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
107추가: int stage = phase && !strcmp(phase, "stage-write") && fd != snapshot_fd;
108추가: if (affected(at) && phase && (stage || !strcmp(phase, "write")
109추가: || !strcmp(phase, "changed") || !strcmp(phase, "io"))) {
110추가: if (!strcmp(phase, "io")) { errno = EIO; return -1; }
111추가: if (!written[at]++) return original_write(fd, bytes, count < 7 ? count : 7);
112추가: if (!strcmp(phase, "changed")) {
113추가: int source = original_openat(AT_FDCWD, getenv("ZIPELO_SPOOL_SOURCE"), O_WRONLY | O_APPEND);
114추가: if (source >= 0) {
115추가: original_write(source, "x", 1);
116추가: close(source);
117추가: }
118추가: }
119추가: errno = EDQUOT;
120추가: return -1;
121추가: }
122추가: return original_write(fd, bytes, count);
123추가: }
124추가: int fstatvfs(int fd, struct statvfs *value) {
125추가: int (*original)(int, struct statvfs *) = dlsym(RTLD_NEXT, "fstatvfs");
126추가: int result = original(fd, value);
127추가: char path[4096];
128추가: int at = descriptor(fd, path, sizeof(path));
129추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
130추가: int stage = phase && !strcmp(phase, "stage-space") && fd != snapshot_fd;
131추가: if (!result && affected(at) && phase && (stage || !strcmp(phase, "space"))) {
132추가: value->f_frsize = 1;
133추가: value->f_bavail = stage ? 0 : 1024;
134추가: }
135추가: return result;
136추가: }