Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions deploy/systemd/poppy-agent.service.d/10-event-no-restart.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# 행사 운영용 drop-in (#100). /etc/systemd/system/poppy-agent.service.d/ 에 설치되어 재부팅 뒤에도 유지된다.
# 비정상 종료 뒤 자동 재시작으로 실제 동작이 다시 켜지지 않게 한다. 재시작은 운영자가
# scripts/event_start.py 로 상태를 확인하며 한다.
[Service]
Restart=no
42 changes: 42 additions & 0 deletions docs/event-start.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# 원클릭 행사 시작 (`scripts/event_start.py`, #100)

운영 노트북에서 운영자가 TTY 로 실행한다. AI 에이전트는 dry-run 과 fake 테스트만 수행한다.

## 순서

1. `systemctl show poppy-agent` 로 상태 확인 → `failed` 면 `reset-failed` + `start`, `inactive` 면 `start`,
`active` 면 그대로. 그 밖의 상태는 FAIL(수동 확인).
2. `deploy/systemd/poppy-agent.service.d/10-event-no-restart.conf`(`Restart=no`)가
`/etc/systemd/system/poppy-agent.service.d/` 에 없거나 다르면 설치 후 `daemon-reload`. 디스크의 drop-in
이라 재부팅 뒤에도 유지된다. 비정상 종료 뒤 자동 재시작으로 실제 동작이 다시 켜지지 않게 한다.
3. 로봇 늦은 기동 대기: `/run/poppy-agent/status.json` 의 `lifecycleState=READY` 와 `telemetry.fresh=true`
를 `--poll-seconds`(기본 5 s) 간격으로 `--wait-seconds`(기본 180 s)까지 재시도.
4. 승인 만료 검사: `TRIAL_EXPIRED`, `EXPIRES_AT` 설정 오류, 남은 시간 30분 이하면 FAIL. 만료 시각을
바꾸거나 우회하지 않는다(교사 승인 갱신 후 켜기 스크립트가 새 만료 시각을 쓴다).
5. 오래된 대기 실행 정리 확인: Server 쪽 정리(Poppy-Server#132) 후 운영자가 `--queue-cleared` 를 줘야
다음 단계로 간다.
6. 켜기: `--switch-command '<켜기 스크립트> on'` 을 실행하고 `physicalExecution.state=READY` 까지 대기.
지정하지 않으면 `MANUAL` 로 끝난다.

마지막 줄은 한 줄 결과다: `OK: ...`, `DRY-RUN OK: ...`, `MANUAL: ...`, `FAIL: <원인과 조치>`.
FAIL 이면 exit code 1.

## 사용

```bash
# 기본은 dry-run: 아무 명령도 실행하지 않고 출력만 한다
python3 scripts/event_start.py --queue-cleared --switch-command '<켜기 스크립트> on'

# 실제 실행(운영자)
python3 scripts/event_start.py --execute --queue-cleared --switch-command '<켜기 스크립트> on'
```

dry-run 은 `--simulate-state failed|inactive|active`, `--simulate-drop-in` 으로 가정 상태를 바꿀 수 있고,
`--status-path` 로 fixture 스냅샷을 줄 수 있다.

## 한계

- EnvironmentFile 은 읽지 않는다. physical off 상태에서는 만료 시각이 스냅샷에 없으므로 승인 검사는
켜기 스크립트와 켜기 후 READY 확인에 맡긴다.
- 대기 실행 정리는 Server API 계약이 정해지지 않아(Poppy-Server#132) 운영자 확인 플래그로 대신한다.
- `Restart=no` 이므로 Agent 가 죽으면 이 스크립트를 다시 실행해 상태를 확인하며 시작한다.
307 changes: 307 additions & 0 deletions scripts/event_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
"""One-command event start for the operator laptop (#100).

Order: service state -> reset-failed/start (physical execution stays as configured)
-> persistent ``Restart=no`` drop-in -> wait for a late Robot (fresh telemetry)
-> approval expiry check -> stale pending Execution check -> switch on -> READY.
The last line printed is a one-line summary for the operator.

Safety:
- The default is a dry run: every command is printed and nothing is executed.
``--execute`` is required to touch systemd or run the switch command.
- The approval expiry is only checked, never extended or bypassed. An expired or
soon-expiring approval stops the script before the switch.
- Physical execution is switched on only after the operator confirms the stale
pending Executions are cleared (``--queue-cleared``; Poppy-Server#132).
- This script sends no Robot command and does not read the EnvironmentFile; it
reads only the secret-free status snapshot (``POPPY_RUNTIME_STATUS_PATH``).
"""

from __future__ import annotations

import argparse
import json
import shlex
import subprocess
import sys
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from pathlib import Path

UNIT = "poppy-agent"
STATUS_PATH = Path("/run/poppy-agent/status.json")
DROP_IN_NAME = "10-event-no-restart.conf"
DROP_IN_SOURCE = (
Path(__file__).resolve().parents[1] / "deploy" / "systemd" / "poppy-agent.service.d"
)
DROP_IN_DIR = Path("/etc/systemd/system/poppy-agent.service.d")
MIN_APPROVAL_REMAINING = timedelta(minutes=30)


class StepFailed(RuntimeError):
"""A step that must stop the start sequence; the message is the summary."""


@dataclass(frozen=True, slots=True)
class CommandResult:
returncode: int
stdout: str = ""


Runner = Callable[[Sequence[str]], CommandResult]


@dataclass
class Report:
steps: list[tuple[str, str]] = field(default_factory=list)

def add(self, step: str, outcome: str) -> None:
self.steps.append((step, outcome))
print(f"[{step}] {outcome}", flush=True)


def subprocess_runner(command: Sequence[str]) -> CommandResult:
completed = subprocess.run( # noqa: S603 - fixed argument lists only
list(command), capture_output=True, text=True, check=False, timeout=60

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 필수 수정 · HIGH

켜기 명령 타임아웃의 불명확한 결과를 처리해야 합니다

모든 실제 명령에 60초 타임아웃을 적용하지만 TimeoutExpired를 처리하지 않습니다. 켜기 명령은 외부 상태 변경을 이미 완료했을 수도 있으므로 타임아웃은 단순 실패가 아니라 결과 불명 상태입니다.

이유: 부작용이 있는 명령의 타임아웃 후 무심코 재실행하는 것은 단일 실행 안전 절차를 훼손할 수 있습니다.

제안: 타임아웃 전용 실패 경로와 테스트를 추가하고, 수동 상태 확인 전에는 재시도하지 않도록 결과 문구를 명확히 하십시오.

)
return CommandResult(completed.returncode, completed.stdout)


class DryRunRunner:
"""Print commands instead of running them; answers come from a simulated state."""

def __init__(self, simulated_active_state: str, drop_in_present: bool) -> None:
self.active_state = simulated_active_state
self.drop_in_present = drop_in_present
self.commands: list[list[str]] = []

def __call__(self, command: Sequence[str]) -> CommandResult:
self.commands.append(list(command))
print(f" (dry-run) {shlex.join(command)}", flush=True)
if list(command[:2]) == ["systemctl", "show"]:
return CommandResult(0, f"ActiveState={self.active_state}\n")
if list(command[:1]) == ["cmp"]:
return CommandResult(0 if self.drop_in_present else 1)
if list(command[:3]) in (
["sudo", "systemctl", "start"],
["sudo", "systemctl", "restart"],
):
self.active_state = "active"
return CommandResult(0)


def parse_properties(text: str) -> dict[str, str]:
properties: dict[str, str] = {}
for line in text.splitlines():
key, sep, value = line.partition("=")
if sep:
properties[key.strip()] = value.strip()
return properties


def read_status(path: Path) -> dict[str, object] | None:
try:
loaded = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return loaded if isinstance(loaded, dict) else None


def _physical(status: dict[str, object]) -> dict[str, object]:
physical = status.get("physicalExecution")
return physical if isinstance(physical, dict) else {}


def telemetry_fresh(status: dict[str, object]) -> bool:
telemetry = status.get("telemetry")
return isinstance(telemetry, dict) and telemetry.get("fresh") is True


def approval_expires_at(status: dict[str, object]) -> datetime | None:
trial = _physical(status).get("trial")
if not isinstance(trial, dict):
return None
raw = trial.get("expiresAt")
if not isinstance(raw, str):
return None
try:
parsed = datetime.fromisoformat(raw)
except ValueError:
return None
return parsed if parsed.tzinfo is not None else None


def check_approval(status: dict[str, object], now: datetime, minimum: timedelta) -> str:
"""Return a description of the approval window or raise ``StepFailed``."""
physical = _physical(status)
reasons = physical.get("reasons")
issues = physical.get("configIssues")
if isinstance(reasons, list) and "TRIAL_EXPIRED" in reasons:
raise StepFailed(
"승인 만료(TRIAL_EXPIRED): 교사 승인 갱신 후 켜기 스크립트로 새 만료 시각 설정"
)
if isinstance(issues, list) and any("EXPIRES_AT" in str(issue) for issue in issues):
raise StepFailed(
"승인 만료 시각 설정 오류: 교사 승인 갱신 후 켜기 스크립트로 새 만료 시각 설정"
)
expires = approval_expires_at(status)
if expires is None:
# Physical execution is still off, so the window is checked by the switch.
return "만료 시각 미표시(physical off) — 켜기 단계에서 확인"
remaining = expires - now
if remaining <= minimum:
minutes = max(0, int(remaining.total_seconds() // 60))
raise StepFailed(f"승인 만료 임박(남은 {minutes}분): 교사 승인 갱신 필요")
return f"승인 유효(남은 {int(remaining.total_seconds() // 60)}분)"


@dataclass
class EventStart:
runner: Runner
status_path: Path
execute: bool
queue_cleared: bool
switch_command: list[str] | None
wait_seconds: float
poll_seconds: float
now: Callable[[], datetime] = lambda: datetime.now(UTC)
sleep: Callable[[float], None] = time.sleep
monotonic: Callable[[], float] = time.monotonic
status_reader: Callable[[Path], dict[str, object] | None] = read_status
report: Report = field(default_factory=Report)

def run(self) -> str:
try:
self._service()
self._drop_in()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 필수 수정 · HIGH

서비스 시작 전에 Restart=no를 적용해야 합니다

현재는 실패하거나 중지된 서비스를 먼저 시작한 뒤 drop-in을 설치합니다. 기존 unit에 자동 재시작 정책이 설정되어 있으면, 새 프로세스가 초기화 중 종료되는 순간 Restart=no가 아직 적용되지 않아 의도와 달리 자동 재시작될 수 있습니다.

이유: 물리 동작을 자동으로 다시 켜지 않겠다는 이 변경의 핵심 안전 목적을 위반할 수 있습니다.

제안: _drop_in()을 _service()보다 먼저 실행하고 이 순서를 검증하는 테스트를 추가하십시오.

Suggested change
self._drop_in()
self._drop_in()
self._service()

status = self._wait_for(
"로봇 텔레메트리",
lambda s: s.get("lifecycleState") == "READY" and telemetry_fresh(s),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 필수 수정 · HIGH

이전 실행의 상태 파일을 현재 READY로 오인할 수 있습니다

준비 판단이 파일 안의 lifecycleState와 telemetry.fresh 불리언만 확인합니다. 이전 Agent가 READY 상태를 기록한 뒤 종료했다면 파일이 남아 있는 동안 새 서비스가 아직 준비되지 않았어도 즉시 통과할 수 있습니다.

이유: 파일에 기록된 과거 안전 상태는 현재 로봇이 준비되었다는 증거가 될 수 없습니다.

제안: 스냅샷 세대 또는 타임스탬프 검증을 추가하고, 잔존 상태 파일을 사용하는 회귀 테스트를 추가하십시오.

"로봇 미기동 또는 텔레메트리 없음: 로봇 전원·유선 연결 확인 후 다시 실행",
)
self.report.add("승인", check_approval(status, self.now(), MIN_APPROVAL_REMAINING))
self._queue()
self._switch_on()
except StepFailed as exc:
return f"FAIL: {exc}"
if self.switch_command is None:
return "MANUAL: 서비스·로봇 준비 완료, 켜기 명령을 직접 실행 (--switch-command 미지정)"
if not self.execute:
return "DRY-RUN OK: 실제 실행은 --execute"
return "OK: 실제 동작 READY"

def _service(self) -> None:
shown = self.runner(["systemctl", "show", UNIT, "-p", "ActiveState,Result,NRestarts"])
state = parse_properties(shown.stdout).get("ActiveState", "unknown")
if state == "failed":
self._mutate(["sudo", "systemctl", "reset-failed", UNIT])
self._mutate(["sudo", "systemctl", "start", UNIT])
self.report.add("서비스", "failed → reset-failed → start")
elif state in {"inactive", "unknown"}:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 필수 수정 · HIGH

서비스 상태 조회 실패를 inactive처럼 처리하면 안 됩니다

systemctl show의 종료 코드를 확인하지 않고 ActiveState가 없으면 unknown으로 만든 뒤 서비스를 시작합니다. DBus 장애, unit 미설치, 권한 문제 같은 조회 실패가 안전한 inactive 상태로 변환됩니다.

이유: 상태를 확인할 수 없으면 fail-closed 해야 하는 운영 절차가 오히려 서비스를 변경합니다.

제안: 조회 성공과 필수 속성을 검증한 후에만 상태별 동작을 수행하고 실패 경로 테스트를 추가하십시오.

self._mutate(["sudo", "systemctl", "start", UNIT])
self.report.add("서비스", f"{state} → start")
elif state in {"active", "activating", "reloading"}:
self.report.add("서비스", f"{state} (변경 없음)")
else:
raise StepFailed(f"서비스 상태 {state}: 수동 확인 필요")

def _drop_in(self) -> None:
source = DROP_IN_SOURCE / DROP_IN_NAME
target = DROP_IN_DIR / DROP_IN_NAME
same = self.runner(["cmp", "-s", str(source), str(target)])
if same.returncode == 0:
self.report.add("Restart=no", "설치됨")
return
self._mutate(["sudo", "install", "-D", "-m", "644", str(source), str(target)])
self._mutate(["sudo", "systemctl", "daemon-reload"])
self.report.add("Restart=no", "drop-in 설치 → daemon-reload (재부팅 후 유지)")

def _queue(self) -> None:
if not self.queue_cleared:
raise StepFailed(
"대기 실행 정리 미확인: Server 에서 오래된 대기 실행 정리 후 "
"--queue-cleared 로 재실행"
)
self.report.add("대기 실행", "운영자 정리 확인")

def _switch_on(self) -> None:
if self.switch_command is None:
self.report.add("켜기", "건너뜀(수동)")
return
result = self._mutate(self.switch_command)
if result.returncode != 0:
raise StepFailed(f"켜기 명령 실패(exit {result.returncode})")
if not self.execute:
self.report.add("켜기", "dry-run")
return
self._wait_for(
"READY",
lambda s: _physical(s).get("state") == "READY",
"켜기 후 READY 아님: status.json 의 physicalExecution.reasons 확인",
)
self.report.add("켜기", "READY")

def _mutate(self, command: Sequence[str]) -> CommandResult:
return self.runner(command)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 필수 수정 · HIGH

systemd 및 drop-in 변경 실패가 성공으로 보고됩니다

reset-failed, start, install, daemon-reload의 종료 코드를 전혀 검사하지 않습니다. 예를 들어 drop-in 설치가 실패해도 보고서에는 설치 완료가 기록되고 이후 물리 동작 켜기 단계까지 진행할 수 있습니다.

이유: 운영자가 의존하는 안전 설정의 적용 여부와 스크립트 보고가 달라질 수 있습니다.

제안: 필수 변경용 검사 헬퍼를 두어 0이 아닌 종료 코드에서 즉시 중단하십시오.


def _wait_for(
self,
name: str,
ready: Callable[[dict[str, object]], bool],
failure: str,
) -> dict[str, object]:
deadline = self.monotonic() + self.wait_seconds
attempts = 0
while True:
attempts += 1
status = self.status_reader(self.status_path)
if status is not None and ready(status):
self.report.add(name, f"확인({attempts}회)")
return status
if self.monotonic() >= deadline:
raise StepFailed(failure)
self.sleep(self.poll_seconds)


def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--execute", action="store_true", help="actually run commands")
parser.add_argument("--status-path", type=Path, default=STATUS_PATH)
parser.add_argument("--queue-cleared", action="store_true")
parser.add_argument("--switch-command", help="operator switch-on command, e.g. '<path> on'")
parser.add_argument("--wait-seconds", type=float, default=180.0)
parser.add_argument("--poll-seconds", type=float, default=5.0)
parser.add_argument(
"--simulate-state",
default="failed",
choices=["failed", "inactive", "active"],
help="dry-run only: assumed service ActiveState",
)
parser.add_argument("--simulate-drop-in", action="store_true", help="dry-run only")
return parser


def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
runner: Runner = (
subprocess_runner
if args.execute
else DryRunRunner(args.simulate_state, args.simulate_drop_in)
)
starter = EventStart(
runner=runner,
status_path=args.status_path,
execute=args.execute,
queue_cleared=args.queue_cleared,
switch_command=shlex.split(args.switch_command) if args.switch_command else None,
wait_seconds=args.wait_seconds,
poll_seconds=args.poll_seconds,
)
summary = starter.run()
print(summary, flush=True)
return 1 if summary.startswith("FAIL") else 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading