Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
84 changes: 68 additions & 16 deletions artemis/runtime/device_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from dataclasses import dataclass
from datetime import UTC, datetime
import json
import logging
import os
from pathlib import Path
import re
Expand All @@ -32,6 +33,8 @@
from artemis.config.paths import get_temp_dir
from artemis.runtime.process_probe import pid_is_alive

logger = logging.getLogger(__name__)


LEASE_HANDOFF_ENV = "ARTEMIS_DEVICE_LEASE_HANDOFF"
MANAGED_AVD_ADMISSION_TIMEOUT_SECONDS = 2.0
Expand Down Expand Up @@ -90,6 +93,8 @@ class DeviceExecutionLock:
"""

_MALFORMED_LOCK_GRACE_SECONDS = 5.0
_PUBLICATION_TEMP_MAX_AGE_SECONDS = 60.0
_link_warned = False # one hard-link fallback warning per process
_DEFAULT_POLL_INTERVAL_SECONDS = 0.1
QUEUE_TICKET_ENV = "ARTEMIS_DEVICE_QUEUE_TICKET"
# CHE-5297: path of the DLP-1 broker's shared claim guard (flock), when composed.
Expand Down Expand Up @@ -292,6 +297,58 @@ def _atomic_write_json(cls, path: Path, payload: dict) -> bool:
cls._safe_unlink(temp_path)
return True

@staticmethod
def _write_all(fd: int, data: bytes) -> None:
"""Write all of ``data`` or raise; ``os.write`` may write fewer bytes."""
while data:
written = os.write(fd, data)
if written <= 0:
raise OSError("short write while publishing lock record")
data = data[written:]

@classmethod
def _publish_exclusive(cls, path: Path, payload: dict) -> bool:
"""Create ``path`` with its whole record, or return False if it exists.

The record is written to a temp file first and hard-linked into place, so
no reader (or stale-record reaper) ever sees an empty ``path``. No fsync:
the record only has to be whole for readers on this machine.
"""
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
temp_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
fd = os.open(temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
try:
try:
cls._write_all(fd, data)
finally:
os.close(fd)
try:
os.link(temp_path, path)
except FileExistsError:
return False
except OSError:
if not DeviceExecutionLock._link_warned:
DeviceExecutionLock._link_warned = True
logger.warning(
"Hard links unavailable in %s; publishing lock records non-atomically",
path.parent,
)
try:
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
return False
written = False
try:
cls._write_all(fd, data)
written = True
finally:
os.close(fd)
if not written:
cls._safe_unlink(path)
return True
finally:
cls._safe_unlink(temp_path)

@classmethod
def _ticket_targets_device(
cls,
Expand Down Expand Up @@ -416,15 +473,7 @@ def reserve(
)
for _ in range(8):
path = queue_dir / f"{time.time_ns():020d}-{token}.wait"
try:
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
continue
else:
try:
os.write(fd, json.dumps(payload, ensure_ascii=False).encode("utf-8"))
finally:
os.close(fd)
if cls._publish_exclusive(path, payload):
return token
raise DeviceBusyError("Could not reserve a position in the Artemis device queue.")

Expand Down Expand Up @@ -722,9 +771,7 @@ def _try_acquire_owner_lock_unguarded(self) -> bool:
)
if self._webusb_claim_alias is not None:
owner_payload["webusb_claim_alias"] = self._webusb_claim_alias
try:
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
if not self._publish_exclusive(self.path, owner_payload):
current_owner = self._read_owner(self.path)
if (
current_owner is not None
Expand All @@ -738,10 +785,6 @@ def _try_acquire_owner_lock_unguarded(self) -> bool:
return True
self._remove_stale_lock()
return False
try:
os.write(fd, json.dumps(owner_payload, ensure_ascii=False).encode("utf-8"))
finally:
os.close(fd)
self._acquired = True
return True

Expand Down Expand Up @@ -1224,4 +1267,13 @@ def cleanup_stale_locks(cls, device_id: str | None = None) -> int:
continue
if cls._safe_unlink(path):
removed += 1

# Temp records of a writer that died before linking them into place.
for folder in [lock_dir, *(d for d in lock_dir.glob("*.queue") if d.is_dir())]:
for path in folder.glob("*.tmp"):
try:
if time.time() - path.stat().st_mtime > cls._PUBLICATION_TEMP_MAX_AGE_SECONDS:
cls._safe_unlink(path)
except OSError:
continue
return removed
8 changes: 6 additions & 2 deletions tests/unit/admin_console/test_host_nack_races.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,12 +371,16 @@ def acquire():
thread.start()
assert lease_created.wait(5)
old_time = time.time() - DeviceExecutionLock._MALFORMED_LOCK_GRACE_SECONDS - 1
os.utime(lock.path, (old_time, old_time))
pending = list(lock.path.parent.glob(f"{lock.path.name}.*.tmp"))
assert pending
assert not lock.path.exists()
for record in pending:
os.utime(record, (old_time, old_time))
kills_while_locked = []
worker.kill.side_effect = lambda: kills_while_locked.append(lock._acquired)
try:
first_decision = await TaskQueueService.requeue_starting("r1")
file_kept_after_refusal = lock.path.exists()
file_kept_after_refusal = all(record.exists() for record in pending)
allow_write.set()
assert acquired.wait(5)
assert lock._acquired
Expand Down
146 changes: 146 additions & 0 deletions tests/unit/runtime/test_device_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,3 +733,149 @@ def test_managed_avd_does_not_retry_occupied_device(
broker_rpc.assert_called_once()
readback.assert_not_called()
sleep.assert_not_called()


# -- CHE-10242: records are published whole, so a paused writer keeps its place --


def _age_publications(folder, prefix, seconds):
old = time.time() - seconds
for path in folder.iterdir():
if path.name.startswith(prefix):
os.utime(path, (old, old))


def _pausing_write(monkeypatch, marker):
"""Block os.write for a payload holding ``marker``; return (entered, release)."""
entered, release = threading.Event(), threading.Event()
real_write = os.write

def write(descriptor, payload):
if marker in payload:
entered.set()
assert release.wait(5)
return real_write(descriptor, payload)

monkeypatch.setattr(os, "write", write)
return entered, release


def test_a_paused_writer_never_yields_two_owners(tmp_path, monkeypatch):
first = DeviceExecutionLock("emulator-5554", "first", session_id="s-first")
second = DeviceExecutionLock("emulator-5554", "second", session_id="s-second")
entered, release = _pausing_write(monkeypatch, first.token.encode())
thread = threading.Thread(target=first._try_acquire_owner_lock_unguarded)
thread.start()
try:
assert entered.wait(5)
_age_publications(
tmp_path, first.path.name, DeviceExecutionLock._MALFORMED_LOCK_GRACE_SECONDS + 1
)
for _ in range(3):
if second._try_acquire_owner_lock_unguarded():
break
finally:
release.set()
thread.join(5)
assert not thread.is_alive()
assert [first._acquired, second._acquired].count(True) == 1
winner = first if first._acquired else second
assert json.loads(first.path.read_text())["token"] == winner.token
winner.release()


def test_a_paused_ticket_keeps_its_place(tmp_path, monkeypatch):
entered, release = _pausing_write(monkeypatch, b"paused-ticket")
tokens = []
thread = threading.Thread(
target=lambda: tokens.append(
DeviceExecutionLock.reserve("probe", "d1", session_id="paused-ticket")
)
)
thread.start()
try:
assert entered.wait(5)
queue = tmp_path / "artemis-global-device.queue"
_age_publications(queue, "", DeviceExecutionLock._MALFORMED_LOCK_GRACE_SECONDS + 1)
DeviceExecutionLock.cleanup_stale_locks()
finally:
release.set()
thread.join(5)
assert not thread.is_alive()
(ticket,) = queue.glob("*.wait")
assert ticket.name == f"{ticket.name[:20]}-{tokens[0]}.wait"
assert ticket.name[:20].isdigit()
DeviceExecutionLock.cancel_reservation(tokens[0])


def test_reentrant_acquire_by_the_same_token_still_succeeds():
lock = DeviceExecutionLock("emulator-5554", "again")
assert lock._try_acquire_owner_lock_unguarded()
try:
assert lock._try_acquire_owner_lock_unguarded()
finally:
lock.release()


def test_hard_link_failure_falls_back_and_warns_once(monkeypatch, caplog):
def no_link(*_args, **_kwargs):
raise PermissionError("no hard links here")

monkeypatch.setattr(os, "link", no_link)
monkeypatch.setattr(DeviceExecutionLock, "_link_warned", False)
with caplog.at_level("WARNING", logger="artemis.runtime.device_lock"):
for device in ("emulator-5554", "emulator-5556"):
lock = DeviceExecutionLock(device, "fallback")
assert lock._try_acquire_owner_lock_unguarded()
assert json.loads(lock.path.read_text())["token"] == lock.token
lock.release()
assert len([r for r in caplog.records if r.levelname == "WARNING"]) == 1


def test_short_writes_are_completed_before_publication(monkeypatch):
real_write = os.write
monkeypatch.setattr(os, "write", lambda fd, data: real_write(fd, bytes(data)[:1]))
lock = DeviceExecutionLock("emulator-5554", "short-write")
assert lock._try_acquire_owner_lock_unguarded()
assert json.loads(lock.path.read_text())["token"] == lock.token
lock.release()


def test_a_failed_write_publishes_nothing(tmp_path, monkeypatch):
real_write = os.write

def write_one_then_fail(fd, data):
if len(data) > 1:
return real_write(fd, bytes(data)[:1])
return 0

monkeypatch.setattr(os, "write", write_one_then_fail)
target = tmp_path / "record.lock"
with pytest.raises(OSError):
DeviceExecutionLock._publish_exclusive(target, {"token": "x"})
assert list(tmp_path.iterdir()) == []


def test_cleanup_removes_only_old_publication_temp_files(tmp_path):
queue = tmp_path / "artemis-global-device.queue"
queue.mkdir()
live = DeviceExecutionLock("emulator-5554", "live")
live.acquire()
ticket = DeviceExecutionLock.reserve("queued", "emulator-5556")
old_temp = tmp_path / "artemis-device-x.lock.aaaa.tmp"
old_queue_temp = queue / "0001-t.wait.bbbb.tmp"
fresh_temp = tmp_path / "artemis-device-y.lock.cccc.tmp"
for path in (old_temp, old_queue_temp, fresh_temp):
path.write_text("{}")
for path in (old_temp, old_queue_temp):
os.utime(path, (time.time() - 61, time.time() - 61))
try:
DeviceExecutionLock.cleanup_stale_locks()
assert not old_temp.exists()
assert not old_queue_temp.exists()
assert fresh_temp.exists()
assert live.path.exists()
assert list(queue.glob(f"*-{ticket}.wait"))
finally:
live.release()
DeviceExecutionLock.cancel_reservation(ticket)
Loading