team-ljyzipelo

공개

분할 원본의 동시 핸들 사용을 제한함

작성자
시로사키 하나
작성 시각
커밋
f93e58cbd9e1aaa4b203b95cf4ad98a216f3b6f6
부모
6bb6f39
이 시점의 파일 보기

변경된 파일 2개

+203-13
수정experiments/rust-archive-worker/src/split_seven_zip.rs+48-13
@@ -605,7 +605,6 @@ pub(crate) fn open(
605605
606606pub(crate) struct Direct {
607607 group: Group,
608삭제: inputs: Vec<Input>,
609608 changes: Vec<Option<(i64, i64)>>,
610609 position: u64,
611610 pub hash: [u8; 32],
@@ -619,17 +618,44 @@ impl Direct {
619618 manifest_sha256: self.group.manifest()?,
620619 })
621620 }
621추가: fn matches(&self, index: usize, input: &Input) -> Result<()> {
622추가: let part = &self.group.parts[index];
623추가: let data = input.file.metadata().map_err(crate::space::io_error)?;
624추가: if !data.is_file()
625추가: || filesystem::object(&input.file)? != part.object
626추가: || data.len() != part.length
627추가: || data.modified().map_err(crate::space::io_error)? != part.modified
628추가: || crate::spool::change_stamp(&data) != self.changes[index]
629추가: {
630추가: return Err(ErrorCode::SourceChanged.into());
631추가: }
632추가: Ok(())
633추가: }
634추가: fn open_checked(
635추가: &self,
636추가: index: usize,
637추가: step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
638추가: ) -> Result<Input> {
639추가: let input = self
640추가: .group
641추가: .open_part(&self.group.parts[index].name, step)
642추가: .map_err(|failure| {
643추가: if failure.error == ErrorCode::UnsafePath {
644추가: ErrorCode::SourceChanged.into()
645추가: } else {
646추가: failure
647추가: }
648추가: })?;
649추가: self.matches(index, &input)?;
650추가: Ok(input)
651추가: }
622652 fn unchanged(
623653 &self,
624654 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
625655 ) -> Result<()> {
626삭제: for ((part, input), changed) in self.group.parts.iter().zip(&self.inputs).zip(&self.changes)
627삭제: {
628삭제: self.group.matches(part, input)?;
629삭제: if crate::spool::change_stamp(&metadata(&input.file)?) != *changed {
630삭제: return Err(ErrorCode::SourceChanged.into());
631삭제: }
656추가: for index in 0..self.group.parts.len() {
632657 step(Step::Check)?;
658추가: self.open_checked(index, step)?;
633659 }
634660 Ok(())
635661 }
@@ -645,15 +671,27 @@ impl Direct {
645671impl Read for Direct {
646672 fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
647673 let mut start = 0;
648삭제: for (part, input) in self.group.parts.iter().zip(&mut self.inputs) {
674추가: if output.is_empty() {
675추가: return Ok(0);
676추가: }
677추가: let source_error = |failure: Failure| {
678추가: std::io::Error::other(format!("분할 원본 읽기 실패: {:?}", failure.error))
679추가: };
680추가: for (index, part) in self.group.parts.iter().enumerate() {
649681 let end = start + part.length;
650682 if self.position < end {
651683 let count = (end - self.position).min(output.len() as u64) as usize;
684추가: // 필요한 조각만 열어 핸들 사용량이 조각 수에 비례하지 않게 함.
685추가: let mut input = self
686추가: .open_checked(index, &mut |_| Ok(()))
687추가: .map_err(source_error)?;
652688 input
653689 .file
654690 .seek(std::io::SeekFrom::Start(self.position - start))?;
655삭제: let count = input.file.read(&mut output[..count])?;
656삭제: if count == 0 && !output.is_empty() {
691추가: let read = input.file.read(&mut output[..count]);
692추가: self.matches(index, &input).map_err(source_error)?;
693추가: let count = read?;
694추가: if count == 0 {
657695 return Err(std::io::Error::new(
658696 std::io::ErrorKind::UnexpectedEof,
659697 "분할 원본이 변경됨",
@@ -689,13 +727,11 @@ pub(crate) fn open_direct(
689727 let Some(mut group) = discover(path, None, limit, metadata_limits, step)? else {
690728 return Ok(None);
691729 };
692삭제: let mut inputs = Vec::new();
693730 let mut changes = Vec::new();
694731 for part in &group.parts {
695732 let input = group.open_part(&part.name, step)?;
696733 group.matches(part, &input)?;
697734 changes.push(crate::spool::change_stamp(&metadata(&input.file)?));
698삭제: inputs.push(input);
699735 }
700736 let mut whole = Sha256::new();
701737 let mut processed = 0;
@@ -716,7 +752,6 @@ pub(crate) fn open_direct(
716752 })?;
717753 let mut direct = Direct {
718754 group,
719삭제: inputs,
720755 changes,
721756 position: 0,
722757 hash: whole.finalize().into(),
수정tests/rust-archive-worker/split_capture.rs+155-0
@@ -582,3 +582,158 @@ fn direct_reader_detects_transient_change_during_final_verification() {
582582 assert!(changed);
583583 assert_eq!(code(result), ErrorCode::SourceChanged);
584584}
585추가:
586추가: #[cfg(target_os = "linux")]
587추가: #[test]
588추가: fn direct_reader_low_fd_child() {
589추가: if std::env::var_os("ZIPELO_SPLIT_LOW_FD_CHILD").is_none() {
590추가: return;
591추가: }
592추가: use std::io::SeekFrom;
593추가: let s = Scratch::new();
594추가: let original = s.split(11);
595추가: let mut copied = s.capture();
596추가: let expected = token(&copied);
597추가: let catalog = crate::seven_zip::open(
598추가: &mut copied.snapshot.file,
599추가: expected.archive_bytes,
600추가: Limits::default(),
601추가: false,
602추가: &mut || Ok(()),
603추가: )
604추가: .unwrap();
605추가: let entries = catalog
606추가: .members
607추가: .iter()
608추가: .map(|m| m.entry.clone())
609추가: .collect::<Vec<_>>();
610추가: drop((catalog, copied));
611추가: let mut direct = open_direct(&s.first(), u64::MAX, Default::default(), &mut |_| Ok(()))
612추가: .unwrap()
613추가: .unwrap();
614추가: assert_eq!(direct.hash, expected.archive_sha256);
615추가: assert_eq!(direct.object().unwrap(), expected.source_object);
616추가: assert_eq!(direct.len(), expected.archive_bytes);
617추가: let mut bytes = Vec::new();
618추가: direct.read_to_end(&mut bytes).unwrap();
619추가: assert_eq!(bytes, original);
620추가: direct.seek(SeekFrom::End(-12)).unwrap();
621추가: let mut last = [0; 12];
622추가: direct.read_exact(&mut last).unwrap();
623추가: assert_eq!(last, original[original.len() - 12..]);
624추가: let catalog = crate::seven_zip::open(
625추가: &mut direct,
626추가: expected.archive_bytes,
627추가: Limits::default(),
628추가: false,
629추가: &mut || Ok(()),
630추가: )
631추가: .unwrap();
632추가: assert_eq!(
633추가: catalog
634추가: .members
635추가: .iter()
636추가: .map(|m| m.entry.clone())
637추가: .collect::<Vec<_>>(),
638추가: entries
639추가: );
640추가: drop(catalog);
641추가: direct.verify(&mut |_| Ok(())).unwrap();
642추가: assert_eq!(std::fs::read_dir(&s.0).unwrap().count(), 11);
643추가: }
644추가:
645추가: #[cfg(target_os = "linux")]
646추가: #[test]
647추가: fn direct_reader_with_sixteen_file_descriptors_lists_eleven_volumes() {
648추가: use std::os::unix::process::CommandExt;
649추가: #[repr(C)]
650추가: struct Limit {
651추가: soft: u64,
652추가: hard: u64,
653추가: }
654추가: unsafe extern "C" {
655추가: fn setrlimit(resource: i32, limit: *const Limit) -> i32;
656추가: }
657추가: let s = Scratch::new();
658추가: let mut command = std::process::Command::new(std::env::current_exe().unwrap());
659추가: command
660추가: .args([
661추가: "--exact",
662추가: "split_seven_zip::tests::direct_reader_low_fd_child",
663추가: "--test-threads=1",
664추가: ])
665추가: .env("TMPDIR", &s.0)
666추가: .env("ZIPELO_SPLIT_LOW_FD_CHILD", "1");
667추가: // 자식 프로세스의 파일 핸들 상한만 16으로 제한함.
668추가: unsafe {
669추가: command.pre_exec(|| {
670추가: if setrlimit(7, &Limit { soft: 16, hard: 16 }) == 0 {
671추가: Ok(())
672추가: } else {
673추가: Err(std::io::Error::last_os_error())
674추가: }
675추가: });
676추가: }
677추가: let result = command.output().unwrap();
678추가: assert!(
679추가: result.status.success(),
680추가: "stdout={} stderr={}",
681추가: String::from_utf8_lossy(&result.stdout),
682추가: String::from_utf8_lossy(&result.stderr)
683추가: );
684추가: assert_eq!(std::fs::read_dir(&s.0).unwrap().count(), 0);
685추가: }
686추가:
687추가: #[test]
688추가: fn direct_reader_reopens_volumes_and_rejects_same_content_replacement_before_read() {
689추가: use std::io::SeekFrom;
690추가: let s = Scratch::new();
691추가: let original = s.split(11);
692추가: let mut direct = open_direct(&s.first(), u64::MAX, Default::default(), &mut |_| Ok(()))
693추가: .unwrap()
694추가: .unwrap();
695추가: let path = s.0.join("sample.7z.006");
696추가: let bytes = std::fs::read(&path).unwrap();
697추가: let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
698추가: std::fs::rename(&path, s.0.join("previous")).unwrap();
699추가: std::fs::write(&path, bytes).unwrap();
700추가: std::fs::OpenOptions::new()
701추가: .write(true)
702추가: .open(&path)
703추가: .unwrap()
704추가: .set_times(std::fs::FileTimes::new().set_modified(modified))
705추가: .unwrap();
706추가: direct
707추가: .seek(SeekFrom::Start((5 * original.len() / 11) as u64))
708추가: .unwrap();
709추가: assert!(direct.read(&mut [0; 1]).is_err());
710추가: assert_eq!(
711추가: code(direct.verify(&mut |_| Ok(()))),
712추가: ErrorCode::SourceChanged
713추가: );
714추가: }
715추가:
716추가: #[test]
717추가: fn direct_reader_classifies_non_file_replacement_as_source_changed() {
718추가: let s = Scratch::new();
719추가: s.split(11);
720추가: let direct = open_direct(&s.first(), u64::MAX, Default::default(), &mut |_| Ok(()))
721추가: .unwrap()
722추가: .unwrap();
723추가: let path = s.0.join("sample.7z.006");
724추가: std::fs::rename(&path, s.0.join("previous")).unwrap();
725추가: std::fs::create_dir(&path).unwrap();
726추가: assert_eq!(
727추가: code(direct.verify(&mut |_| Ok(()))),
728추가: ErrorCode::SourceChanged
729추가: );
730추가: #[cfg(unix)]
731추가: {
732추가: std::fs::remove_dir(&path).unwrap();
733추가: std::os::unix::fs::symlink(s.0.join("previous"), &path).unwrap();
734추가: assert_eq!(
735추가: code(direct.verify(&mut |_| Ok(()))),
736추가: ErrorCode::SourceChanged
737추가: );
738추가: }
739추가: }