Read audit files for the Console shipper

Merged
YO
4d ago
+1884-7

Summary

RFC 021 sends a server's audit entries to Dagu Console, so the record of who did what outlives the server and its 7-day local retention. Masking at write (#4050) and cleanup records with file sizes (#4068) are in. This is task D3 (tracker dagucloud/cloud#51): the reading half of the shipper. It tails the daily audit files by byte offset, picks the entries the level sends, turns what it cannot send into gaps, and hands batches to a sender. Nothing starts it yet; the sender, the cloud.audit setting, and the drain on stop are D4.

Changes

  • internal/persis/file/audit gains a Feed that reads the audit files back after a saved position, one byte offset per day file. It returns only lines that end in a newline, so a line still being written waits.
    • A line that does not parse, or is over 1 MiB, is a rejected loss from the entry before it to the entry after it. A run of them stays open across reads until the entry after it, and one no entry closes ends at midnight once its day is over. A line still growing past 1 MiB is passed over as it grows, not read again.
    • Once a full read has reached the end of today's file, a file gone from disk is a deleted loss unless the shipper had read up to the size its cleanup record gave. A file never read that a cleanup record lists counts from offset 0, as one dagu secret wrote while the server was stopped. Cleanup records written before the shipper first ran are ignored.
  • internal/cloudreport gains the shipper loop:
    • It holds its own lease, separate from the DAG-run events lease, so one process per installation sends whatever cloud.report is.
    • It checks today's file every 5 seconds and every file once a minute, so an entry that lands in yesterday's file after midnight is found within a minute.
    • It sends only entries with "masked": true, and of an MCP call only its result. At changes it skips successful reads, which are resource reads and dagu_read calls. Skipped entries still move the position.
    • It sends up to 1,000 entries per batch, and a batch takes no more reads once it holds 4 MiB. The next batch goes at once after a full one.
    • It merges losses into one gap per reason. The wire contract carries one gap per request, so a second reason waits in the state for the next request. A gap's ID derives from its reason and range, so a resent gap is stored once.
    • It saves its position only after the sender reports the batch stored. With no saved state, it first saves where it starts, so a file removed before the first batch is stored still counts as lost.
    • A check of every file stays due until what it found is stored. Stopping interrupts a long read. A batch Console did not store goes again as built, without reading again.
  • The cleaner and the feed share the audit_cleanup action and the day-file name parsing.

Core change

A pass first sends again a batch Console did not store, as built. It then reads after the saved position, sends, and saves only once Console stores the batch. A check of every file counts as done only when the whole pass succeeds (internal/cloudreport/audit.go:190):

for {
	pass, resend := s.pending, s.pending != nil
	if !resend {
		built, err := s.build(ctx, full)
		... // return on stop or a read error
		pass = &built
	}
	if len(pass.batch.Entries) == 0 && pass.batch.Gap == nil {
		// Entries the level skips still move the position.
		...
		break
	}
	if err := s.send(ctx, pass.batch); err != nil {
		s.pending = pass
		...
		return
	}
	s.pending = nil
	if !s.save(ctx, pass.next) {
		return
	}
	if !pass.more && !resend {
		break
	}
}
if full {
	s.scannedAt = startedAt
}

A removed file is lost only past what was read of it (internal/persis/file/audit/feed.go:421):

if file.Recorded == nil || *file.Recorded > file.Offset {
	// Covers a run of bad lines still open in it too.
	r.lose(audit.LossDeleted, file.since(day), day.AddDate(0, 0, 1))
} else {
	r.closeRejected(file, day)
}
delete(r.pos.Files, name)

Testing

Feed (internal/persis/file/audit/feed_test.go):

  • TestFeed_RejectsBadLines: a garbled line, a non-JSON line, or one over 1 MiB between two good entries. Both entries are returned, with one rejected loss between their timestamps (RFC 021 Verification 6).
  • TestFeed_FullReadFindsLateEntriesInOlderFiles: an entry stamped 23:59:59.9 and appended after midnight into yesterday's file. Today's check misses it; the full read returns it (Verification 3).
  • TestFeed_Retention, with the real cleaner (Verification 2):
    • A file read to its end, then expired: no loss.
    • A file with unread entries: a deleted loss from the last entry read.
    • A file written while the shipper was not running, then expired: a loss for its whole day.
    • A file removed before the first read: no loss.
    • A file deleted by hand: a loss.
  • Also: resuming after a position, a partial last line, the keep filter, and the limit.

Shipper (internal/cloudreport/audit_test.go), with a real store, feed, lease, and state file in a temp dir and the reporter tests' fake clock:

  • TestAuditShipperLevels: 100 MCP calls (80 dagu_read, 20 dagu_change) write 300 local entries. 20 are sent at changes and 100 at all (the level part of Verification 1).
  • TestAuditShipperSendsWhatTheLevelSends: failed and denied reads are sent, received and started are not, and a tool name masked on disk is sent.
  • TestAuditShipperSendsOnlyMaskedEntries, TestAuditShipperSendsFullBatchesAtOnce (1,500 entries go out as 1,000 then 500 with no wait), and TestAuditShipperResendsWhatConsoleDidNotStore.
  • TestAuditShipperFindsLateEntriesWithinAMinute, TestAuditShipperSendsOneGapPerBatch, TestAuditGapIDDerivesFromReasonAndRange.
  • From review: TestAuditShipperKeepsItsStartWhenTheFirstSendFails, TestAuditShipperRepeatsAFailedFullCheck, TestAuditShipperBoundsBatchBytes, TestAuditShipperStopsDuringALongRead, TestAuditShipperResendsWithoutReadingAgain, TestFeed_ContinuesAFullReadThatStopped, TestFeed_ReadsPartialLinesOnlyOnceTheyGrow, TestFeed_Retention/file_ending_in_bad_lines, TestFeed_PassesOverAGrowingOversizedLine, TestFeed_KeepsARejectedRunOpenAcrossReads, TestFeed_KeepsTodaysRejectedRunOpen, and TestFeed_OrdersTheEndsOfARejectedRun. Each failed before its fix.
  • TestAuditShipperLease: a second process stands by, takes over when the first stops, and goes on from the saved position.
  • TestAuditShipperIdleWritesNothing: skipped entries save the position once; idle passes write nothing.
  • I broke each rule in turn (no masked check, sending received, a full check on every pass, no immediate next batch, saving after a failed send, saving when idle, ignoring recorded sizes, ignoring when the shipper first ran, the line cap), and a test failed each time.
  • I ran go test -race on internal/cloudreport, internal/persis/file/audit, and internal/audit, and golangci-lint on them for Linux and Windows.

Performance

Risk: a periodic stat, but the loop is not started yet. Once D4 starts it:

  • Who runs it: only the lease holder, one process per installation, and not at all at cloud.audit: off.
  • Every 5 seconds: one stat of today's audit file. A file is opened only when it grew past its offset.
  • Every minute: one directory read and one lstat per day file, 8 at the default 7-day retention.
  • Lease: a heartbeat every 20 seconds, within the lease's stale threshold.
  • Reads: only bytes past the offsets, at most 4 MiB per read. Lines over 1 MiB are not kept in memory, and the part of one already read is not read again. A partial line under 1 MiB counts toward the budget and is read again only once its file grows.
  • Memory: a batch holds at most 1,000 entries and about 9 MiB of them. A batch Console did not store is kept and sent again as built, so a failing Console costs no reads.
  • Writes: the state file, under 1 KB at the default retention, once at the first start, and then only after a batch is stored or entries were skipped. An idle server writes nothing.
  • Scale: nothing grows with DAGs, runs, steps, workers, or browser tabs. Audit entries come from user actions.

Compatibility

  • No persisted format changes. The state file <data_dir>/cloud/audit-state.json and its lease are new, and nothing creates them until D4.
  • internal/audit gains FeedQuery, FeedChunk, FeedLoss, LossDeleted, and LossRejected. internal/persis/file/audit gains Feed and NewFeed. Everything in cloudreport stays private.

Review guide

The diff is about 1,700 lines, about half of it tests.

flowchart LR
  F["audit files<br/>(day .jsonl)"] -->|"stat 5s / list 1m"| FE["Feed.Read (new)<br/>offsets, complete lines"]
  FE -->|"entries, losses,<br/>position"| SH["auditShipper (new)<br/>level filter, gaps"]
  SH -->|"≤1,000 entries, ≤1 gap"| SE["send (D4)"]
  SE -->|"stored"| ST["audit-state.json (new)<br/>position, unsent gaps"]
  ST --> SH
  • Mechanical: the shared cleanupAction and fileDay in the cleaner, and the test helpers.
  • Judgment calls:
    • Loss ranges: a deleted loss runs from the last entry read in the file, or its day's start, to the day's end. A rejected one runs between the good entries around it.
    • Ignored records: cleanup records written before the shipper's first position are ignored, so history deleted before shipping was on is not reported as lost.
    • Gaps: one per reason, waiting in the state, since a request carries one gap.
    • Reads: "a read" means resource reads and dagu_read calls, with the tool list beside the filter. A tool name masked on disk counts as not a read.

Out of scope

  • The HTTP sender and status handling (401, 402, 410, 413, 429, 503), a byte budget per request, cutting fields, the drain and stopped gap on stop, and the cloud.audit setting: D4.
  • The backlog in the report: D5.