team-ljyzipelo

공개

Merge pull request #130 from Team-LJY/fix/partial-output-cleanup

부분 출력 실패 검증과 임시 파일 정리 보강
작성자
LeeJunyoung
작성 시각
커밋
cd45eab3f68179f5a73b7edf4cc6a06ed85c4600
이 시점의 파일 보기

변경된 파일 4개

+500-12
수정experiments/rust-archive-worker/src/filesystem.rs+42-11
@@ -786,12 +786,17 @@ pub(crate) fn publish_reader_steps(
786786 &mut PublicationMonitor(check),
787787 )
788788 })();
789추가: let identity = temporary.as_ref().map(|temp| temp.object.clone());
789790 let closed = completed(
790791 close(file).map_err(crate::space::io_error),
791792 &mut PublicationMonitor(check),
792793 );
793794 let mut finish = written.and(closed).and_then(|_| {
794795 check(PublishStep::Commit(temporary))?;
796추가: // 생성한 임시 파일과 이름이 가리키는 파일이 같은지 확인함.
797추가: if dir.existing(&temp)?.as_ref().map(|file| &file.object) != identity.as_ref() {
798추가: return Err(ErrorCode::Conflict);
799추가: }
795800 // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
796801 if let Some(expected) = replace {
797802 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
@@ -836,19 +841,28 @@ pub(crate) fn publish_reader_steps(
836841 }
837842 }
838843 if !temp_consumed {
839삭제: if dir.remove(&temp) {
840삭제: publication_activity(&mut finish, check);
841삭제: } else {
842삭제: result.cleanup = Cleanup::Failed;
843삭제: result.retained = 1;
844삭제: result.retained_name = Some(match name.rsplit_once('/') {
845삭제: Some((prefix, _)) => format!("{prefix}/{temp}"),
846삭제: None => temp.clone(),
847삭제: });
848삭제: if finish.is_ok() {
849삭제: finish = Err(ErrorCode::Io);
844추가: match dir.existing(&temp) {
845추가: Ok(None) => result.cleanup = Cleanup::Unconfirmed,
846추가: Ok(Some(current)) if Some(&current.object) == identity.as_ref() => {
847추가: if dir.remove(&temp) {
848추가: publication_activity(&mut finish, check);
849추가: } else {
850추가: result.cleanup = Cleanup::Failed;
851추가: result.retained = 1;
852추가: result.retained_name = Some(match name.rsplit_once('/') {
853추가: Some((prefix, _)) => format!("{prefix}/{temp}"),
854추가: None => temp.clone(),
855추가: });
856추가: }
857추가: }
858추가: _ => {
859추가: // 다른 파일은 보존하고 소유 임시 파일의 위치를 단정하지 않음.
860추가: result.cleanup = Cleanup::Unconfirmed;
850861 }
851862 }
863추가: if result.cleanup != Cleanup::Complete && finish.is_ok() {
864추가: finish = Err(ErrorCode::Io);
865추가: }
852866 }
853867 if result.created {
854868 if let Err(error) = dir.sync_checked() {
@@ -858,6 +872,23 @@ pub(crate) fn publish_reader_steps(
858872 publication_activity(&mut finish, check);
859873 }
860874 }
875추가: if result.created {
876추가: // 이름 기반 게시 뒤에도 결과가 생성한 파일인지 확인함.
877추가: let verified = match dir.existing(&leaf) {
878추가: Ok(Some(current)) if Some(&current.object) == identity.as_ref() => Ok(()),
879추가: Ok(_) => Err(ErrorCode::Conflict),
880추가: Err(error) => Err(error),
881추가: };
882추가: if let Err(error) = verified {
883추가: result.created = false;
884추가: result.uncertain = true;
885추가: result.durability = Durability::Unconfirmed;
886추가: if result.cleanup == Cleanup::Complete {
887추가: result.cleanup = Cleanup::Unconfirmed;
888추가: }
889추가: finish = Err(error);
890추가: }
891추가: }
861892 finish
862893 })();
863894 result.error = prepared.err();
수정tests/rust-archive-worker/io_fault.c+58-1
@@ -91,7 +91,7 @@ ssize_t write(int fd, const void *bytes, size_t count) {
9191 return -1;
9292 }
9393 if (!strcmp(fault, "write-io")) { errno = EIO; return -1; }
94삭제: if (!strcmp(fault, "full") || !strcmp(fault, "stage-full")) {
94추가: if (!strcmp(fault, "full") || !strcmp(fault, "stage-full") || !strcmp(fault, "full-cleanup-fail")) {
9595 if (!started++) return real_write(fd, bytes, count < 7 ? count : 7);
9696 errno = ENOSPC;
9797 return -1;
@@ -133,15 +133,72 @@ int fstatvfs(int fd, struct statvfs *value) {
133133int fsync(int fd) {
134134 const char *fault = getenv("ZIPELO_TEST_FAULT");
135135 struct stat st;
136추가: if (fault && !strcmp(fault, "move-on-sync") && output_file(fd)) {
137추가: char link[64], path[4096], moved[4112];
138추가: snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
139추가: ssize_t count = readlink(link, path, sizeof(path) - 1);
140추가: if (count < 0) { errno = EIO; return -1; }
141추가: path[count] = 0;
142추가: snprintf(moved, sizeof(moved), "%s.owned", path);
143추가: if (rename(path, moved)) { errno = EIO; return -1; }
144추가: return real_fsync(fd);
145추가: }
136146 int directory_full = fault && !strcmp(fault, "dir-sync-full")
137147 && !fstat(fd, &st) && S_ISDIR(st.st_mode);
138148 if (directory_full || (fault && !strcmp(fault, "sync-full") && output_file(fd))) {
139149 errno = ENOSPC;
140150 return -1;
141151 }
152추가: if (fault && output_file(fd) && (!strcmp(fault, "sync-io") || !strcmp(fault, "sync-cleanup-fail") || !strcmp(fault, "swap-sync") || !strcmp(fault, "swap-publish"))) {
153추가: if (!strcmp(fault, "swap-sync") || !strcmp(fault, "swap-publish")) {
154추가: char link[64], path[4096], moved[4112];
155추가: snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
156추가: ssize_t count = readlink(link, path, sizeof(path) - 1);
157추가: if (count < 0) { errno = EIO; return -1; }
158추가: path[count] = 0;
159추가: snprintf(moved, sizeof(moved), "%s.owned", path);
160추가: if (rename(path, moved)) { errno = EIO; return -1; }
161추가: int replacement = real_openat(AT_FDCWD, path, O_CREAT | O_EXCL | O_WRONLY, 0600);
162추가: if (replacement < 0) { errno = EIO; return -1; }
163추가: real_write(replacement, "unrelated replacement", 21);
164추가: close(replacement);
165추가: if (!strcmp(fault, "swap-publish")) return real_fsync(fd);
166추가: }
167추가: errno = EIO;
168추가: return -1;
169추가: }
170추가: if (fault && !strcmp(fault, "dir-sync-io") && !fstat(fd, &st) && S_ISDIR(st.st_mode)) {
171추가: errno = EIO;
172추가: return -1;
173추가: }
142174 return real_fsync(fd);
143175}
144176
177추가: int unlinkat(int fd, const char *path, int flags) {
178추가: const char *fault = getenv("ZIPELO_TEST_FAULT");
179추가: if (fault && strstr(fault, "cleanup-fail") && !strncmp(path, ".zipelo-", 8)) {
180추가: errno = EACCES;
181추가: return -1;
182추가: }
183추가: int (*real_unlinkat)(int, const char *, int) = dlsym(RTLD_NEXT, "unlinkat");
184추가: return real_unlinkat(fd, path, flags);
185추가: }
186추가:
187추가: int linkat(int oldfd, const char *oldname, int newfd, const char *newname, int flags) {
188추가: int (*real_linkat)(int, const char *, int, const char *, int) = dlsym(RTLD_NEXT, "linkat");
189추가: const char *fault = getenv("ZIPELO_TEST_FAULT");
190추가: if (fault && !strcmp(fault, "swap-on-link") && !strncmp(oldname, ".zipelo-", 8)) {
191추가: char moved[512];
192추가: snprintf(moved, sizeof(moved), "%s.owned", oldname);
193추가: if (renameat(oldfd, oldname, oldfd, moved)) return -1;
194추가: int replacement = real_openat(oldfd, oldname, O_CREAT | O_EXCL | O_WRONLY, 0600);
195추가: if (replacement < 0) return -1;
196추가: real_write(replacement, "unrelated replacement", 21);
197추가: close(replacement);
198추가: }
199추가: return real_linkat(oldfd, oldname, newfd, newname, flags);
200추가: }
201추가:
145202int renameat(int oldfd, const char *oldname, int newfd, const char *newname) {
146203 const char *fault = getenv("ZIPELO_TEST_FAULT");
147204 if (fault && !strcmp(fault, "replace-fail")) { errno = EIO; return -1; }
수정tests/rust-archive-worker/main.rs+3-0
@@ -1631,3 +1631,6 @@ mod seven_zip_create;
16311631mod seven_zip_create_runtime;
16321632
16331633mod recovery;
1634추가:
1635추가: #[cfg(target_os = "linux")]
1636추가: mod partial_output;
추가tests/rust-archive-worker/partial_output.rs+397-0
@@ -0,0 +1,397 @@
1추가: use super::*;
2추가: use std::os::unix::fs::DirBuilderExt;
3추가:
4추가: const SOURCE: &[u8] = b"unchanged source";
5추가: const SENTINEL: &[u8] = b"unrelated user file";
6추가:
7추가: fn prepare(s: &Scratch, operation: &str) -> (Start, PathBuf) {
8추가: fs::write(s.0.join("source"), SOURCE).unwrap();
9추가: fs::DirBuilder::new()
10추가: .mode(0o700)
11추가: .create(s.0.join("tmp"))
12추가: .unwrap();
13추가: let (action, output) = match operation {
14추가: "extract" | "extract-nested" => {
15추가: let created = execute(Start {
16추가: action: Action::CreateZip {
17추가: sources: vec![Source {
18추가: path: s.path("source"),
19추가: archive_name: if operation == "extract-nested" {
20추가: "folder/payload"
21추가: } else {
22추가: "payload"
23추가: }
24추가: .into(),
25추가: }],
26추가: output_file: s.path("archive"),
27추가: method: Method::Store,
28추가: encryption: Encryption::None,
29추가: },
30추가: limits: Limits::default(),
31추가: });
32추가: assert_eq!(terminal(&created).outcome, Outcome::Completed);
33추가: fs::DirBuilder::new()
34추가: .mode(0o700)
35추가: .create(s.0.join("output"))
36추가: .unwrap();
37추가: if operation == "extract-nested" {
38추가: fs::DirBuilder::new()
39추가: .mode(0o700)
40추가: .create(s.0.join("output/folder"))
41추가: .unwrap();
42추가: }
43추가: (
44추가: Action::Extract {
45추가: archive: s.path("archive"),
46추가: destination: s.path("output"),
47추가: selection: Selection::All,
48추가: list_id: None,
49추가: gzip_output_name: None,
50추가: },
51추가: s.0.join(if operation == "extract-nested" {
52추가: "output/folder/payload"
53추가: } else {
54추가: "output/payload"
55추가: }),
56추가: )
57추가: }
58추가: "seven-zip" => (
59추가: Action::CreateSevenZip {
60추가: sources: vec![Source {
61추가: path: s.path("source"),
62추가: archive_name: "payload".into(),
63추가: }],
64추가: output_file: s.path("result.7z"),
65추가: method: SevenZipMethod::Lzma2,
66추가: solid: false,
67추가: encryption: Encryption::None,
68추가: },
69추가: s.0.join("result.7z"),
70추가: ),
71추가: "recovery" => {
72추가: fs::write(
73추가: s.0.join("archive"),
74추가: include_bytes!("../zip-recovery-fixtures/broken-local-header.zip"),
75추가: )
76추가: .unwrap();
77추가: (
78추가: Action::RecoverZip {
79추가: archive: s.path("archive"),
80추가: output_file: s.path("recovered.zip"),
81추가: },
82추가: s.0.join("recovered.zip"),
83추가: )
84추가: }
85추가: _ => unreachable!(),
86추가: };
87추가: (
88추가: Start {
89추가: action,
90추가: limits: Limits::default(),
91추가: },
92추가: output,
93추가: )
94추가: }
95추가:
96추가: fn run(s: &Scratch, start: Start, fault: &str) -> Vec<Message> {
97추가: let library = s.0.join("fault.so");
98추가: assert!(
99추가: Command::new("cc")
100추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
101추가: .arg(
102추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
103추가: .join("../../tests/rust-archive-worker/io_fault.c"),
104추가: )
105추가: .args(["-ldl", "-o"])
106추가: .arg(&library)
107추가: .status()
108추가: .unwrap()
109추가: .success()
110추가: );
111추가: let mut child = s
112추가: .worker()
113추가: .env("TMPDIR", s.0.join("tmp"))
114추가: .env("LD_PRELOAD", library)
115추가: .env("ZIPELO_TEST_FAULT", fault)
116추가: .env("ZIPELO_TEST_MARKER", s.0.join("marker"))
117추가: .stdin(Stdio::piped())
118추가: .stdout(Stdio::piped())
119추가: .stderr(Stdio::piped())
120추가: .spawn()
121추가: .unwrap();
122추가: Writer::new(child.stdin.take().unwrap(), 17)
123추가: .send(&Message::Start(start))
124추가: .unwrap();
125추가: let output = child.wait_with_output().unwrap();
126추가: assert!(output.status.success());
127추가: assert!(output.stderr.is_empty(), "{:?}", output.stderr);
128추가: let mut reader = Reader::new(output.stdout.as_slice());
129추가: let mut events = Vec::new();
130추가: while let Some((_, _, event)) = reader.read().unwrap() {
131추가: events.push(event);
132추가: }
133추가: assert_eq!(
134추가: events
135추가: .iter()
136추가: .filter(|e| matches!(e, Message::Terminal(_)))
137추가: .count(),
138추가: 1
139추가: );
140추가: assert_eq!(fs::read_dir(s.0.join("tmp")).unwrap().count(), 0);
141추가: events
142추가: }
143추가:
144추가: #[test]
145추가: fn storage_failure_matrix_preserves_outputs_and_reports_remaining_files() {
146추가: for operation in ["extract", "extract-nested", "seven-zip", "recovery"] {
147추가: for fault in [
148추가: "none",
149추가: "temp-full",
150추가: "create-full",
151추가: "full",
152추가: "sync-full",
153추가: "sync-io",
154추가: "dir-sync-full",
155추가: "dir-sync-io",
156추가: "cleanup-fail",
157추가: "full-cleanup-fail",
158추가: "sync-cleanup-fail",
159추가: ] {
160추가: let s = Scratch::new();
161추가: let (request, output) = prepare(&s, operation);
162추가: let parent = output.parent().unwrap();
163추가: let root = if operation.starts_with("extract") {
164추가: s.0.join("output")
165추가: } else {
166추가: s.0.clone()
167추가: };
168추가: let unrelated = parent.join(".zipelo-unrelated.tmp");
169추가: fs::write(&unrelated, SENTINEL).unwrap();
170추가: let archive = fs::read(s.0.join("archive")).ok();
171추가: let events = run(&s, request, fault);
172추가: let end = terminal(&events);
173추가: let context = format!("{operation}/{fault}: {events:?}");
174추가: let published = matches!(
175추가: fault,
176추가: "none" | "cleanup-fail" | "dir-sync-full" | "dir-sync-io"
177추가: );
178추가: assert_eq!(output.exists(), published, "{context}");
179추가: assert_eq!(end.created_count, u64::from(published), "{context}");
180추가: assert_eq!(
181추가: end.outcome,
182추가: if fault == "none" {
183추가: Outcome::Completed
184추가: } else {
185추가: Outcome::Failed
186추가: },
187추가: "{context}"
188추가: );
189추가: let expected_error = if fault == "none" {
190추가: ErrorCode::None
191추가: } else if matches!(
192추가: fault,
193추가: "sync-io" | "dir-sync-io" | "cleanup-fail" | "sync-cleanup-fail"
194추가: ) {
195추가: ErrorCode::Io
196추가: } else {
197추가: ErrorCode::DiskFull
198추가: };
199추가: assert_eq!(end.error, expected_error, "{context}");
200추가: assert_eq!(
201추가: end.publication,
202추가: if fault == "none" {
203추가: Publication::Complete
204추가: } else if published {
205추가: Publication::Partial
206추가: } else {
207추가: Publication::None
208추가: },
209추가: "{context}"
210추가: );
211추가: assert_eq!(
212추가: end.durability,
213추가: if fault.starts_with("dir-sync") {
214추가: Durability::Failed
215추가: } else if published {
216추가: Durability::Synced
217추가: } else {
218추가: Durability::NotApplicable
219추가: },
220추가: "{context}"
221추가: );
222추가: let retained: Vec<_> = events
223추가: .iter()
224추가: .filter_map(|e| match e {
225추가: Message::Output {
226추가: relative_name,
227추가: disposition: Disposition::PartialRetained,
228추가: ..
229추가: } => Some(relative_name),
230추가: _ => None,
231추가: })
232추가: .collect();
233추가: let cleanup_failed = fault.ends_with("cleanup-fail");
234추가: assert_eq!(
235추가: end.cleanup,
236추가: if cleanup_failed {
237추가: Cleanup::Failed
238추가: } else {
239추가: Cleanup::Complete
240추가: },
241추가: "{context}"
242추가: );
243추가: assert_eq!(
244추가: end.retained_partial_count,
245추가: u64::from(cleanup_failed),
246추가: "{context}"
247추가: );
248추가: assert_eq!(retained.len(), usize::from(cleanup_failed), "{context}");
249추가: for name in retained {
250추가: let path = root.join(name);
251추가: assert!(path.is_file(), "{context}: {path:?}");
252추가: if published {
253추가: assert_eq!(fs::read(path).unwrap(), fs::read(&output).unwrap());
254추가: }
255추가: }
256추가: assert_eq!(fs::read(&unrelated).unwrap(), SENTINEL, "{context}");
257추가: assert_eq!(fs::read(s.0.join("source")).unwrap(), SOURCE, "{context}");
258추가: assert_eq!(fs::read(s.0.join("archive")).ok(), archive, "{context}");
259추가: assert_eq!(
260추가: fs::read_dir(parent)
261추가: .unwrap()
262추가: .filter(|e| {
263추가: let name = e.as_ref().unwrap().file_name();
264추가: let name = name.to_string_lossy();
265추가: name.starts_with(".zipelo-") && name != ".zipelo-unrelated.tmp"
266추가: })
267추가: .count(),
268추가: usize::from(cleanup_failed),
269추가: "{context}"
270추가: );
271추가: if published && operation.starts_with("extract") {
272추가: assert_eq!(fs::read(output).unwrap(), SOURCE, "{context}");
273추가: }
274추가: }
275추가: }
276추가: }
277추가:
278추가: #[test]
279추가: fn cleanup_does_not_delete_a_replacement_at_the_temporary_name() {
280추가: for operation in ["extract", "extract-nested", "seven-zip", "recovery"] {
281추가: for fault in ["swap-sync", "swap-publish"] {
282추가: let s = Scratch::new();
283추가: let (request, output) = prepare(&s, operation);
284추가: let events = run(&s, request, fault);
285추가: let end = terminal(&events);
286추가: assert_eq!(end.outcome, Outcome::Failed, "{operation}: {events:?}");
287추가: assert_eq!(
288추가: end.error,
289추가: if fault == "swap-publish" {
290추가: ErrorCode::Conflict
291추가: } else {
292추가: ErrorCode::Io
293추가: }
294추가: );
295추가: assert!(!output.exists());
296추가: let replacements: Vec<_> = fs::read_dir(output.parent().unwrap())
297추가: .unwrap()
298추가: .map(|e| e.unwrap().path())
299추가: .filter(|p| p.file_name().unwrap().to_string_lossy().ends_with(".tmp"))
300추가: .collect();
301추가: assert_eq!(replacements.len(), 1, "{operation}: {events:?}");
302추가: assert_eq!(
303추가: fs::read(&replacements[0]).unwrap(),
304추가: b"unrelated replacement"
305추가: );
306추가: assert_eq!(end.cleanup, Cleanup::Unconfirmed);
307추가: assert_eq!(end.retained_partial_count, 0);
308추가: assert!(!events.iter().any(|e| matches!(
309추가: e,
310추가: Message::Output {
311추가: disposition: Disposition::PartialRetained,
312추가: ..
313추가: }
314추가: )));
315추가: assert_eq!(fs::read(s.0.join("source")).unwrap(), SOURCE);
316추가: }
317추가: }
318추가: }
319추가:
320추가: #[test]
321추가: fn late_temporary_name_swap_is_never_reported_as_created_output() {
322추가: for operation in ["extract", "extract-nested", "seven-zip", "recovery"] {
323추가: let s = Scratch::new();
324추가: let (request, output) = prepare(&s, operation);
325추가: let original = fs::read(s.0.join("archive")).ok();
326추가: let events = run(&s, request, "swap-on-link");
327추가: let end = terminal(&events);
328추가: assert_eq!(end.outcome, Outcome::Failed, "{operation}: {events:?}");
329추가: assert_eq!(end.created_count, 0, "{operation}: {events:?}");
330추가: assert_eq!(end.error, ErrorCode::Conflict);
331추가: assert_eq!(end.publication, Publication::Uncertain);
332추가: assert_eq!(end.durability, Durability::Unconfirmed);
333추가: assert_eq!(end.cleanup, Cleanup::Unconfirmed);
334추가: assert_eq!(end.retained_partial_count, 0);
335추가: assert!(!events.iter().any(|e| matches!(
336추가: e,
337추가: Message::Output {
338추가: disposition: Disposition::Created,
339추가: ..
340추가: }
341추가: )));
342추가: assert_eq!(
343추가: events
344추가: .iter()
345추가: .filter(|e| matches!(
346추가: e,
347추가: Message::Output {
348추가: disposition: Disposition::CommitUncertain,
349추가: ..
350추가: }
351추가: ))
352추가: .count(),
353추가: 1
354추가: );
355추가: assert_eq!(fs::read(&output).unwrap(), b"unrelated replacement");
356추가: assert_eq!(fs::read(s.0.join("source")).unwrap(), SOURCE);
357추가: assert_eq!(fs::read(s.0.join("archive")).ok(), original);
358추가: let replacements: Vec<_> = fs::read_dir(output.parent().unwrap())
359추가: .unwrap()
360추가: .map(|e| e.unwrap().path())
361추가: .filter(|p| p.file_name().unwrap().to_string_lossy().ends_with(".tmp"))
362추가: .collect();
363추가: assert_eq!(replacements.len(), 1);
364추가: assert_eq!(
365추가: fs::read(&replacements[0]).unwrap(),
366추가: b"unrelated replacement"
367추가: );
368추가: }
369추가: }
370추가:
371추가: #[test]
372추가: fn moved_temporary_file_is_not_reported_cleaned() {
373추가: for operation in ["extract", "extract-nested", "seven-zip", "recovery"] {
374추가: let s = Scratch::new();
375추가: let (request, output) = prepare(&s, operation);
376추가: let events = run(&s, request, "move-on-sync");
377추가: let end = terminal(&events);
378추가: assert!(!output.exists());
379추가: assert_eq!(end.outcome, Outcome::Failed, "{operation}: {events:?}");
380추가: assert_eq!(end.error, ErrorCode::Conflict);
381추가: assert_eq!(end.publication, Publication::None);
382추가: assert_eq!(end.created_count, 0);
383추가: let owned: Vec<_> = fs::read_dir(output.parent().unwrap())
384추가: .unwrap()
385추가: .map(|e| e.unwrap().path())
386추가: .filter(|p| p.file_name().unwrap().to_string_lossy().ends_with(".owned"))
387추가: .collect();
388추가: assert_eq!(owned.len(), 1);
389추가: assert!(!fs::read(&owned[0]).unwrap().is_empty());
390추가: if operation.starts_with("extract") {
391추가: assert_eq!(fs::read(&owned[0]).unwrap(), SOURCE);
392추가: }
393추가: assert_eq!(end.cleanup, Cleanup::Unconfirmed, "{events:?}");
394추가: assert_eq!(end.retained_partial_count, 0);
395추가: assert_eq!(fs::read(s.0.join("source")).unwrap(), SOURCE);
396추가: }
397추가: }