| 1 | use crate::fixtures::crc32; |
| 2 | use job::{ |
| 3 | Checkpoint, Event, FileJob, Limits, Outcome, Report, Request, Stop, Usage, gzip, publication, |
| 4 | snapshot, |
| 5 | }; |
| 6 | use sha2::{Digest, Sha256}; |
| 7 | use std::{ |
| 8 | ffi::{OsStr, OsString}, |
| 9 | fs::{self, DirBuilder, OpenOptions}, |
| 10 | io::Write, |
| 11 | os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, |
| 12 | path::{Path, PathBuf}, |
| 13 | sync::atomic::{AtomicU64, Ordering}, |
| 14 | }; |
| 15 | |
| 16 | static NEXT: AtomicU64 = AtomicU64::new(1); |
| 17 | |
| 18 | pub struct Sandbox { |
| 19 | pub root: PathBuf, |
| 20 | identity: (u64, u64), |
| 21 | } |
| 22 | |
| 23 | impl Sandbox { |
| 24 | pub fn new() -> Self { |
| 25 | let runs = Path::new(env!("CARGO_MANIFEST_DIR")).join("runs"); |
| 26 | let info = fs::symlink_metadata(&runs).expect("runner가 전용 runs를 준비해야 함"); |
| 27 | assert!(info.is_dir() && !info.file_type().is_symlink()); |
| 28 | assert_eq!(info.mode() & 0o777, 0o700); |
| 29 | assert_eq!(info.uid(), unsafe { libc::geteuid() }); |
| 30 | assert_eq!(runs.canonicalize().unwrap(), runs); |
| 31 | let root = runs.join(format!( |
| 32 | "case-{}-{}", |
| 33 | std::process::id(), |
| 34 | NEXT.fetch_add(1, Ordering::Relaxed) |
| 35 | )); |
| 36 | DirBuilder::new().mode(0o700).create(&root).unwrap(); |
| 37 | let info = fs::symlink_metadata(&root).unwrap(); |
| 38 | let result = Self { |
| 39 | root, |
| 40 | identity: (info.dev(), info.ino()), |
| 41 | }; |
| 42 | result.dir("parent"); |
| 43 | result |
| 44 | } |
| 45 | |
| 46 | pub fn path(&self, name: impl AsRef<Path>) -> PathBuf { |
| 47 | let name = name.as_ref(); |
| 48 | assert!( |
| 49 | name.components() |
| 50 | .all(|part| matches!(part, std::path::Component::Normal(_))) |
| 51 | ); |
| 52 | self.root.join(name) |
| 53 | } |
| 54 | |
| 55 | pub fn parent(&self) -> PathBuf { |
| 56 | self.path("parent") |
| 57 | } |
| 58 | |
| 59 | pub fn dir(&self, name: impl AsRef<Path>) -> PathBuf { |
| 60 | let path = self.path(name); |
| 61 | DirBuilder::new().mode(0o700).create(&path).unwrap(); |
| 62 | path |
| 63 | } |
| 64 | |
| 65 | pub fn file(&self, name: impl AsRef<Path>, bytes: &[u8]) -> PathBuf { |
| 66 | let path = self.path(name); |
| 67 | let mut handle = OpenOptions::new() |
| 68 | .write(true) |
| 69 | .create_new(true) |
| 70 | .mode(0o600) |
| 71 | .open(&path) |
| 72 | .unwrap(); |
| 73 | handle.write_all(bytes).unwrap(); |
| 74 | handle.sync_all().unwrap(); |
| 75 | path |
| 76 | } |
| 77 | |
| 78 | pub fn finish(self) { |
| 79 | assert!( |
| 80 | owned_descriptors(&self.root).is_empty(), |
| 81 | "소유 fd가 남아 있음" |
| 82 | ); |
| 83 | let info = fs::symlink_metadata(&self.root).unwrap(); |
| 84 | assert!(info.is_dir() && !info.file_type().is_symlink()); |
| 85 | assert_eq!((info.dev(), info.ino()), self.identity); |
| 86 | fs::remove_dir_all(&self.root).unwrap(); |
| 87 | assert!(!self.root.exists()); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | pub fn owned_descriptors(root: &Path) -> Vec<u32> { |
| 92 | let mut result = Vec::new(); |
| 93 | for item in fs::read_dir("/proc/self/fd").unwrap() { |
| 94 | let item = item.unwrap(); |
| 95 | if let Ok(target) = fs::read_link(item.path()) { |
| 96 | if target.starts_with(root) { |
| 97 | result.push(item.file_name().to_str().unwrap().parse().unwrap()); |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | result.sort(); |
| 102 | result |
| 103 | } |
| 104 | |
| 105 | pub fn names(parent: &Path) -> Vec<OsString> { |
| 106 | let mut result: Vec<_> = fs::read_dir(parent) |
| 107 | .unwrap() |
| 108 | .map(|e| e.unwrap().file_name()) |
| 109 | .collect(); |
| 110 | result.sort(); |
| 111 | result |
| 112 | } |
| 113 | |
| 114 | pub fn identity(path: &Path) -> (u64, u64, u64, u32, i64, i64, i64, i64) { |
| 115 | let m = fs::symlink_metadata(path).unwrap(); |
| 116 | ( |
| 117 | m.dev(), |
| 118 | m.ino(), |
| 119 | m.len(), |
| 120 | m.mode(), |
| 121 | m.mtime(), |
| 122 | m.mtime_nsec(), |
| 123 | m.ctime(), |
| 124 | m.ctime_nsec(), |
| 125 | ) |
| 126 | } |
| 127 | |
| 128 | pub fn request<'a>(input: &'a Path, parent: &'a Path, limits: Limits) -> Request<'a> { |
| 129 | Request { |
| 130 | input, |
| 131 | output_parent: parent, |
| 132 | output_leaf: OsStr::new("output"), |
| 133 | limits, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | #[derive(Default)] |
| 138 | pub struct Trace { |
| 139 | pub points: Vec<Checkpoint>, |
| 140 | } |
| 141 | |
| 142 | fn counters(usage: Usage) -> [u64; 18] { |
| 143 | let s = usage.snapshot; |
| 144 | let g = usage.gzip; |
| 145 | let p = usage.publication; |
| 146 | [ |
| 147 | s.open_calls, |
| 148 | s.metadata_calls, |
| 149 | s.read_calls, |
| 150 | s.reserved_read_bytes, |
| 151 | s.actual_read_bytes, |
| 152 | s.compared_bytes, |
| 153 | g.processed, |
| 154 | g.output, |
| 155 | g.metadata, |
| 156 | p.open_calls, |
| 157 | p.metadata_calls, |
| 158 | p.sync_calls, |
| 159 | p.link_calls, |
| 160 | p.read_calls, |
| 161 | p.write_calls, |
| 162 | p.reserved_io_bytes, |
| 163 | p.actual_read_bytes, |
| 164 | p.actual_written_bytes, |
| 165 | ] |
| 166 | } |
| 167 | |
| 168 | pub fn phase(event: Event) -> u8 { |
| 169 | match event { |
| 170 | Event::Snapshot(_) => 0, |
| 171 | Event::Decode(_) => 1, |
| 172 | Event::Publication(_) => 2, |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | impl Trace { |
| 177 | pub fn push(&mut self, point: Checkpoint) { |
| 178 | if let Some(before) = self.points.last() { |
| 179 | assert!(phase(before.event) <= phase(point.event)); |
| 180 | for (a, b) in counters(before.usage) |
| 181 | .into_iter() |
| 182 | .zip(counters(point.usage)) |
| 183 | { |
| 184 | assert!(a <= b); |
| 185 | } |
| 186 | } |
| 187 | match point.event { |
| 188 | Event::Snapshot(native) => { |
| 189 | assert_eq!(point.usage.snapshot, native.usage); |
| 190 | assert_eq!(point.usage.gzip, gzip::Usage::default()); |
| 191 | assert_eq!(point.usage.publication, publication::Usage::default()); |
| 192 | } |
| 193 | Event::Decode(native) => { |
| 194 | assert_eq!(point.usage.gzip, native.usage); |
| 195 | assert_eq!(point.usage.publication, publication::Usage::default()); |
| 196 | } |
| 197 | Event::Publication(native) => { |
| 198 | assert_eq!(point.usage.publication, native.usage); |
| 199 | assert_eq!(native.usage.link_calls, 0); |
| 200 | } |
| 201 | } |
| 202 | self.points.push(point); |
| 203 | } |
| 204 | |
| 205 | pub fn finish<E>(&self, report: &Report<E>) { |
| 206 | if let Some(last) = self.points.last() { |
| 207 | for (a, b) in counters(last.usage).into_iter().zip(counters(report.usage)) { |
| 208 | assert!(a <= b); |
| 209 | } |
| 210 | } |
| 211 | match &report.outcome { |
| 212 | Outcome::SnapshotFailed(failure) => { |
| 213 | assert_eq!(report.usage.snapshot, failure.usage); |
| 214 | assert_eq!(report.usage.gzip, gzip::Usage::default()); |
| 215 | assert_eq!(report.usage.publication, publication::Usage::default()); |
| 216 | assert!(report.snapshot.is_none() && report.decoded.is_none()); |
| 217 | assert!(self.points.iter().all(|p| phase(p.event) == 0)); |
| 218 | } |
| 219 | Outcome::DecodeFailed(_) => { |
| 220 | assert!(report.snapshot.is_some() && report.decoded.is_none()); |
| 221 | assert_eq!(report.usage.publication, publication::Usage::default()); |
| 222 | assert!(self.points.iter().all(|p| phase(p.event) <= 1)); |
| 223 | } |
| 224 | Outcome::Publication(native) => { |
| 225 | assert!(report.snapshot.is_some() && report.decoded.is_some()); |
| 226 | assert_eq!(report.usage.publication, native.usage); |
| 227 | } |
| 228 | Outcome::AdapterFailed(_) => panic!("정상 decoder에서 adapter 실패가 발생함"), |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | pub fn run(input: &Path, parent: &Path, limits: Limits) -> (Report<()>, Trace) { |
| 234 | let (task, cancel) = FileJob::new(); |
| 235 | let mut trace = Trace::default(); |
| 236 | let report = task.run(request(input, parent, limits), |point| { |
| 237 | trace.push(point); |
| 238 | Ok::<_, Stop<()>>(()) |
| 239 | }); |
| 240 | trace.finish(&report); |
| 241 | assert_eq!(cancel.request(), publication::CancelDecision::Finished); |
| 242 | (report, trace) |
| 243 | } |
| 244 | |
| 245 | pub fn snapshot_usage(usage: snapshot::Usage, length: usize) { |
| 246 | assert_eq!( |
| 247 | usage, |
| 248 | snapshot::Usage { |
| 249 | open_calls: 4, |
| 250 | metadata_calls: 5, |
| 251 | read_calls: 2 * (length as u64).div_ceil(65_536) + 2, |
| 252 | reserved_read_bytes: 2 * length as u64 + 2, |
| 253 | actual_read_bytes: 2 * length as u64, |
| 254 | compared_bytes: length as u64, |
| 255 | } |
| 256 | ); |
| 257 | } |
| 258 | |
| 259 | pub fn gzip_usage(usage: gzip::Usage, archive: &[u8], output: &[u8], header: usize) { |
| 260 | assert_eq!( |
| 261 | usage, |
| 262 | gzip::Usage { |
| 263 | processed: (archive.len() + output.len()) as u64, |
| 264 | output: output.len() as u64, |
| 265 | metadata: header as u64, |
| 266 | } |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | pub fn cleanup(value: &publication::Cleanup, attempts: u8) { |
| 271 | assert_eq!(value.attempted, attempts); |
| 272 | assert!(value.all_close_calls_succeeded()); |
| 273 | assert!(value.failures.iter().all(Option::is_none)); |
| 274 | } |
| 275 | |
| 276 | pub fn publication_usage(usage: publication::Usage, length: usize, linked: bool) { |
| 277 | let chunks = (length as u64).div_ceil(65_536); |
| 278 | assert_eq!( |
| 279 | usage, |
| 280 | publication::Usage { |
| 281 | open_calls: 4, |
| 282 | metadata_calls: 5, |
| 283 | sync_calls: if linked { 2 } else { 1 }, |
| 284 | link_calls: 1, |
| 285 | read_calls: chunks + 1, |
| 286 | write_calls: chunks, |
| 287 | reserved_io_bytes: 2 * length as u64 + 1, |
| 288 | actual_read_bytes: length as u64, |
| 289 | actual_written_bytes: length as u64, |
| 290 | } |
| 291 | ); |
| 292 | } |
| 293 | |
| 294 | pub fn observations<E>( |
| 295 | report: &Report<E>, |
| 296 | source_id: (u64, u64), |
| 297 | archive: &[u8], |
| 298 | output: &[u8], |
| 299 | header: usize, |
| 300 | ) { |
| 301 | let captured = report.snapshot.as_ref().expect("snapshot 관측값 누락"); |
| 302 | assert_eq!( |
| 303 | (captured.identity().device(), captured.identity().inode()), |
| 304 | source_id |
| 305 | ); |
| 306 | assert_eq!(captured.identity().length(), archive.len() as u64); |
| 307 | assert_eq!(captured.sha256(), <[u8; 32]>::from(Sha256::digest(archive))); |
| 308 | let boundary = report |
| 309 | .decoded |
| 310 | .as_ref() |
| 311 | .expect("decode 관측값 누락") |
| 312 | .boundary(); |
| 313 | assert_eq!(boundary.header_bytes, header); |
| 314 | assert_eq!(boundary.member_bytes, archive.len()); |
| 315 | assert_eq!(boundary.deflate_bytes as usize, archive.len() - header - 8); |
| 316 | assert_eq!(boundary.inflated_bytes, output.len() as u64); |
| 317 | assert_eq!(boundary.crc32, crc32(output)); |
| 318 | snapshot_usage(report.usage.snapshot, archive.len()); |
| 319 | gzip_usage(report.usage.gzip, archive, output, header); |
| 320 | } |
| 321 | |
| 322 | pub fn committed<E>(report: &Report<E>, parent: &Path, output: &[u8]) { |
| 323 | let native = match &report.outcome { |
| 324 | Outcome::Publication(native) => native, |
| 325 | _ => panic!("게시 보고서 누락"), |
| 326 | }; |
| 327 | assert_eq!(native.usage, report.usage.publication); |
| 328 | publication_usage(native.usage, output.len(), true); |
| 329 | cleanup(&native.cleanup, 4); |
| 330 | let (receipt, durability) = match &native.outcome { |
| 331 | publication::Outcome::Committed { |
| 332 | receipt, |
| 333 | durability, |
| 334 | } => (receipt, durability), |
| 335 | _ => panic!("확정된 게시가 아님"), |
| 336 | }; |
| 337 | assert!(matches!( |
| 338 | durability, |
| 339 | publication::Durability::FileAndParentSynced |
| 340 | )); |
| 341 | let m = fs::symlink_metadata(parent.join("output")).unwrap(); |
| 342 | let p = fs::metadata(parent).unwrap(); |
| 343 | assert!(m.is_file() && !m.file_type().is_symlink()); |
| 344 | assert_eq!(m.nlink(), 1); |
| 345 | assert_eq!(m.mode() & 0o777, 0o600); |
| 346 | assert_eq!(receipt.length(), output.len() as u64); |
| 347 | assert_eq!( |
| 348 | ( |
| 349 | receipt.parent_identity().device(), |
| 350 | receipt.parent_identity().inode() |
| 351 | ), |
| 352 | (p.dev(), p.ino()) |
| 353 | ); |
| 354 | assert_eq!( |
| 355 | ( |
| 356 | receipt.file_identity().device(), |
| 357 | receipt.file_identity().inode() |
| 358 | ), |
| 359 | (m.dev(), m.ino()) |
| 360 | ); |
| 361 | assert_eq!(fs::read(parent.join("output")).unwrap(), output); |
| 362 | assert_eq!(names(parent), vec![OsString::from("output")]); |
| 363 | } |
| 364 | |
| 365 | pub fn conflict<E>(report: &Report<E>, length: usize) { |
| 366 | let native = match &report.outcome { |
| 367 | Outcome::Publication(native) => native, |
| 368 | _ => panic!("게시 보고서 누락"), |
| 369 | }; |
| 370 | match &native.outcome { |
| 371 | publication::Outcome::NotCommitted(publication::Error::Io { operation, source }) => { |
| 372 | assert_eq!(*operation, "linkat_conflict"); |
| 373 | assert_eq!(source.raw_os_error(), Some(libc::EEXIST)); |
| 374 | } |
| 375 | _ => panic!("명확한 충돌 오류가 아님"), |
| 376 | } |
| 377 | assert_eq!(report.usage.publication, native.usage); |
| 378 | publication_usage(native.usage, length, false); |
| 379 | cleanup(&native.cleanup, 4); |
| 380 | } |