Serialize gateway log compaction safely
This commit is contained in:
@@ -863,7 +863,6 @@ def list_service(kind):
|
||||
def service_logs(kind, args):
|
||||
max_lines = int(cli_option(args, "--lines", "--tail", default="120"))
|
||||
path = service_log_path(kind)
|
||||
compact_log_file(path)
|
||||
lines = log_tail_lines(path, max_lines=max_lines)
|
||||
status = "ok" if path.exists() else "missing"
|
||||
return {
|
||||
|
||||
@@ -614,6 +614,7 @@ def compact_log_file(path, max_bytes):
|
||||
if max_bytes <= 0:
|
||||
return
|
||||
file_path = pathlib.Path(path)
|
||||
with GATEWAY_LOG_LOCK:
|
||||
try:
|
||||
size = file_path.stat().st_size
|
||||
except FileNotFoundError:
|
||||
@@ -632,10 +633,10 @@ def compact_log_file(path, max_bytes):
|
||||
if newline_index >= 0 and newline_index + 1 < len(chunk):
|
||||
chunk = chunk[newline_index + 1 :]
|
||||
try:
|
||||
# Keep the inode stable: the daemon's stdout/stderr already point to
|
||||
# this file. Replacing the pathname would leave the live process
|
||||
# writing to a deleted inode and make `nap gateway logs` stale.
|
||||
with GATEWAY_LOG_LOCK, file_path.open("r+b") as handle:
|
||||
# Keep the inode stable: the daemon's stdout/stderr already point
|
||||
# to this file. The same lock covers the read/truncate interval so
|
||||
# a concurrent gateway_log append cannot be discarded.
|
||||
with file_path.open("r+b") as handle:
|
||||
handle.seek(0)
|
||||
handle.write(chunk)
|
||||
handle.truncate()
|
||||
|
||||
@@ -329,3 +329,15 @@ def test_cli_log_compaction_preserves_live_writer_inode(tmp_path):
|
||||
content = log_path.read_bytes()
|
||||
assert content.endswith(b"after-cli-compaction\n")
|
||||
assert b"recent-line\n" in content
|
||||
|
||||
|
||||
def test_logs_command_never_compacts_a_running_service_log(tmp_path, monkeypatch):
|
||||
module = load_installer()
|
||||
log_path = tmp_path / "gateway.log"
|
||||
log_path.write_text("one\ntwo\n", encoding="utf-8")
|
||||
monkeypatch.setattr(module, "service_log_path", lambda kind: log_path)
|
||||
monkeypatch.setattr(module, "compact_log_file", fail_if_called)
|
||||
|
||||
result = module.service_logs("gateway", ["--lines", "1"])
|
||||
|
||||
assert result["lines"] == ["two"]
|
||||
|
||||
Reference in New Issue
Block a user