team-ljyzipelo

공개

승인된 작업의 앱 전체 시간 제한을 해제한다

작성자
호시노 히나타
작성 시각
커밋
dcae9b1c37455d5daeb7945ed321b6c6050fb610
부모
f2d6db3
이 시점의 파일 보기

변경된 파일 4개

+203-2
수정experiments/rust-ui-memory-app/src/archive_process.rs+42-1
@@ -337,6 +337,12 @@ fn fault(events: &SyncSender<ui::HostEvent>, stop: &AtomicBool, message: &str) {
337337 notify(events, ui::HostEvent::Fault(message.into()));
338338}
339339
340추가: #[derive(Default)]
341추가: struct ResourceDeadline {
342추가: pending: Option<(u64, wire::ResourceScope)>,
343추가: approved: bool,
344추가: }
345추가:
340346pub struct ProcessFactory {
341347 worker: PathBuf,
342348}
@@ -366,10 +372,12 @@ impl ui::Factory for ProcessFactory {
366372 let stop = Arc::new(AtomicBool::new(false));
367373 let done = Arc::new(AtomicBool::new(false));
368374 let expected = Arc::new(Mutex::new(None));
375추가: let resources = Arc::new(Mutex::new(ResourceDeadline::default()));
369376 let worker = self.worker.clone();
370377 let worker_stop = stop.clone();
371378 let worker_done = done.clone();
372379 let worker_expected = expected.clone();
380추가: let worker_resources = resources.clone();
373381 let supervisor = thread::Builder::new()
374382 .name("zipelo-worker-owner".into())
375383 .spawn(move || {
@@ -407,6 +415,7 @@ impl ui::Factory for ProcessFactory {
407415 worker_stop,
408416 worker_done,
409417 worker_expected,
418추가: worker_resources,
410419 );
411420 })
412421 .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?;
@@ -423,6 +432,7 @@ impl ui::Factory for ProcessFactory {
423432 stop,
424433 supervisor: Some(supervisor),
425434 expected,
435추가: resources,
426436 done,
427437 disconnected: false,
428438 reaped: false,
@@ -451,6 +461,7 @@ struct ProcessConnection {
451461 stop: Arc<AtomicBool>,
452462 supervisor: Option<JoinHandle<()>>,
453463 expected: Arc<Mutex<Option<wire::ActionKind>>>,
464추가: resources: Arc<Mutex<ResourceDeadline>>,
454465 done: Arc<AtomicBool>,
455466 disconnected: bool,
456467 reaped: bool,
@@ -513,6 +524,10 @@ impl ui::Connection for ProcessConnection {
513524 self.stop.store(true, Ordering::Release);
514525 return Err("작업자 요청을 직렬화하지 못했습니다".into());
515526 }
527추가: let mut resources = self.resources.lock().map_err(|_| {
528추가: self.stop.store(true, Ordering::Release);
529추가: "작업자 승인 상태 오류"
530추가: })?;
516531 let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel);
517532 if self.send.as_ref().unwrap().try_send(bytes).is_err() {
518533 if is_cancel && self.done.load(Ordering::Acquire) {
@@ -522,6 +537,16 @@ impl ui::Connection for ProcessConnection {
522537 self.stop.store(true, Ordering::Release);
523538 return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into());
524539 }
540추가: if let wire::Message::ResourceReply {
541추가: challenge_id,
542추가: scope,
543추가: allow,
544추가: } = message
545추가: && resources.pending == Some((challenge_id, scope))
546추가: {
547추가: resources.approved |= allow;
548추가: resources.pending = None;
549추가: }
525550 self.next += 1;
526551 Ok(())
527552 }
@@ -563,6 +588,7 @@ fn supervise(
563588 stop: Arc<AtomicBool>,
564589 done: Arc<AtomicBool>,
565590 expected: Arc<Mutex<Option<wire::ActionKind>>>,
591추가: resources: Arc<Mutex<ResourceDeadline>>,
566592) {
567593 let mut input = child.stdin.take().unwrap();
568594 let mut output = child.stdout.take().unwrap();
@@ -604,6 +630,7 @@ fn supervise(
604630 let tx = events.clone();
605631 let abort = stop.clone();
606632 let received_terminal = terminal_received.clone();
633추가: let pending_resource = resources.clone();
607634 threads.push(
608635 thread::Builder::new()
609636 .name("zipelo-worker-output".into())
@@ -620,6 +647,14 @@ fn supervise(
620647 fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다");
621648 break false;
622649 }
650추가: if let Ok(ui::Event::ResourceRequired(question)) = &event {
651추가: if let Ok(mut state) = pending_resource.lock() {
652추가: state.pending = Some((question.id, question.scope));
653추가: } else {
654추가: fault(&tx, &abort, "작업자 승인 상태 오류");
655추가: break false;
656추가: }
657추가: }
623658 if matches!(event, Ok(ui::Event::Terminal(_))) {
624659 received_terminal.store(true, Ordering::Release);
625660 }
@@ -679,7 +714,13 @@ fn supervise(
679714 }
680715 let started = Instant::now();
681716 let status = loop {
682삭제: if started.elapsed() >= Duration::from_secs(310) {
717추가: // 승인 뒤 실제 진행과 질문 대기 시간은 작업자의 60초 정체 감시로 판단함.
718추가: // 응답 프레임 간격을 실제 파일 처리 진행으로 간주하지 않음.
719추가: let approved = resources
720추가: .lock()
721추가: .map(|state| state.approved)
722추가: .unwrap_or(false);
723추가: if !approved && started.elapsed() >= Duration::from_secs(310) {
683724 fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다");
684725 }
685726 if stop.load(Ordering::Acquire) {
수정tests/rust-app-real-worker/README.md+3-1
@@ -10,7 +10,7 @@ PATH나 현재 작업 폴더에서 임의 작업자를 검색하지 않음. ui-f
1010정상 종료에는 Terminal, 양쪽 EOF와 child wait를 모두 확인함. 통신 오류는 성공으로
1111표시하지 않으며, 오류 경로에서는 child 회수와 모든 파이프 스레드/핸들 정리가 끝났다는
1212명시적 완료 신호까지 확인함. 연결이 예외적으로 폐기돼도 소유한 자식을 종료하고 회수함.
13삭제: 310초 제한 시간을 넘긴 작업자도 종료와 회수를 시도하며 완료 여부가 불명확하면 닫기를 허용하지 않음.
13추가: 확대 승인 전에는 기존 310초 제한과 강제 종료 및 회수를 유지함. 유효한 자원 질문과 일치하는 허용 응답이 요청 큐에 들어간 뒤에는 앱의 전체 시간 제한을 해제함. 승인 뒤 실제 진행 없는 60초와 질문별 응답 대기 300초는 작업자의 Watchdog에서 판단하며, 앱은 응답 프레임을 실제 진행으로 추정하지 않음. 암호/충돌/자원 질문에 답하는 시간은 정체 시간에 포함하지 않음. 완료 여부가 불명확하면 닫기를 허용하지 않음.
1414
1515## 실행
1616
@@ -67,3 +67,5 @@ formats.rs는 전체 ListEnd 프레임을 고정 바이트와 비교하고 Unix/
6767목록 응답과 해제 요청 사이에서 보존되는지 확인함. 화면 흐름 시험은 PR69의 LZMA와
6868LZMA2 표본을 실제 작업자로 열고, 받은 ListId로 풀어 원본 바이트를 확인함.
6969구버전 앱은 새 형식 값을 해석할 수 없으므로 앱과 작업자를 함께 갱신해야 함.
70추가:
71추가: 가상 시계 회귀 approved_password_wait_is_not_killed_by_app_deadline은 정상 시계 대조군, 승인 뒤 관리 스레드의 311초 경과와 암호 대기, 승인하지 않은 작업의 기존 강제 종료를 실제 작업자 파이프로 검증함. 시계는 별도 시험 프로세스의 관리 스레드에만 적용하며 실제 310초를 기다리지 않음.
수정tests/rust-app-real-worker/guarded_flows.rs+140-0
@@ -166,3 +166,143 @@ fn approved_extraction_reports_implicit_parents_separately_from_entries() {
166166 );
167167 }
168168}
169추가:
170추가: #[cfg(target_os = "linux")]
171추가: #[test]
172추가: fn approved_password_wait_is_not_killed_by_app_deadline() {
173추가: const MODE: &str = "ZIPELO_SUPERVISOR_CLOCK_CASE";
174추가: if let Ok(mode) = std::env::var(MODE) {
175추가: let approved = mode != "unapproved";
176추가: let scratch = Scratch::new();
177추가: let output = scratch.path("output.zip");
178추가: let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
179추가: let mut connection = factory.connect(1).unwrap();
180추가: let start = Start::CreateZip {
181추가: sources: vec![(scratch.path("source.txt"), "source.txt".into())],
182추가: output_file: output.clone(),
183추가: method: Method::Store,
184추가: aes256: true,
185추가: };
186추가: fs::write(scratch.path("source.txt"), b"source").unwrap();
187추가: connection
188추가: .send(Request {
189추가: job_id: 1,
190추가: sequence: 0,
191추가: command: if approved {
192추가: Command::StartExpanded(start)
193추가: } else {
194추가: Command::Start(start)
195추가: },
196추가: })
197추가: .unwrap();
198추가: let started = Instant::now();
199추가: let mut sequence = 1;
200추가: let mut granted = false;
201추가: let mut password = false;
202추가: let mut cancelled = false;
203추가: let mut terminal = None;
204추가: let mut fault = None;
205추가: loop {
206추가: if let Some(event) = connection.poll() {
207추가: match event {
208추가: HostEvent::Frame {
209추가: event: Event::ResourceRequired(q),
210추가: ..
211추가: } => {
212추가: assert!(approved);
213추가: connection
214추가: .send(Request {
215추가: job_id: 1,
216추가: sequence,
217추가: command: Command::ResourceReply {
218추가: challenge_id: q.id,
219추가: scope: q.scope,
220추가: allow: true,
221추가: },
222추가: })
223추가: .unwrap();
224추가: sequence += 1;
225추가: granted = true;
226추가: }
227추가: HostEvent::Frame {
228추가: event: Event::PasswordRequired { .. },
229추가: ..
230추가: } => password = true,
231추가: HostEvent::Frame {
232추가: event: Event::Terminal(value),
233추가: ..
234추가: } => terminal = Some(value),
235추가: HostEvent::Fault(message) => fault = Some(message),
236추가: HostEvent::Exited { success } => {
237추가: assert!(password);
238추가: assert_eq!(granted, approved);
239추가: assert!(!output.exists());
240추가: if approved {
241추가: assert!(success);
242추가: assert!(
243추가: fault.is_none(),
244추가: "승인 뒤 암호 대기를 강제 종료함: {fault:?}"
245추가: );
246추가: assert_eq!(terminal.unwrap().outcome, Outcome::Cancelled);
247추가: } else {
248추가: assert!(!success);
249추가: assert!(fault.unwrap().contains("제한 시간"));
250추가: }
251추가: return;
252추가: }
253추가: _ => {}
254추가: }
255추가: }
256추가: if approved && started.elapsed() > Duration::from_secs(4) && !cancelled {
257추가: connection
258추가: .send(Request {
259추가: job_id: 1,
260추가: sequence,
261추가: command: Command::Cancel,
262추가: })
263추가: .unwrap();
264추가: cancelled = true;
265추가: }
266추가: assert!(started.elapsed() < Duration::from_secs(8));
267추가: std::thread::sleep(Duration::from_millis(1));
268추가: }
269추가: }
270추가: let scratch = Scratch::new();
271추가: let clock = scratch.path("supervisor-clock.so");
272추가: assert!(
273추가: std::process::Command::new("cc")
274추가: .args(["-shared", "-fPIC", "-pthread"])
275추가: .arg(
276추가: Path::new(env!("CARGO_MANIFEST_DIR"))
277추가: .join("../../tests/rust-app-real-worker/supervisor_clock.c")
278추가: )
279추가: .args(["-o"])
280추가: .arg(&clock)
281추가: .arg("-ldl")
282추가: .status()
283추가: .unwrap()
284추가: .success()
285추가: );
286추가: for mode in ["control", "approved", "unapproved"] {
287추가: let mut command = std::process::Command::new(std::env::current_exe().unwrap());
288추가: command
289추가: .args([
290추가: "--exact",
291추가: "guarded_flows::approved_password_wait_is_not_killed_by_app_deadline",
292추가: "--nocapture",
293추가: ])
294추가: .env(MODE, mode);
295추가: if mode == "control" {
296추가: command.env_remove("LD_PRELOAD");
297추가: } else {
298추가: command.env("LD_PRELOAD", &clock);
299추가: }
300추가: let output = command.output().unwrap();
301추가: assert!(
302추가: output.status.success(),
303추가: "{mode}: {}\n{}",
304추가: String::from_utf8_lossy(&output.stdout),
305추가: String::from_utf8_lossy(&output.stderr)
306추가: );
307추가: }
308추가: }
추가tests/rust-app-real-worker/supervisor_clock.c+18-0
@@ -0,0 +1,18 @@
1추가: #define _GNU_SOURCE
2추가: #include <dlfcn.h>
3추가: #include <pthread.h>
4추가: #include <string.h>
5추가: #include <time.h>
6추가:
7추가: int clock_gettime(clockid_t id, struct timespec *value) {
8추가: int (*original)(clockid_t, struct timespec *) = dlsym(RTLD_NEXT, "clock_gettime");
9추가: int result = original(id, value);
10추가: char name[16] = {0};
11추가: pthread_getname_np(pthread_self(), name, sizeof(name));
12추가: if (result == 0 && id == CLOCK_MONOTONIC && !strcmp(name, "zipelo-worker-o")) {
13추가: static _Thread_local time_t start;
14추가: if (!start) start = value->tv_sec;
15추가: if (value->tv_sec - start >= 2) value->tv_sec += 311;
16추가: }
17추가: return result;
18추가: }