firewatcher 1.66__tar.gz → 1.67__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {firewatcher-1.66/firewatcher.egg-info → firewatcher-1.67}/PKG-INFO +2 -2
  2. {firewatcher-1.66 → firewatcher-1.67}/README.md +1 -1
  3. firewatcher-1.67/docs/lessons-full.md +37 -0
  4. firewatcher-1.67/docs/lessons.md +13 -0
  5. {firewatcher-1.66 → firewatcher-1.67}/docs/limitations.md +2 -2
  6. {firewatcher-1.66 → firewatcher-1.67/firewatcher.egg-info}/PKG-INFO +2 -2
  7. {firewatcher-1.66 → firewatcher-1.67}/firewatcher.egg-info/SOURCES.txt +2 -0
  8. {firewatcher-1.66 → firewatcher-1.67}/firewatcher.py +58 -12
  9. {firewatcher-1.66 → firewatcher-1.67}/tests/test_cli.py +1 -1
  10. {firewatcher-1.66 → firewatcher-1.67}/tests/test_compressor.py +70 -2
  11. {firewatcher-1.66 → firewatcher-1.67}/tests/test_position.py +149 -14
  12. {firewatcher-1.66 → firewatcher-1.67}/LICENSE +0 -0
  13. {firewatcher-1.66 → firewatcher-1.67}/MANIFEST.in +0 -0
  14. {firewatcher-1.66 → firewatcher-1.67}/examples/firewatcher.conf +0 -0
  15. {firewatcher-1.66 → firewatcher-1.67}/examples/nvme_failure.regex +0 -0
  16. {firewatcher-1.66 → firewatcher-1.67}/examples/sys_msg.txt +0 -0
  17. {firewatcher-1.66 → firewatcher-1.67}/firewatcher.egg-info/dependency_links.txt +0 -0
  18. {firewatcher-1.66 → firewatcher-1.67}/firewatcher.egg-info/entry_points.txt +0 -0
  19. {firewatcher-1.66 → firewatcher-1.67}/firewatcher.egg-info/top_level.txt +0 -0
  20. {firewatcher-1.66 → firewatcher-1.67}/setup.cfg +0 -0
  21. {firewatcher-1.66 → firewatcher-1.67}/setup.py +0 -0
  22. {firewatcher-1.66 → firewatcher-1.67}/tests/conftest.py +0 -0
  23. {firewatcher-1.66 → firewatcher-1.67}/tests/test_capture.py +0 -0
  24. {firewatcher-1.66 → firewatcher-1.67}/tests/test_config.py +0 -0
  25. {firewatcher-1.66 → firewatcher-1.67}/tests/test_events.py +0 -0
  26. {firewatcher-1.66 → firewatcher-1.67}/tests/test_log_source.py +0 -0
  27. {firewatcher-1.66 → firewatcher-1.67}/tests/test_matching.py +0 -0
  28. {firewatcher-1.66 → firewatcher-1.67}/tests/test_notify.py +0 -0
  29. {firewatcher-1.66 → firewatcher-1.67}/tests/test_patterns.py +0 -0
  30. {firewatcher-1.66 → firewatcher-1.67}/tests/test_redirects.py +0 -0
  31. {firewatcher-1.66 → firewatcher-1.67}/tests/test_slugify.py +0 -0
  32. {firewatcher-1.66 → firewatcher-1.67}/tests/test_systemd.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: firewatcher
3
- Version: 1.66
3
+ Version: 1.67
4
4
  Summary: Watch logs for incident patterns and persist surrounding context off-box
5
5
  Home-page: https://github.com/yufei-pan/firewatcher
6
6
  Author: Yufei Pan
@@ -85,7 +85,7 @@ SIGHUP reloads the pattern files and the `--always-notify` files from the paths
85
85
 
86
86
  ### Resuming after a restart
87
87
 
88
- When firewatcher follows the journal (not a log file), it saves how far it has read in `--position-file` (default `/var/lib/firewatcher/journal.position`): about once a second while lines arrive or a capture is open, as soon as a match opens a capture, and when it stops. After a restart it reads on from there instead of the last `--tail-lines` lines; after a crash or `kill -9`, that can be up to about a second before the last line it read. Lines logged while it was stopped, such as during a reboot, are still matched, and an incident it already captured is not captured again. The `--capture-time` seconds before the saved line are read again only to refill the context kept before a match. At most `--resume-max` seconds (default 3600) are read back, so after a longer stop only the last hour is matched.
88
+ When firewatcher follows the journal (not a log file), it saves how far it has read in `--position-file` (default `/var/lib/firewatcher/journal.position`): about once a second while lines arrive or a capture is open (the open capture is fsynced first, so a saved position never covers capture lines that are not on disk), as soon as a match opens a capture, and when it stops. After a restart it reads on from there instead of the last `--tail-lines` lines; after a crash or `kill -9`, that can be up to about a second before the last line it read. Each save is fsynced before it replaces the old one, so a hard reset or power loss leaves the last or the previous position, never an empty file. Lines logged while it was stopped, such as during a reboot, are still matched, and an incident it already captured is not captured again. The `--capture-time` seconds before the saved line are read again only to refill the context kept before a match. At most `--resume-max` seconds (default 3600) are read back, so after a longer stop only the last hour is matched.
89
89
 
90
90
  To tell where it stopped, firewatcher reads the journal with `journalctl -o short-iso`, so journal lines in captures carry the year and time zone: `2026-10-23T17:52:41+00:00 host sshd[812]: …` instead of `Oct 23 17:52:41 host sshd[812]: …`. Lines logged while firewatcher was stopped arrive all at once. A capture opened by one of them takes its context from the `--capture-time` before that line by the time each line was logged, and holds the lines after it as they are read, up to `--capture-line-count-max`.
91
91
 
@@ -58,7 +58,7 @@ SIGHUP reloads the pattern files and the `--always-notify` files from the paths
58
58
 
59
59
  ### Resuming after a restart
60
60
 
61
- When firewatcher follows the journal (not a log file), it saves how far it has read in `--position-file` (default `/var/lib/firewatcher/journal.position`): about once a second while lines arrive or a capture is open, as soon as a match opens a capture, and when it stops. After a restart it reads on from there instead of the last `--tail-lines` lines; after a crash or `kill -9`, that can be up to about a second before the last line it read. Lines logged while it was stopped, such as during a reboot, are still matched, and an incident it already captured is not captured again. The `--capture-time` seconds before the saved line are read again only to refill the context kept before a match. At most `--resume-max` seconds (default 3600) are read back, so after a longer stop only the last hour is matched.
61
+ When firewatcher follows the journal (not a log file), it saves how far it has read in `--position-file` (default `/var/lib/firewatcher/journal.position`): about once a second while lines arrive or a capture is open (the open capture is fsynced first, so a saved position never covers capture lines that are not on disk), as soon as a match opens a capture, and when it stops. After a restart it reads on from there instead of the last `--tail-lines` lines; after a crash or `kill -9`, that can be up to about a second before the last line it read. Each save is fsynced before it replaces the old one, so a hard reset or power loss leaves the last or the previous position, never an empty file. Lines logged while it was stopped, such as during a reboot, are still matched, and an incident it already captured is not captured again. The `--capture-time` seconds before the saved line are read again only to refill the context kept before a match. At most `--resume-max` seconds (default 3600) are read back, so after a longer stop only the last hour is matched.
62
62
 
63
63
  To tell where it stopped, firewatcher reads the journal with `journalctl -o short-iso`, so journal lines in captures carry the year and time zone: `2026-10-23T17:52:41+00:00 host sshd[812]: …` instead of `Oct 23 17:52:41 host sshd[812]: …`. Lines logged while firewatcher was stopped arrive all at once. A capture opened by one of them takes its context from the `--capture-time` before that line by the time each line was logged, and holds the lines after it as they are read, up to `--capture-line-count-max`.
64
64
 
@@ -0,0 +1,37 @@
1
+ # Lessons: full entries
2
+
3
+ Why this project's APIs, formats and agreed behaviours had to change. `lessons.md` has one line per
4
+ entry: read that first, and look entries up here by date and name rather than reading this whole. New
5
+ entries go last, in the same commit as the change:
6
+
7
+ ```markdown
8
+ ## YYYY-MM-DD <short name>
9
+ - Changed: ...
10
+ - Why we had to change: ...
11
+ - Original design was wrong because: ...
12
+ - Lesson: ...
13
+ ```
14
+
15
+ ## 2026-10-27 firewatcher: the model's excerpt is built from where the events are, not from the file's ends
16
+ - Changed: the excerpt of a large capture sent to the LLM is the header, the lines before the match, the lines after it and the end of the capture, located by byte offsets capture_messages records as it writes (GitHub 1.61/1.62 of 2026-10-23, first published to PyPI as 1.63). 1.60 sent the first 2 KB and the last ~46 KB.
17
+ - Why we had to change: captures hold 5 minutes before and after the match, so in 35 of 49 captures on one server in October the matched event was in the gap and the model judged an incident it never saw. Keeping the end matters too: on 2026-10-23 a failed backup's retry succeeded in the last minutes of the capture, and that is what kept the model from pushing.
18
+ - Original design was wrong because: it cut by position (start and end) a record whose important part sits at a known place in the middle, and it located nothing by what the writer already knew (where it wrote the match).
19
+ - Lesson: when a record must be cut to a budget, record where its important parts are while writing it, cut around those, and keep the end where outcomes show. A budget split must never shrink a piece when the budget grows (a superseded attempt that did kept producing new edge cases).
20
+
21
+ ## 2026-10-27 firewatcher: --requires-mounts-for paths are normalized as text, never resolved on disk
22
+ - Changed: in 1.64 each `--requires-mounts-for` path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`), from its bytes, and quoted with `%` doubled. A path with a newline or carriage return, or one that is not UTF-8, is refused before anything is installed. Before, the path was written raw. Symlinks are not followed and the file system is not touched.
23
+ - Why we had to change: systemd splits an unquoted path at spaces, expands `%`, and ignores relative and unnormalized paths. So a unit could wait on the wrong mount, or on none, and start before an NFS share was up, with only a warning in the journal.
24
+ - Original design was wrong because: it passed operator text into a file with its own syntax (unit-file quoting, specifiers, path rules) as if it were plain text, and nothing checked what systemd read back. Two later attempts were wrong as well. Refusing `..` broke input that was accepted before. Resolving with realpath could follow a symlink off the remote share, hang on a dead hard-NFS mount, trigger automounts, and make the result depend on what was mounted at install time.
25
+ - Lesson: when you write a value into another program's file format, test what that program reads back for each odd input, against the real program. Transform the value only as the reading program would (here as text, like systemd), never by consulting state that may be absent or hung at the time you write.
26
+
27
+ ## 2026-11-03 firewatcher 1.65: the verdict moved to the receiver
28
+ - Changed: with `[notify] events_url` set, every finished capture is POSTed as JSON (with an excerpt of up to 16 KiB) and firewatcher's own LLM analysis is off, whatever `[llm] enabled` says; a startup line says so. The event's `push` is the rule-based floor, `always_notify`. `model_notify` stays in the event, always `null`. A 2xx answer means the receiver has the capture and nothing goes to ntfy. When the POST fails, only `always_notify` captures are pushed to ntfy; the others stay in the capture folder and the journal.
29
+ - Why we had to change: the first events_url design (before 1.65 was released) kept firewatcher's own LLM judging the push, and housekeepd followed it, so behaviour stayed the same while events_url was new. Once housekeepd had its own triage, with the host's tools and history, there were two judges, two verdicts, double LLM traffic, and an outside LLM service saw every capture.
30
+ - Original design was wrong because: it kept the judgment at the sender after a better-informed stage existed downstream.
31
+ - Lesson: when a pipeline gains a smarter stage downstream, move the judgment there whole, and keep only the rule-based floor (`always_notify`) at the source.
32
+
33
+ ## 2026-11-03 firewatcher 1.65: a URL is parsed once, by our own strict rule
34
+ - Changed: one strict check (`_is_http_url`) decides whether an LLM, ntfy or events URL is usable. The request and every log line use only what that check matched; a `user:password` is stripped and never sent or logged, and a URL is shown only as its server (`scheme://host[:port]`). Before 1.65 the check only needed an `http://` or `https://` start with no whitespace or control characters. Now firewatcher also stops at startup for: a server part that is not a host name (no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%`) or a bracketed IPv6 address, followed by an optional port of up to 5 digits (0 to 65535), judged also after Unicode NFKC normalization; a `user:password` that holds a `/`, `?` or `#`; and a URL with a `user:password` and another `@` later in its path, query or fragment. A URL without `user:password` may still hold an `@` in its path. With events_url set, a bad `[llm]` URL no longer stops firewatcher, since the LLM does not run.
35
+ - Why we had to change: a password holding an `@` before a `/`, `?` or `#` left the text between them as the host, and the host is logged. Review took five fix rounds on this check (credentials in requests and logs, unparseable URLs echoed, a password holding an `@`), and the last one replaced the library's view of the authority with our own check that gives the same answer on every Python.
36
+ - Original design was wrong because: it used a lenient library parser for a value that is both sent in requests and written to logs, and the old check accepted nearly anything with an http prefix.
37
+ - Lesson: when a value is both used for requests and written to logs, parse it once with our own strict rule that behaves the same on every runtime, not a lenient library parser. Record what that refuses that used to be accepted, as the entry above does.
@@ -0,0 +1,13 @@
1
+ # Lessons
2
+
3
+ What this project's past changes taught us. Read all of this before changing an API, a format or an
4
+ agreed behaviour here. For the full story of a line, find the entry with the same date and name in
5
+ `lessons-full.md`.
6
+
7
+ When one has to change, add the full entry to `lessons-full.md` and one line here, newest last, in the
8
+ same commit as the change. Keep this file under 20 KB: at the cap, merge lines before adding.
9
+
10
+ - **2026-10-27 firewatcher: the model's excerpt is built from where the events are, not from the file's ends**: when a record must be cut to a budget, record where its important parts are while writing it, cut around those, and keep the end where outcomes show. A budget split must never shrink a piece when the budget grows (a superseded attempt that did kept producing new edge cases).
11
+ - **2026-10-27 firewatcher: --requires-mounts-for paths are normalized as text, never resolved on disk**: when you write a value into another program's file format, test what that program reads back for each odd input, against the real program. Transform the value only as the reading program would (here as text, like systemd), never by consulting state that may be absent or hung at the time you write.
12
+ - **2026-11-03 firewatcher 1.65: the verdict moved to the receiver**: when a pipeline gains a smarter stage downstream, move the judgment there whole, and keep only the rule-based floor (`always_notify`) at the source.
13
+ - **2026-11-03 firewatcher 1.65: a URL is parsed once, by our own strict rule**: when a value is both used for requests and written to logs, parse it once with our own strict rule that behaves the same on every runtime, not a lenient library parser. Record what that refuses that used to be accepted, as the entry above does.
@@ -33,8 +33,8 @@ Approved known limitations and deferrals. Reviewers: read this first, and don't
33
33
  with digits followed by `/`), the text up to the `/` is a valid host and port (`u`, port 2024), so firewatcher
34
34
  accepts it and its log lines show `http://u:2024`: the leading digits of the password appear as the port, and the
35
35
  request goes to host `u`. The same holds for a password that starts with `/`, `?` or `#` (`http://usr:/…@h/e`
36
- goes to host `usr`).
36
+ goes to host `usr`). Because such a URL reads as a host and port, firewatcher gives it no user:password warning.
37
37
  - Why: such a URL is valid as written; refusing it would mean refusing an `@` in a URL's path, which valid LLM URLs
38
38
  use. Credentials in a URL are never sent anyway (README: use `events_token`, `token` or `api_key`).
39
39
  - Revisit when: a way to tell such a URL from a real host and path appears, or someone hits it.
40
- - Approved: 2026-11-01, the user ticked "fw: digits shown as port".
40
+ - Approved: 2026-11-01, the user ticked "fw: digits shown as port". The no-warning sentence added 2026-11-04, the user: "Add it to the wording".
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: firewatcher
3
- Version: 1.66
3
+ Version: 1.67
4
4
  Summary: Watch logs for incident patterns and persist surrounding context off-box
5
5
  Home-page: https://github.com/yufei-pan/firewatcher
6
6
  Author: Yufei Pan
@@ -85,7 +85,7 @@ SIGHUP reloads the pattern files and the `--always-notify` files from the paths
85
85
 
86
86
  ### Resuming after a restart
87
87
 
88
- When firewatcher follows the journal (not a log file), it saves how far it has read in `--position-file` (default `/var/lib/firewatcher/journal.position`): about once a second while lines arrive or a capture is open, as soon as a match opens a capture, and when it stops. After a restart it reads on from there instead of the last `--tail-lines` lines; after a crash or `kill -9`, that can be up to about a second before the last line it read. Lines logged while it was stopped, such as during a reboot, are still matched, and an incident it already captured is not captured again. The `--capture-time` seconds before the saved line are read again only to refill the context kept before a match. At most `--resume-max` seconds (default 3600) are read back, so after a longer stop only the last hour is matched.
88
+ When firewatcher follows the journal (not a log file), it saves how far it has read in `--position-file` (default `/var/lib/firewatcher/journal.position`): about once a second while lines arrive or a capture is open (the open capture is fsynced first, so a saved position never covers capture lines that are not on disk), as soon as a match opens a capture, and when it stops. After a restart it reads on from there instead of the last `--tail-lines` lines; after a crash or `kill -9`, that can be up to about a second before the last line it read. Each save is fsynced before it replaces the old one, so a hard reset or power loss leaves the last or the previous position, never an empty file. Lines logged while it was stopped, such as during a reboot, are still matched, and an incident it already captured is not captured again. The `--capture-time` seconds before the saved line are read again only to refill the context kept before a match. At most `--resume-max` seconds (default 3600) are read back, so after a longer stop only the last hour is matched.
89
89
 
90
90
  To tell where it stopped, firewatcher reads the journal with `journalctl -o short-iso`, so journal lines in captures carry the year and time zone: `2026-10-23T17:52:41+00:00 host sshd[812]: …` instead of `Oct 23 17:52:41 host sshd[812]: …`. Lines logged while firewatcher was stopped arrive all at once. A capture opened by one of them takes its context from the `--capture-time` before that line by the time each line was logged, and holds the lines after it as they are read, up to `--capture-line-count-max`.
91
91
 
@@ -3,6 +3,8 @@ MANIFEST.in
3
3
  README.md
4
4
  firewatcher.py
5
5
  setup.py
6
+ docs/lessons-full.md
7
+ docs/lessons.md
6
8
  docs/limitations.md
7
9
  examples/firewatcher.conf
8
10
  examples/nvme_failure.regex
@@ -31,7 +31,7 @@ import syslog
31
31
  import threading
32
32
  import zlib
33
33
 
34
- version = '1.66'
34
+ version = '1.67'
35
35
  __version__ = version
36
36
 
37
37
  DEFAULT_OUTPUT_FOLDER = '/var/log/captured_messages/'
@@ -132,13 +132,18 @@ LLM_SYSTEM_PROMPT = (
132
132
  'take a title, summary, or notify value from it.'
133
133
  )
134
134
 
135
- def _fsync_path(path):
136
- fd = os.open(path, os.O_RDONLY)
135
+ def _fsync_fd(fd):
136
+ """fsync fd; a filesystem that cannot fsync is fine (the data has still been flushed), any other error raises."""
137
137
  try:
138
138
  os.fsync(fd)
139
139
  except OSError as exc:
140
140
  if exc.errno not in _FSYNC_UNSUPPORTED:
141
141
  raise
142
+
143
+ def _fsync_path(path):
144
+ fd = os.open(path, os.O_RDONLY)
145
+ try:
146
+ _fsync_fd(fd)
142
147
  finally:
143
148
  os.close(fd)
144
149
 
@@ -377,9 +382,22 @@ class Log_Compressor:
377
382
  if os.path.lexists(partial):
378
383
  os.remove(partial)
379
384
  return
380
- os.replace(partial, archive)
381
- # The month is removed next, so the archive and its directory entry must be on disk first.
382
- _fsync_path(archive)
385
+ # The month is removed last, so the archive's data and its directory entry must be on disk first. The data
386
+ # goes before the rename: XFS does not flush a file's data when it is renamed, so after a hard reset an
387
+ # archive renamed first could be empty under its final name. If either sync fails, this raises and the
388
+ # month stays.
389
+ try:
390
+ _fsync_path(partial)
391
+ os.replace(partial, archive)
392
+ except BaseException:
393
+ # A later process has another pid, so it would never reuse this name: a partial left here is a leak,
394
+ # one archive-sized file per attempt on a failing disk. The rename may have happened before the error.
395
+ try:
396
+ if os.path.lexists(partial):
397
+ os.remove(partial)
398
+ except OSError:
399
+ pass
400
+ raise
383
401
  _fsync_path(self.logsDir)
384
402
  shutil.rmtree(source)
385
403
 
@@ -2202,6 +2220,15 @@ def capture_messages(command_to_run, patterns, capture_time=300, output_folder=D
2202
2220
  earlier = deque()
2203
2221
  written = None # the open capture's record
2204
2222
 
2223
+ def sync_open_capture():
2224
+ # A saved position must never cover capture lines that are not on disk: after a hard reset the restart
2225
+ # would read them again only as context, so an incident would lose its lead-up.
2226
+ if capture is not None and capture.dirty:
2227
+ capture.sync()
2228
+
2229
+ if journal_position is not None:
2230
+ journal_position.before_save = sync_open_capture
2231
+
2205
2232
  def end_capture(now):
2206
2233
  nonlocal capture, capture_until, capture_ends_by, captured_line_counter, written
2207
2234
  reached_max = capture_ends_by is not None and now >= capture_ends_by
@@ -2242,16 +2269,22 @@ def capture_messages(command_to_run, patterns, capture_time=300, output_folder=D
2242
2269
  sync_due = capture.sync_due() if capture else None
2243
2270
  if sync_due is not None and (deadline is None or sync_due < deadline):
2244
2271
  deadline = sync_due
2272
+ if journal_position is not None and journal_position.changed:
2273
+ # A line the capture synced on commit leaves nothing pending, so without this its
2274
+ # position would wait for the next line, or the end of the capture.
2275
+ if deadline is None or journal_position.next_save < deadline:
2276
+ deadline = journal_position.next_save
2245
2277
  remaining = None if deadline is None else max(0, deadline - time.time())
2246
2278
  line = pending_read.result(timeout=remaining)
2247
2279
  pending_read = None
2248
2280
  except ReadTimeout:
2249
2281
  if journal_position is not None:
2250
- # Saved along with the capture's fsync below, so a quiet journal leaves no line unsaved for long.
2282
+ # The save syncs the capture first (before_save), so a quiet journal leaves no line unsaved for long.
2251
2283
  journal_position.save()
2252
2284
  # Keep the same pending read while the source is quiet.
2253
2285
  if capture and capture_until is not None and time.time() < capture_until:
2254
- capture.sync()
2286
+ if capture.dirty:
2287
+ capture.sync()
2255
2288
  continue
2256
2289
  end_capture(time.time())
2257
2290
  continue
@@ -2826,6 +2859,8 @@ class JournalPosition(object):
2826
2859
  self.ordinal = 0
2827
2860
  self.changed = False
2828
2861
  self.next_save = 0
2862
+ # Called before every write of a changed position; capture_messages sets it to sync the open capture first.
2863
+ self.before_save = None
2829
2864
  self.save_failed = False
2830
2865
  # The time of self.stamp, for the context: a line read long after it was logged keeps its own time.
2831
2866
  self.stamp_time = None
@@ -2899,6 +2934,9 @@ class JournalPosition(object):
2899
2934
  def saw(self, line, now):
2900
2935
  """Record a line as read, before it is handled. The periodic save (at most once per POSITION_SAVE_INTERVAL)
2901
2936
  runs first, so it never covers a line still being handled; unsee() takes the line back."""
2937
+ # Cleared first: a stop that lands inside the save below must not make unsee() take back the line before
2938
+ # this one, which was already handled in full.
2939
+ self.before = None
2902
2940
  if self.changed and now >= self.next_save:
2903
2941
  self.save(now)
2904
2942
  self.before = (self.stamp, self.stamp_time, self.ordinal, self.last_line, self.last_end, self.changed)
@@ -2922,12 +2960,16 @@ class JournalPosition(object):
2922
2960
  self.before = None
2923
2961
 
2924
2962
  def save(self, now=None, final=False):
2925
- """Write the position atomically; a failure is logged once and retried at the next save."""
2963
+ """Write the position atomically; a failure is logged once and retried at the next save.
2964
+
2965
+ final is not used: every save is fsynced. Two test subclasses use it to tell the save at exit from the others."""
2926
2966
  import json
2927
2967
  now = time.time() if now is None else now
2928
2968
  self.next_save = now + POSITION_SAVE_INTERVAL
2929
2969
  if not self.changed:
2930
2970
  return
2971
+ if self.before_save is not None:
2972
+ self.before_save()
2931
2973
  self.changed = False
2932
2974
  import tempfile
2933
2975
  record = {
@@ -2943,9 +2985,13 @@ class JournalPosition(object):
2943
2985
  fd, unfinished = tempfile.mkstemp(prefix=os.path.basename(self.path) + '.', suffix='.tmp', dir=folder)
2944
2986
  with os.fdopen(fd, 'w', encoding='utf-8') as f:
2945
2987
  f.write(json.dumps(record) + '\n')
2946
- if final:
2947
- f.flush()
2948
- os.fsync(f.fileno())
2988
+ # Every save, not only the final one: XFS does not flush a file's data when it is renamed over
2989
+ # another, so after a hard reset an unsynced position could come back empty and the restart would
2990
+ # lose the lead-up to the crash. About 100 bytes per fsync, at most once per POSITION_SAVE_INTERVAL, plus
2991
+ # the save that comes with a capture opening.
2992
+ # The directory is not synced: a rename that is lost leaves the previous position, which resume handles.
2993
+ f.flush()
2994
+ _fsync_fd(f.fileno())
2949
2995
  os.replace(unfinished, self.path)
2950
2996
  except OSError as exc:
2951
2997
  self.changed = True
@@ -104,7 +104,7 @@ def test_parser_rejects_conflicting_service_flags():
104
104
  def test_module_has_no_nebula_product_name():
105
105
  src = open(fw.__file__, encoding='utf-8').read().lower()
106
106
  assert 'nebula' not in src
107
- assert fw.version == '1.66'
107
+ assert fw.version == '1.67'
108
108
  assert fw.__version__ == fw.version
109
109
 
110
110
 
@@ -182,7 +182,7 @@ def test_log_compressor_in_background(tmp_path):
182
182
  blocker.join()
183
183
 
184
184
 
185
- def test_log_compressor_syncs_the_archive_before_removing_the_month(tmp_path, monkeypatch):
185
+ def test_log_compressor_syncs_the_partial_archive_before_removing_the_month(tmp_path, monkeypatch):
186
186
  logs = month_dirs(tmp_path, '2020-01')
187
187
  synced = []
188
188
  real = fw._fsync_path
@@ -193,10 +193,78 @@ def test_log_compressor_syncs_the_archive_before_removing_the_month(tmp_path, mo
193
193
 
194
194
  monkeypatch.setattr(fw, '_fsync_path', recording)
195
195
  fw.Log_Compressor(str(logs), compressAfterMonths=1, deleteLogAfterMonths=0)
196
- assert synced == [(str(logs / '2020-01.tar.xz'), True), (str(logs), True)]
196
+ assert synced == [(str(logs / ('2020-01.tar.xz.%d.partial' % fw.os.getpid())), True), (str(logs), True)]
197
197
  assert not (logs / '2020-01').exists()
198
198
 
199
199
 
200
+ def test_log_compressor_orders_sync_rename_sync_remove(tmp_path, monkeypatch):
201
+ # XFS does not flush a file's data on rename: the archive's data must be synced before it gets its final name.
202
+ logs = month_dirs(tmp_path, '2020-01')
203
+ events = []
204
+ real_fsync, real_replace, real_rmtree = fw.os.fsync, fw.os.replace, fw.shutil.rmtree
205
+ names = {}
206
+ real_open = fw.os.open
207
+
208
+ def opening(path, *args, **kwargs):
209
+ fd = real_open(path, *args, **kwargs)
210
+ names[fd] = path
211
+ return fd
212
+
213
+ def fsync(fd):
214
+ events.append(('fsync', names.get(fd)))
215
+ real_fsync(fd)
216
+
217
+ monkeypatch.setattr(fw.os, 'open', opening)
218
+ monkeypatch.setattr(fw.os, 'fsync', fsync)
219
+ monkeypatch.setattr(fw.os, 'replace', lambda a, b: events.append(('replace', a, b)) or real_replace(a, b))
220
+ monkeypatch.setattr(fw.shutil, 'rmtree', lambda path: events.append(('rmtree', path)) or real_rmtree(path))
221
+ fw.Log_Compressor(str(logs), compressAfterMonths=1, deleteLogAfterMonths=0)
222
+ partial = str(logs / ('2020-01.tar.xz.%d.partial' % fw.os.getpid()))
223
+ assert events == [
224
+ ('fsync', partial),
225
+ ('replace', partial, str(logs / '2020-01.tar.xz')),
226
+ ('fsync', str(logs)),
227
+ ('rmtree', str(logs / '2020-01')),
228
+ ]
229
+
230
+
231
+ def test_log_compressor_keeps_the_month_when_a_sync_fails(tmp_path, monkeypatch, capsys):
232
+ # Only the first sync (the data), then only the second (the directory), fail: the month stays both times.
233
+ for failing in (1, 2):
234
+ sub = tmp_path / str(failing)
235
+ sub.mkdir()
236
+ logs = month_dirs(sub, '2020-01')
237
+ calls = []
238
+ real = fw.os.fsync
239
+
240
+ def fsync(fd, failing=failing, calls=calls, real=real):
241
+ calls.append(fd)
242
+ if len(calls) == failing:
243
+ raise OSError(fw.errno.EIO, 'Input/output error')
244
+ real(fd)
245
+
246
+ monkeypatch.setattr(fw.os, 'fsync', fsync)
247
+ fw.Log_Compressor(str(logs), compressAfterMonths=1, deleteLogAfterMonths=0)
248
+ assert (logs / '2020-01' / 'x.log').read_text() == 'x'
249
+ assert 'failed' in capsys.readouterr().out
250
+ if failing == 1:
251
+ # a later process has another pid and would never reuse the partial's name
252
+ assert not list(logs.glob('*.partial'))
253
+ assert not list(logs.glob('*.tar.xz'))
254
+
255
+
256
+ def test_log_compressor_removes_the_partial_when_the_rename_fails(tmp_path, monkeypatch, capsys):
257
+ logs = month_dirs(tmp_path, '2020-01')
258
+
259
+ def failing_replace(src, dst):
260
+ raise OSError(fw.errno.EIO, 'Input/output error')
261
+
262
+ monkeypatch.setattr(fw.os, 'replace', failing_replace)
263
+ fw.Log_Compressor(str(logs), compressAfterMonths=1, deleteLogAfterMonths=0)
264
+ assert sorted(p.name for p in logs.iterdir()) == ['2020-01']
265
+ assert (logs / '2020-01' / 'x.log').read_text() == 'x'
266
+
267
+
200
268
  def test_fsync_path_tolerates_filesystems_without_fsync(tmp_path, monkeypatch):
201
269
  def unsupported(fd):
202
270
  raise OSError(fw.errno.EINVAL, 'Invalid argument')
@@ -10,7 +10,7 @@ import time
10
10
  import pytest
11
11
 
12
12
  import firewatcher as fw
13
- from conftest import ROOT, ScriptedPopen, fake_exists, incident_logs, parse_cli, patch_popen, use_journal
13
+ from conftest import ROOT, Clock, ScriptedPopen, fake_exists, incident_logs, parse_cli, patch_popen, use_journal
14
14
 
15
15
  # --- resuming the journal after a restart ---
16
16
 
@@ -178,6 +178,68 @@ def test_saw_saves_once_per_interval_and_round_trips(tmp_path):
178
178
  assert replay(again, [jline(0, 'a'), jline(0, 'b'), jline(0, 'c'), jline(1, 'd'), jline(1, 'e')]) == ['old'] * 4 + ['new']
179
179
 
180
180
 
181
+ def test_every_save_syncs_the_file_before_the_rename(tmp_path, monkeypatch):
182
+ # XFS does not flush a file's data when it is renamed over another; after a hard reset an unsynced
183
+ # position could come back empty. Even a periodic save (final=False) must sync first.
184
+ path = tmp_path / 'journal.position'
185
+ position = fw.JournalPosition(str(path), now=T)
186
+ events = []
187
+ real_fsync, real_replace = os.fsync, os.replace
188
+
189
+ def fsync(fd):
190
+ events.append('fsync')
191
+ real_fsync(fd)
192
+
193
+ def replace(a, b):
194
+ events.append('replace')
195
+ real_replace(a, b)
196
+
197
+ monkeypatch.setattr(fw.os, 'fsync', fsync)
198
+ monkeypatch.setattr(fw.os, 'replace', replace)
199
+ position.saw(jline(0, 'a'), 100.0)
200
+ position.saw(jline(0, 'b'), 100.5)
201
+ assert events == ['fsync', 'replace']
202
+ position.saw(jline(1, 'c'), 101.5)
203
+ assert events == ['fsync', 'replace'] * 2
204
+ position.changed = True
205
+ position.save(final=True)
206
+ assert events == ['fsync', 'replace'] * 3
207
+ assert json.loads(path.read_text())['line'] == 1
208
+
209
+
210
+ def test_save_survives_a_filesystem_without_fsync(tmp_path, monkeypatch):
211
+ def unsupported(fd):
212
+ raise OSError(fw.errno.EINVAL, 'Invalid argument')
213
+
214
+ monkeypatch.setattr(fw.os, 'fsync', unsupported)
215
+ path = tmp_path / 'journal.position'
216
+ position = fw.JournalPosition(str(path), now=T)
217
+ position.saw(jline(0, 'a'), 100.0)
218
+ position.save(100.0)
219
+ assert json.loads(path.read_text())['line'] == 1
220
+ assert not position.save_failed
221
+
222
+
223
+ def test_a_stop_inside_the_save_of_saw_does_not_take_back_the_line_before(tmp_path):
224
+ path = tmp_path / 'journal.position'
225
+ position = fw.JournalPosition(str(path), now=T)
226
+ position.saw(jline(0, 'A'), 100.0)
227
+ position.save(100.0)
228
+ position.saw(jline(1, 'B'), 100.5) # B is handled in full
229
+
230
+ def stop():
231
+ raise KeyboardInterrupt # where SIGTERM lands: in the capture or position fsync of this save
232
+
233
+ position.before_save = stop
234
+ with pytest.raises(KeyboardInterrupt):
235
+ position.saw(jline(2, 'C'), 101.5) # C is in flight
236
+ position.unsee() # what capture_messages does for the line in flight
237
+ position.before_save = None
238
+ position.save(final=True)
239
+ # B was handled, so the restart must not read it again
240
+ assert json.loads(path.read_text())['time'] == T + 1
241
+
242
+
181
243
  def test_save_without_a_new_line_writes_nothing(tmp_path):
182
244
  path = tmp_path / 'journal.position'
183
245
  position = fw.JournalPosition(str(path), now=T)
@@ -447,32 +509,105 @@ def test_a_line_that_crashes_the_loop_is_not_read_again(tmp_path, monkeypatch):
447
509
  assert json.loads((tmp_path / 'journal.position').read_text())['time'] == T + 1
448
510
 
449
511
 
450
- def test_a_quiet_journal_during_a_capture_still_saves_the_position(tmp_path, monkeypatch):
451
- monkeypatch.setattr(fw, 'CAPTURE_SYNC_INTERVAL', 0.05)
452
- path = tmp_path / 'journal.position'
453
- seen_while_quiet = []
454
-
512
+ def _quiet_after(lines, path, expected):
513
+ """A stdout that serves lines (a str, or a float to wait that many seconds first), then stays quiet, polling
514
+ for up to 5 s until the position file holds `expected` (its line count) before it ends; the polls are returned."""
455
515
  class QuietStdout:
456
516
  def __init__(self):
457
- self.lines = [jline(0, 'HIT one'), jline(0, 'HIT two')]
517
+ self.lines = list(lines)
518
+ self.seen = []
458
519
 
459
520
  def readline(self, size=-1):
460
- if self.lines:
461
- return self.lines.pop(0)
462
- time.sleep(0.5)
463
- seen_while_quiet.append(json.loads(path.read_text())['line'])
521
+ while self.lines:
522
+ item = self.lines.pop(0)
523
+ if isinstance(item, float):
524
+ time.sleep(item)
525
+ else:
526
+ return item
527
+ deadline = time.time() + 5
528
+ while time.time() < deadline:
529
+ try:
530
+ seen = json.loads(path.read_text())['line']
531
+ except (OSError, ValueError):
532
+ seen = None
533
+ self.seen.append(seen)
534
+ if seen == expected:
535
+ break
536
+ time.sleep(0.01)
464
537
  return ''
538
+ return QuietStdout()
539
+
465
540
 
541
+ def _run_quiet(tmp_path, monkeypatch, stdout):
542
+ monkeypatch.setattr(fw.os, 'fsync', lambda fd: None) # a slow disk must not decide this test
543
+ monkeypatch.setattr(fw, 'CAPTURE_SYNC_INTERVAL', 0.05)
544
+ monkeypatch.setattr(fw, 'POSITION_SAVE_INTERVAL', 0.05)
466
545
  popen = ScriptedPopen([])
467
- popen.stdout = QuietStdout()
546
+ popen.stdout = stdout
468
547
  patch_popen(monkeypatch, popen)
469
548
  pat = tmp_path / 'p.txt'
470
549
  pat.write_text('HIT\n')
471
550
  fw.capture_messages(['unused'], fw.load_patterns([str(pat)]), capture_time=60, output_folder=str(tmp_path / 'out'),
472
551
  compress_after_months=0, delete_after_months=0,
473
- journal_position=fw.JournalPosition(str(path), now=T))
552
+ journal_position=fw.JournalPosition(str(tmp_path / 'journal.position'), now=T))
553
+
554
+
555
+ def test_a_quiet_journal_during_a_capture_still_saves_the_position(tmp_path, monkeypatch):
556
+ path = tmp_path / 'journal.position'
557
+ stdout = _quiet_after([jline(0, 'HIT one'), jline(0, 'HIT two')], path, 2)
558
+ _run_quiet(tmp_path, monkeypatch, stdout)
474
559
  # 'HIT two' only extended the open capture, so no save came with it: the quiet wait saved it
475
- assert seen_while_quiet == [2]
560
+ assert stdout.seen[-1] == 2
561
+
562
+
563
+ def test_a_line_synced_on_commit_has_its_position_saved_while_the_journal_is_quiet(tmp_path, monkeypatch):
564
+ # The line is read after the capture's sync interval, so the commit syncs it and nothing is left pending:
565
+ # only the position's own deadline wakes the read.
566
+ path = tmp_path / 'journal.position'
567
+ stdout = _quiet_after([jline(0, 'HIT one'), 0.2, jline(0, 'HIT two')], path, 2)
568
+ _run_quiet(tmp_path, monkeypatch, stdout)
569
+ assert stdout.seen[-1] == 2
570
+
571
+
572
+ def test_a_position_save_never_covers_capture_lines_that_are_not_synced(tmp_path, monkeypatch):
573
+ clock = Clock(1_000_000.0)
574
+ monkeypatch.setattr(fw.time, 'time', clock.time)
575
+ monkeypatch.setattr(fw.os, 'fsync', lambda fd: None)
576
+ events = []
577
+ real_write, real_sync = fw.CaptureFile.write, fw.CaptureFile.sync
578
+
579
+ def write(self, text):
580
+ events.append('write')
581
+ return real_write(self, text)
582
+
583
+ def sync(self, now=None):
584
+ events.append('sync')
585
+ return real_sync(self, now)
586
+
587
+ monkeypatch.setattr(fw.CaptureFile, 'write', write)
588
+ monkeypatch.setattr(fw.CaptureFile, 'sync', sync)
589
+ unsynced_at_save = []
590
+
591
+ class Recording(fw.JournalPosition):
592
+ def save(self, now=None, final=False):
593
+ covers = self.changed and not final
594
+ super().save(now, final)
595
+ if covers:
596
+ # a write after the last sync would be on disk only by luck when the position reaches it
597
+ tail = events[len(events) - events[::-1].index('sync'):] if 'sync' in events else events
598
+ unsynced_at_save.append('write' in tail)
599
+
600
+ # The capture opens at t, 'a' and 'b' are written within the sync interval, and 'c' comes after the
601
+ # position's interval: its saw() saves a and b, which the capture has not synced yet.
602
+ popen = ScriptedPopen([(jline(0, 'HIT'), 0), (jline(0, 'a'), 0.25), (jline(0, 'b'), 0.25), (jline(1, 'c'), 0.75), (jline(1, 'd'), 0)], clock=clock)
603
+ patch_popen(monkeypatch, popen)
604
+ pat = tmp_path / 'p.txt'
605
+ pat.write_text('HIT\n')
606
+ fw.capture_messages(['unused'], fw.load_patterns([str(pat)]), capture_time=600, output_folder=str(tmp_path / 'out'),
607
+ compress_after_months=0, delete_after_months=0,
608
+ journal_position=Recording(str(tmp_path / 'journal.position'), now=T))
609
+ assert len(unsynced_at_save) >= 2
610
+ assert not any(unsynced_at_save)
476
611
 
477
612
 
478
613
  def test_a_carriage_return_fragment_that_looks_like_a_stamp_is_harmless(tmp_path, monkeypatch):
File without changes
File without changes
File without changes
File without changes
File without changes