firewatcher 1.65__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.65 → firewatcher-1.67}/MANIFEST.in +1 -0
  2. {firewatcher-1.65/firewatcher.egg-info → firewatcher-1.67}/PKG-INFO +7 -6
  3. {firewatcher-1.65 → firewatcher-1.67}/README.md +6 -5
  4. firewatcher-1.67/docs/lessons-full.md +37 -0
  5. firewatcher-1.67/docs/lessons.md +13 -0
  6. firewatcher-1.67/docs/limitations.md +40 -0
  7. {firewatcher-1.65 → firewatcher-1.67/firewatcher.egg-info}/PKG-INFO +7 -6
  8. {firewatcher-1.65 → firewatcher-1.67}/firewatcher.egg-info/SOURCES.txt +4 -0
  9. {firewatcher-1.65 → firewatcher-1.67}/firewatcher.py +109 -22
  10. {firewatcher-1.65 → firewatcher-1.67}/tests/test_cli.py +1 -1
  11. {firewatcher-1.65 → firewatcher-1.67}/tests/test_compressor.py +70 -2
  12. {firewatcher-1.65 → firewatcher-1.67}/tests/test_notify.py +19 -19
  13. {firewatcher-1.65 → firewatcher-1.67}/tests/test_position.py +159 -18
  14. firewatcher-1.67/tests/test_redirects.py +163 -0
  15. {firewatcher-1.65 → firewatcher-1.67}/LICENSE +0 -0
  16. {firewatcher-1.65 → firewatcher-1.67}/examples/firewatcher.conf +0 -0
  17. {firewatcher-1.65 → firewatcher-1.67}/examples/nvme_failure.regex +0 -0
  18. {firewatcher-1.65 → firewatcher-1.67}/examples/sys_msg.txt +0 -0
  19. {firewatcher-1.65 → firewatcher-1.67}/firewatcher.egg-info/dependency_links.txt +0 -0
  20. {firewatcher-1.65 → firewatcher-1.67}/firewatcher.egg-info/entry_points.txt +0 -0
  21. {firewatcher-1.65 → firewatcher-1.67}/firewatcher.egg-info/top_level.txt +0 -0
  22. {firewatcher-1.65 → firewatcher-1.67}/setup.cfg +0 -0
  23. {firewatcher-1.65 → firewatcher-1.67}/setup.py +0 -0
  24. {firewatcher-1.65 → firewatcher-1.67}/tests/conftest.py +0 -0
  25. {firewatcher-1.65 → firewatcher-1.67}/tests/test_capture.py +0 -0
  26. {firewatcher-1.65 → firewatcher-1.67}/tests/test_config.py +0 -0
  27. {firewatcher-1.65 → firewatcher-1.67}/tests/test_events.py +0 -0
  28. {firewatcher-1.65 → firewatcher-1.67}/tests/test_log_source.py +0 -0
  29. {firewatcher-1.65 → firewatcher-1.67}/tests/test_matching.py +0 -0
  30. {firewatcher-1.65 → firewatcher-1.67}/tests/test_patterns.py +0 -0
  31. {firewatcher-1.65 → firewatcher-1.67}/tests/test_slugify.py +0 -0
  32. {firewatcher-1.65 → firewatcher-1.67}/tests/test_systemd.py +0 -0
@@ -1,4 +1,5 @@
1
1
  include LICENSE
2
2
  include README.md
3
3
  include examples/*
4
+ include docs/*.md
4
5
  recursive-include tests *.py
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: firewatcher
3
- Version: 1.65
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
 
@@ -131,7 +131,7 @@ Useful flags:
131
131
  | Flag | Description |
132
132
  |------|-------------|
133
133
  | `--unit-name NAME` | Unit name (default: `firewatcher`) |
134
- | `--requires-mounts-for PATH` | Add `RequiresMountsFor=` (repeat for NFS/remote output). Each path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`; symlinks are not followed, as systemd follows none), quoted for you when it has spaces, quotes or backslashes, and refused if it has a newline or is not UTF-8 (systemd cannot read either back there). On systemd 229 and older (EL7), a path with `%`, `"` or `\` is read as a different path ([limitations](docs/limitations.md#on-systemd-229-and-older-some-mount-paths-are-written-wrong)) |
134
+ | `--requires-mounts-for PATH` | Add `RequiresMountsFor=` (repeat for NFS/remote output). Each path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`; symlinks are not followed, as systemd follows none), quoted for you when it has spaces, quotes or backslashes, and refused if it has a newline or is not UTF-8 (systemd cannot read either back there). On systemd 229 and older (EL7), a path with `%`, `"` or `\` is read as a different path ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#on-systemd-229-and-older-some-mount-paths-are-written-wrong)) |
135
135
  | `--no-enable` | Write the unit and reload, but do not enable or start it |
136
136
 
137
137
  ```bash
@@ -183,7 +183,7 @@ sudo firewatcher --install-service -o /mnt/logs/captured_messages \
183
183
 
184
184
  Runtime settings live in an INI file. Explicit command-line flags override the file. Built-in defaults apply when neither sets a value. A missing default file is ignored. `--uninstall-service` does not read the file.
185
185
 
186
- A commented example with all supported settings is in [`examples/firewatcher.conf`](examples/firewatcher.conf). Copy it to `/etc/firewatcher/firewatcher.conf`, or use `firewatcher --config /path/to/firewatcher.conf`.
186
+ A commented example with all supported settings is in [`examples/firewatcher.conf`](https://github.com/yufei-pan/firewatcher/blob/master/examples/firewatcher.conf). Copy it to `/etc/firewatcher/firewatcher.conf`, or use `firewatcher --config /path/to/firewatcher.conf`.
187
187
 
188
188
  ```ini
189
189
  [watch]
@@ -214,7 +214,7 @@ always_notify =
214
214
 
215
215
  `patterns` and `always_notify` are one path per line, or comma-separated. Positional pattern arguments replace the `patterns` list.
216
216
 
217
- Out-of-range values stop `firewatcher` at startup: a negative time or count, `capture_time` over 7 days or `capture_time_max` over 30 days, `min_free_percent` outside 0–50, `purge_interval` or `resume_max` over 30 days, `buffer_max_mb` below 1, a timeout of 0 or less or over a day, an ntfy priority outside 1–5, or an LLM, ntfy or events URL that does not start with `http://` or `https://` or that contains spaces, or whose server part (after any `user:password@`) is not a host name with no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%` in it, or an IPv6 address in brackets, then an optional `:port` of up to 5 digits (0–65535); so a `user:password` holding a `/`, `?` or `#` is refused (`[` and `]` are fine there, since the `user:password` is stripped before the request). Also refused is a URL with a `user:password` that has another `@` later in its path, query or fragment (a password holding an `@` before a `/`, `?` or `#`). A password that starts with digits and a `/` still reads as a host and port, and those digits show as the port in logs ([limitations](docs/limitations.md#a-url-whose-password-starts-with-digits-and-a--shows-those-digits-as-the-port)).
217
+ Out-of-range values stop `firewatcher` at startup: a negative time or count, `capture_time` over 7 days or `capture_time_max` over 30 days, `min_free_percent` outside 0–50, `purge_interval` or `resume_max` over 30 days, `buffer_max_mb` below 1, a timeout of 0 or less or over a day, an ntfy priority outside 1–5, or an LLM, ntfy or events URL that does not start with `http://` or `https://` or that contains spaces, or whose server part (after any `user:password@`) is not a host name with no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%` in it, or an IPv6 address in brackets, then an optional `:port` of up to 5 digits (0–65535); so a `user:password` holding a `/`, `?` or `#` is refused (`[` and `]` are fine there, since the `user:password` is stripped before the request). Also refused is a URL with a `user:password` that has another `@` later in its path, query or fragment (a password holding an `@` before a `/`, `?` or `#`). A password that starts with digits and a `/` still reads as a host and port, and those digits show as the port in logs ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#a-url-whose-password-starts-with-digits-and-a--shows-those-digits-as-the-port)).
218
218
 
219
219
  `api_key` under `[llm]` and `token` under `[notify]` are not command-line flags. `FIREWATCHER_LLM_API_KEY` and `FIREWATCHER_NTFY_TOKEN` override them when set. `events_token` under `[notify]` is likewise config-only, overridden by `FIREWATCHER_EVENTS_TOKEN`. `--install-service` creates `/etc/firewatcher/firewatcher.conf` with mode `0600` only when it is missing, and the unit runs `firewatcher --config` that path. An existing file is left as it is. Flags passed to a later install are appended on `ExecStart` so they override the file.
220
220
 
@@ -229,6 +229,7 @@ Both features default off.
229
229
  - Both on: a push is sent only when the model sets `notify` to true.
230
230
  - With `[notify] events_url` set, the events service judges instead and firewatcher's LLM is off; see [Sending captures to an events service](#sending-captures-to-an-events-service).
231
231
  - If the LLM request times out, returns an HTTP error, or is not the expected JSON, and notifications are on, firewatcher still pushes, using the generated title.
232
+ - No request firewatcher makes (the LLM, ntfy or the events service) follows a redirect: a 3xx answer is a failure, logged as `HTTP 301 from <server> (redirect, not followed)` with only the server, so the request and its token never go on to another host. A failed ntfy push is logged as `ntfy failed`; a failed LLM request falls back as above.
232
233
 
233
234
  The capture window closes even when no further log lines arrive. Analysis runs on a background worker so log following stays live. The queue holds four captures. When the queue is full, that incident skips the model and, if notifications are on, the capture thread sends the generated-title push itself.
234
235
 
@@ -259,7 +260,7 @@ The receiver judges. With `events_url` set, firewatcher's own LLM analysis is of
259
260
  | `path` | the capture file, or `null` when it could not be saved |
260
261
  | `time` | when the event was sent (ISO 8601 with the UTC offset): after the capture window, not when the line matched |
261
262
 
262
- Captures are posted whatever `push` says, so the service sees them all. Any 2xx answer means the service has the capture, and then nothing goes to ntfy. Anything else (a refused connection, a timeout, a TLS error, a redirect, a 4xx or 5xx) is logged as `event post failed`, and then only `always_notify` captures are pushed to ntfy (when notifications are on), with the generated title and the line that matched. Other captures stay in the capture folder and the journal (`event post failed: ...; not pushed (not always_notify)`). While the service does not answer, each push goes out one timeout late ([limitations](docs/limitations.md#while-the-events-receiver-is-down-each-alert-waits-one-timeout-before-ntfy)). `events_url` also works without `[notify] enabled`; a failed POST then only logs. Like the ntfy topic, the URL is shown only as its server, and the token is never logged. A `user:password` in a URL (events, ntfy or LLM) is not sent: use `events_token` (`token` under `[notify]` for ntfy, `api_key` under `[llm]` for the model).
263
+ Captures are posted whatever `push` says, so the service sees them all. Any 2xx answer means the service has the capture, and then nothing goes to ntfy. Anything else (a refused connection, a timeout, a TLS error, a redirect, a 4xx or 5xx) is logged as `event post failed`, and then only `always_notify` captures are pushed to ntfy (when notifications are on), with the generated title and the line that matched. Other captures stay in the capture folder and the journal (`event post failed: ...; not pushed (not always_notify)`). While the service does not answer, each push goes out one timeout late ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#while-the-events-receiver-is-down-each-alert-waits-one-timeout-before-ntfy)). `events_url` also works without `[notify] enabled`; a failed POST then only logs. Like the ntfy topic, the URL is shown only as its server, and the token is never logged. A `user:password` in a URL (events, ntfy or LLM) is not sent: use `events_token` (`token` under `[notify]` for ntfy, `api_key` under `[llm]` for the model). firewatcher warns at startup when one is there, naming the setting (`Warning: notify.ntfy_url holds a user:password, ...`) but never its value.
263
264
 
264
265
  Lines firewatcher writes back to the journal are a single physical line containing `firewatcher-self`, so a summary that quotes `panic` or `I/O error` does not start another capture. In journalctl and syslog output, firewatcher recognizes its own lines by the identifier field after the timestamp and host (`firewatcher[PID]:`), not by text elsewhere in the line, so a process or user name chosen to look like firewatcher cannot hide a kernel or daemon message. Lines in other formats are checked for `firewatcher-self` or `firewatcher[PID]:` anywhere. The capture files themselves stay in the log stream's original format.
265
266
 
@@ -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
 
@@ -104,7 +104,7 @@ Useful flags:
104
104
  | Flag | Description |
105
105
  |------|-------------|
106
106
  | `--unit-name NAME` | Unit name (default: `firewatcher`) |
107
- | `--requires-mounts-for PATH` | Add `RequiresMountsFor=` (repeat for NFS/remote output). Each path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`; symlinks are not followed, as systemd follows none), quoted for you when it has spaces, quotes or backslashes, and refused if it has a newline or is not UTF-8 (systemd cannot read either back there). On systemd 229 and older (EL7), a path with `%`, `"` or `\` is read as a different path ([limitations](docs/limitations.md#on-systemd-229-and-older-some-mount-paths-are-written-wrong)) |
107
+ | `--requires-mounts-for PATH` | Add `RequiresMountsFor=` (repeat for NFS/remote output). Each path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`; symlinks are not followed, as systemd follows none), quoted for you when it has spaces, quotes or backslashes, and refused if it has a newline or is not UTF-8 (systemd cannot read either back there). On systemd 229 and older (EL7), a path with `%`, `"` or `\` is read as a different path ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#on-systemd-229-and-older-some-mount-paths-are-written-wrong)) |
108
108
  | `--no-enable` | Write the unit and reload, but do not enable or start it |
109
109
 
110
110
  ```bash
@@ -156,7 +156,7 @@ sudo firewatcher --install-service -o /mnt/logs/captured_messages \
156
156
 
157
157
  Runtime settings live in an INI file. Explicit command-line flags override the file. Built-in defaults apply when neither sets a value. A missing default file is ignored. `--uninstall-service` does not read the file.
158
158
 
159
- A commented example with all supported settings is in [`examples/firewatcher.conf`](examples/firewatcher.conf). Copy it to `/etc/firewatcher/firewatcher.conf`, or use `firewatcher --config /path/to/firewatcher.conf`.
159
+ A commented example with all supported settings is in [`examples/firewatcher.conf`](https://github.com/yufei-pan/firewatcher/blob/master/examples/firewatcher.conf). Copy it to `/etc/firewatcher/firewatcher.conf`, or use `firewatcher --config /path/to/firewatcher.conf`.
160
160
 
161
161
  ```ini
162
162
  [watch]
@@ -187,7 +187,7 @@ always_notify =
187
187
 
188
188
  `patterns` and `always_notify` are one path per line, or comma-separated. Positional pattern arguments replace the `patterns` list.
189
189
 
190
- Out-of-range values stop `firewatcher` at startup: a negative time or count, `capture_time` over 7 days or `capture_time_max` over 30 days, `min_free_percent` outside 0–50, `purge_interval` or `resume_max` over 30 days, `buffer_max_mb` below 1, a timeout of 0 or less or over a day, an ntfy priority outside 1–5, or an LLM, ntfy or events URL that does not start with `http://` or `https://` or that contains spaces, or whose server part (after any `user:password@`) is not a host name with no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%` in it, or an IPv6 address in brackets, then an optional `:port` of up to 5 digits (0–65535); so a `user:password` holding a `/`, `?` or `#` is refused (`[` and `]` are fine there, since the `user:password` is stripped before the request). Also refused is a URL with a `user:password` that has another `@` later in its path, query or fragment (a password holding an `@` before a `/`, `?` or `#`). A password that starts with digits and a `/` still reads as a host and port, and those digits show as the port in logs ([limitations](docs/limitations.md#a-url-whose-password-starts-with-digits-and-a--shows-those-digits-as-the-port)).
190
+ Out-of-range values stop `firewatcher` at startup: a negative time or count, `capture_time` over 7 days or `capture_time_max` over 30 days, `min_free_percent` outside 0–50, `purge_interval` or `resume_max` over 30 days, `buffer_max_mb` below 1, a timeout of 0 or less or over a day, an ntfy priority outside 1–5, or an LLM, ntfy or events URL that does not start with `http://` or `https://` or that contains spaces, or whose server part (after any `user:password@`) is not a host name with no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%` in it, or an IPv6 address in brackets, then an optional `:port` of up to 5 digits (0–65535); so a `user:password` holding a `/`, `?` or `#` is refused (`[` and `]` are fine there, since the `user:password` is stripped before the request). Also refused is a URL with a `user:password` that has another `@` later in its path, query or fragment (a password holding an `@` before a `/`, `?` or `#`). A password that starts with digits and a `/` still reads as a host and port, and those digits show as the port in logs ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#a-url-whose-password-starts-with-digits-and-a--shows-those-digits-as-the-port)).
191
191
 
192
192
  `api_key` under `[llm]` and `token` under `[notify]` are not command-line flags. `FIREWATCHER_LLM_API_KEY` and `FIREWATCHER_NTFY_TOKEN` override them when set. `events_token` under `[notify]` is likewise config-only, overridden by `FIREWATCHER_EVENTS_TOKEN`. `--install-service` creates `/etc/firewatcher/firewatcher.conf` with mode `0600` only when it is missing, and the unit runs `firewatcher --config` that path. An existing file is left as it is. Flags passed to a later install are appended on `ExecStart` so they override the file.
193
193
 
@@ -202,6 +202,7 @@ Both features default off.
202
202
  - Both on: a push is sent only when the model sets `notify` to true.
203
203
  - With `[notify] events_url` set, the events service judges instead and firewatcher's LLM is off; see [Sending captures to an events service](#sending-captures-to-an-events-service).
204
204
  - If the LLM request times out, returns an HTTP error, or is not the expected JSON, and notifications are on, firewatcher still pushes, using the generated title.
205
+ - No request firewatcher makes (the LLM, ntfy or the events service) follows a redirect: a 3xx answer is a failure, logged as `HTTP 301 from <server> (redirect, not followed)` with only the server, so the request and its token never go on to another host. A failed ntfy push is logged as `ntfy failed`; a failed LLM request falls back as above.
205
206
 
206
207
  The capture window closes even when no further log lines arrive. Analysis runs on a background worker so log following stays live. The queue holds four captures. When the queue is full, that incident skips the model and, if notifications are on, the capture thread sends the generated-title push itself.
207
208
 
@@ -232,7 +233,7 @@ The receiver judges. With `events_url` set, firewatcher's own LLM analysis is of
232
233
  | `path` | the capture file, or `null` when it could not be saved |
233
234
  | `time` | when the event was sent (ISO 8601 with the UTC offset): after the capture window, not when the line matched |
234
235
 
235
- Captures are posted whatever `push` says, so the service sees them all. Any 2xx answer means the service has the capture, and then nothing goes to ntfy. Anything else (a refused connection, a timeout, a TLS error, a redirect, a 4xx or 5xx) is logged as `event post failed`, and then only `always_notify` captures are pushed to ntfy (when notifications are on), with the generated title and the line that matched. Other captures stay in the capture folder and the journal (`event post failed: ...; not pushed (not always_notify)`). While the service does not answer, each push goes out one timeout late ([limitations](docs/limitations.md#while-the-events-receiver-is-down-each-alert-waits-one-timeout-before-ntfy)). `events_url` also works without `[notify] enabled`; a failed POST then only logs. Like the ntfy topic, the URL is shown only as its server, and the token is never logged. A `user:password` in a URL (events, ntfy or LLM) is not sent: use `events_token` (`token` under `[notify]` for ntfy, `api_key` under `[llm]` for the model).
236
+ Captures are posted whatever `push` says, so the service sees them all. Any 2xx answer means the service has the capture, and then nothing goes to ntfy. Anything else (a refused connection, a timeout, a TLS error, a redirect, a 4xx or 5xx) is logged as `event post failed`, and then only `always_notify` captures are pushed to ntfy (when notifications are on), with the generated title and the line that matched. Other captures stay in the capture folder and the journal (`event post failed: ...; not pushed (not always_notify)`). While the service does not answer, each push goes out one timeout late ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#while-the-events-receiver-is-down-each-alert-waits-one-timeout-before-ntfy)). `events_url` also works without `[notify] enabled`; a failed POST then only logs. Like the ntfy topic, the URL is shown only as its server, and the token is never logged. A `user:password` in a URL (events, ntfy or LLM) is not sent: use `events_token` (`token` under `[notify]` for ntfy, `api_key` under `[llm]` for the model). firewatcher warns at startup when one is there, naming the setting (`Warning: notify.ntfy_url holds a user:password, ...`) but never its value.
236
237
 
237
238
  Lines firewatcher writes back to the journal are a single physical line containing `firewatcher-self`, so a summary that quotes `panic` or `I/O error` does not start another capture. In journalctl and syslog output, firewatcher recognizes its own lines by the identifier field after the timestamp and host (`firewatcher[PID]:`), not by text elsewhere in the line, so a process or user name chosen to look like firewatcher cannot hide a kernel or daemon message. Lines in other formats are checked for `firewatcher-self` or `firewatcher[PID]:` anywhere. The capture files themselves stay in the log stream's original format.
238
239
 
@@ -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.
@@ -0,0 +1,40 @@
1
+ # Limitations
2
+
3
+ Approved known limitations and deferrals. Reviewers: read this first, and don't raise these again.
4
+
5
+ ### On systemd 229 and older, some mount paths are written wrong
6
+ - Kind: known limitation
7
+ - What the operator sees: on systemd 229 and older (CentOS/RHEL 7's 219, Ubuntu 16.04's 229), a
8
+ `--requires-mounts-for` path holding `%`, `"` or `\` is written into `RequiresMountsFor=` in a form those
9
+ versions read as a different path: they keep 1.64's `%%` and its backslash escapes as they are. The unit then
10
+ does not wait for that mount. 1.63 wrote such a path unchanged, which those versions read correctly. Paths
11
+ with spaces work there too.
12
+ - Why: those versions neither expand `%` specifiers nor unescape in `RequiresMountsFor=` (systemd 219's
13
+ `config_parse_unit_requires_mounts_for` splits on whitespace and quotes, nothing more); newer ones (239 and
14
+ later) do both, and 1.64 writes for them. Writing per systemd version would mean detecting the version, for
15
+ an end-of-life systemd and a mount path that holds one of these three characters.
16
+ - Revisit when: someone runs firewatcher on such a systemd with such a mount path.
17
+ - Approved: 2026-11-01, the user chose "Known limitation (Recommended)".
18
+
19
+ ### While the events receiver is down, each alert waits one timeout before ntfy
20
+ - Kind: known limitation
21
+ - What the operator sees: with `events_url` set and its receiver not answering (the host down, its packets
22
+ dropped), each alert (only `always_notify` captures fall back to ntfy) is pushed one `ntfy_timeout` late (10 s by default; twice that for a capture that
23
+ overflows), because firewatcher tries the POST first and pushes to ntfy only when it fails. No alert is lost.
24
+ - Why: the POST and the push run one after the other. A separate short timeout, or skipping the POST for a while
25
+ after a failure, would shorten the wait at the cost of a second setting or of state; a few seconds' delay while
26
+ the receiver is down was judged acceptable.
27
+ - Revisit when: the delay matters in practice (a burst of alerts while the receiver is down).
28
+ - Approved: 2026-11-01, the user chose "Known limitation".
29
+
30
+ ### A URL whose password starts with digits and a `/` shows those digits as the port
31
+ - Kind: known limitation
32
+ - What the operator sees: in a URL such as `http://u:2024/<rest>@h/e` (a `user:password` whose password starts
33
+ with digits followed by `/`), the text up to the `/` is a valid host and port (`u`, port 2024), so firewatcher
34
+ accepts it and its log lines show `http://u:2024`: the leading digits of the password appear as the port, and the
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`). Because such a URL reads as a host and port, firewatcher gives it no user:password warning.
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
+ use. Credentials in a URL are never sent anyway (README: use `events_token`, `token` or `api_key`).
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". 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.65
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
 
@@ -131,7 +131,7 @@ Useful flags:
131
131
  | Flag | Description |
132
132
  |------|-------------|
133
133
  | `--unit-name NAME` | Unit name (default: `firewatcher`) |
134
- | `--requires-mounts-for PATH` | Add `RequiresMountsFor=` (repeat for NFS/remote output). Each path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`; symlinks are not followed, as systemd follows none), quoted for you when it has spaces, quotes or backslashes, and refused if it has a newline or is not UTF-8 (systemd cannot read either back there). On systemd 229 and older (EL7), a path with `%`, `"` or `\` is read as a different path ([limitations](docs/limitations.md#on-systemd-229-and-older-some-mount-paths-are-written-wrong)) |
134
+ | `--requires-mounts-for PATH` | Add `RequiresMountsFor=` (repeat for NFS/remote output). Each path is made absolute and normalized as text (`.`, `..`, `//`, a trailing `/`; symlinks are not followed, as systemd follows none), quoted for you when it has spaces, quotes or backslashes, and refused if it has a newline or is not UTF-8 (systemd cannot read either back there). On systemd 229 and older (EL7), a path with `%`, `"` or `\` is read as a different path ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#on-systemd-229-and-older-some-mount-paths-are-written-wrong)) |
135
135
  | `--no-enable` | Write the unit and reload, but do not enable or start it |
136
136
 
137
137
  ```bash
@@ -183,7 +183,7 @@ sudo firewatcher --install-service -o /mnt/logs/captured_messages \
183
183
 
184
184
  Runtime settings live in an INI file. Explicit command-line flags override the file. Built-in defaults apply when neither sets a value. A missing default file is ignored. `--uninstall-service` does not read the file.
185
185
 
186
- A commented example with all supported settings is in [`examples/firewatcher.conf`](examples/firewatcher.conf). Copy it to `/etc/firewatcher/firewatcher.conf`, or use `firewatcher --config /path/to/firewatcher.conf`.
186
+ A commented example with all supported settings is in [`examples/firewatcher.conf`](https://github.com/yufei-pan/firewatcher/blob/master/examples/firewatcher.conf). Copy it to `/etc/firewatcher/firewatcher.conf`, or use `firewatcher --config /path/to/firewatcher.conf`.
187
187
 
188
188
  ```ini
189
189
  [watch]
@@ -214,7 +214,7 @@ always_notify =
214
214
 
215
215
  `patterns` and `always_notify` are one path per line, or comma-separated. Positional pattern arguments replace the `patterns` list.
216
216
 
217
- Out-of-range values stop `firewatcher` at startup: a negative time or count, `capture_time` over 7 days or `capture_time_max` over 30 days, `min_free_percent` outside 0–50, `purge_interval` or `resume_max` over 30 days, `buffer_max_mb` below 1, a timeout of 0 or less or over a day, an ntfy priority outside 1–5, or an LLM, ntfy or events URL that does not start with `http://` or `https://` or that contains spaces, or whose server part (after any `user:password@`) is not a host name with no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%` in it, or an IPv6 address in brackets, then an optional `:port` of up to 5 digits (0–65535); so a `user:password` holding a `/`, `?` or `#` is refused (`[` and `]` are fine there, since the `user:password` is stripped before the request). Also refused is a URL with a `user:password` that has another `@` later in its path, query or fragment (a password holding an `@` before a `/`, `?` or `#`). A password that starts with digits and a `/` still reads as a host and port, and those digits show as the port in logs ([limitations](docs/limitations.md#a-url-whose-password-starts-with-digits-and-a--shows-those-digits-as-the-port)).
217
+ Out-of-range values stop `firewatcher` at startup: a negative time or count, `capture_time` over 7 days or `capture_time_max` over 30 days, `min_free_percent` outside 0–50, `purge_interval` or `resume_max` over 30 days, `buffer_max_mb` below 1, a timeout of 0 or less or over a day, an ntfy priority outside 1–5, or an LLM, ntfy or events URL that does not start with `http://` or `https://` or that contains spaces, or whose server part (after any `user:password@`) is not a host name with no `/`, `?`, `#`, `@`, `[`, `]`, `:` or `%` in it, or an IPv6 address in brackets, then an optional `:port` of up to 5 digits (0–65535); so a `user:password` holding a `/`, `?` or `#` is refused (`[` and `]` are fine there, since the `user:password` is stripped before the request). Also refused is a URL with a `user:password` that has another `@` later in its path, query or fragment (a password holding an `@` before a `/`, `?` or `#`). A password that starts with digits and a `/` still reads as a host and port, and those digits show as the port in logs ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#a-url-whose-password-starts-with-digits-and-a--shows-those-digits-as-the-port)).
218
218
 
219
219
  `api_key` under `[llm]` and `token` under `[notify]` are not command-line flags. `FIREWATCHER_LLM_API_KEY` and `FIREWATCHER_NTFY_TOKEN` override them when set. `events_token` under `[notify]` is likewise config-only, overridden by `FIREWATCHER_EVENTS_TOKEN`. `--install-service` creates `/etc/firewatcher/firewatcher.conf` with mode `0600` only when it is missing, and the unit runs `firewatcher --config` that path. An existing file is left as it is. Flags passed to a later install are appended on `ExecStart` so they override the file.
220
220
 
@@ -229,6 +229,7 @@ Both features default off.
229
229
  - Both on: a push is sent only when the model sets `notify` to true.
230
230
  - With `[notify] events_url` set, the events service judges instead and firewatcher's LLM is off; see [Sending captures to an events service](#sending-captures-to-an-events-service).
231
231
  - If the LLM request times out, returns an HTTP error, or is not the expected JSON, and notifications are on, firewatcher still pushes, using the generated title.
232
+ - No request firewatcher makes (the LLM, ntfy or the events service) follows a redirect: a 3xx answer is a failure, logged as `HTTP 301 from <server> (redirect, not followed)` with only the server, so the request and its token never go on to another host. A failed ntfy push is logged as `ntfy failed`; a failed LLM request falls back as above.
232
233
 
233
234
  The capture window closes even when no further log lines arrive. Analysis runs on a background worker so log following stays live. The queue holds four captures. When the queue is full, that incident skips the model and, if notifications are on, the capture thread sends the generated-title push itself.
234
235
 
@@ -259,7 +260,7 @@ The receiver judges. With `events_url` set, firewatcher's own LLM analysis is of
259
260
  | `path` | the capture file, or `null` when it could not be saved |
260
261
  | `time` | when the event was sent (ISO 8601 with the UTC offset): after the capture window, not when the line matched |
261
262
 
262
- Captures are posted whatever `push` says, so the service sees them all. Any 2xx answer means the service has the capture, and then nothing goes to ntfy. Anything else (a refused connection, a timeout, a TLS error, a redirect, a 4xx or 5xx) is logged as `event post failed`, and then only `always_notify` captures are pushed to ntfy (when notifications are on), with the generated title and the line that matched. Other captures stay in the capture folder and the journal (`event post failed: ...; not pushed (not always_notify)`). While the service does not answer, each push goes out one timeout late ([limitations](docs/limitations.md#while-the-events-receiver-is-down-each-alert-waits-one-timeout-before-ntfy)). `events_url` also works without `[notify] enabled`; a failed POST then only logs. Like the ntfy topic, the URL is shown only as its server, and the token is never logged. A `user:password` in a URL (events, ntfy or LLM) is not sent: use `events_token` (`token` under `[notify]` for ntfy, `api_key` under `[llm]` for the model).
263
+ Captures are posted whatever `push` says, so the service sees them all. Any 2xx answer means the service has the capture, and then nothing goes to ntfy. Anything else (a refused connection, a timeout, a TLS error, a redirect, a 4xx or 5xx) is logged as `event post failed`, and then only `always_notify` captures are pushed to ntfy (when notifications are on), with the generated title and the line that matched. Other captures stay in the capture folder and the journal (`event post failed: ...; not pushed (not always_notify)`). While the service does not answer, each push goes out one timeout late ([limitations](https://github.com/yufei-pan/firewatcher/blob/master/docs/limitations.md#while-the-events-receiver-is-down-each-alert-waits-one-timeout-before-ntfy)). `events_url` also works without `[notify] enabled`; a failed POST then only logs. Like the ntfy topic, the URL is shown only as its server, and the token is never logged. A `user:password` in a URL (events, ntfy or LLM) is not sent: use `events_token` (`token` under `[notify]` for ntfy, `api_key` under `[llm]` for the model). firewatcher warns at startup when one is there, naming the setting (`Warning: notify.ntfy_url holds a user:password, ...`) but never its value.
263
264
 
264
265
  Lines firewatcher writes back to the journal are a single physical line containing `firewatcher-self`, so a summary that quotes `panic` or `I/O error` does not start another capture. In journalctl and syslog output, firewatcher recognizes its own lines by the identifier field after the timestamp and host (`firewatcher[PID]:`), not by text elsewhere in the line, so a process or user name chosen to look like firewatcher cannot hide a kernel or daemon message. Lines in other formats are checked for `firewatcher-self` or `firewatcher[PID]:` anywhere. The capture files themselves stay in the log stream's original format.
265
266
 
@@ -3,6 +3,9 @@ MANIFEST.in
3
3
  README.md
4
4
  firewatcher.py
5
5
  setup.py
6
+ docs/lessons-full.md
7
+ docs/lessons.md
8
+ docs/limitations.md
6
9
  examples/firewatcher.conf
7
10
  examples/nvme_failure.regex
8
11
  examples/sys_msg.txt
@@ -22,5 +25,6 @@ tests/test_matching.py
22
25
  tests/test_notify.py
23
26
  tests/test_patterns.py
24
27
  tests/test_position.py
28
+ tests/test_redirects.py
25
29
  tests/test_slugify.py
26
30
  tests/test_systemd.py
@@ -31,7 +31,7 @@ import syslog
31
31
  import threading
32
32
  import zlib
33
33
 
34
- version = '1.65'
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
 
@@ -1067,6 +1085,23 @@ def _strip_userinfo(url):
1067
1085
  return url[:start] + url[at + 1:]
1068
1086
 
1069
1087
 
1088
+ def userinfo_warnings(settings):
1089
+ """A line for each URL setting that holds a user:password, naming the setting and never its value.
1090
+
1091
+ The user:password is not sent (see _strip_userinfo), so without this the mistake shows only as 401s when an
1092
+ incident fires."""
1093
+ rows = []
1094
+ for attr, label, instead in (
1095
+ ('llm_base_url', 'llm.base_url', 'api_key under [llm]'),
1096
+ ('ntfy_url', 'notify.ntfy_url', 'token under [notify]'),
1097
+ ('events_url', 'notify.events_url', 'events_token under [notify]'),
1098
+ ):
1099
+ url = getattr(settings, attr, '') or ''
1100
+ if url and _strip_userinfo(url) != str(url):
1101
+ rows.append('Warning: %s holds a user:password, which firewatcher does not send; use %s instead.' % (label, instead))
1102
+ return rows
1103
+
1104
+
1070
1105
  def _ini_patterns(paths):
1071
1106
  paths = list(paths or [])
1072
1107
  if not paths:
@@ -1310,15 +1345,41 @@ def _notify_body(text, path):
1310
1345
  return body.decode('utf-8', 'ignore') + suffix
1311
1346
 
1312
1347
 
1313
- def _urlopen_bytes(url, data, headers, timeout):
1348
+ def _open_url(request, timeout):
1349
+ """Open request without following redirects: a 3xx raises HTTPError, like a 4xx.
1350
+
1351
+ Every outgoing request goes through here. A followed 301 or 302 turns the POST into a GET, and urllib sends the
1352
+ Authorization header on to whatever host the Location names, while the answer still reads as success."""
1314
1353
  # Imported on first use: urllib.request pulls in ssl and http.client (about 9 MB RSS),
1315
- # and only LLM analysis and ntfy pushes need them.
1354
+ # and only the LLM, ntfy and the events service need them.
1355
+ import urllib.request
1356
+
1357
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
1358
+ def redirect_request(self, *args, **kwargs):
1359
+ return None
1360
+
1361
+ return urllib.request.build_opener(NoRedirect).open(request, timeout=timeout)
1362
+
1363
+
1364
+ def _http_error_reason(exc, url, detail=None):
1365
+ """'HTTP <code> from <origin>', then ': detail' when given; a 3xx says it was refused instead, without its body.
1366
+
1367
+ Never the Location: it is the server's, not ours to log."""
1368
+ reason = 'HTTP %s from %s' % (exc.code, _url_origin(url))
1369
+ if 300 <= exc.code < 400:
1370
+ return reason + ' (redirect, not followed)'
1371
+ if detail is not None:
1372
+ reason += ': ' + detail[:300]
1373
+ return reason
1374
+
1375
+
1376
+ def _urlopen_bytes(url, data, headers, timeout):
1316
1377
  import urllib.error
1317
1378
  import urllib.request
1318
1379
  url = _strip_userinfo(url)
1319
1380
  request = urllib.request.Request(url, data=data, headers=headers, method='POST')
1320
1381
  try:
1321
- with urllib.request.urlopen(request, timeout=timeout) as response:
1382
+ with _open_url(request, timeout) as response:
1322
1383
  return response.read()
1323
1384
  except urllib.error.HTTPError as exc:
1324
1385
  detail = ''
@@ -1326,7 +1387,7 @@ def _urlopen_bytes(url, data, headers, timeout):
1326
1387
  detail = exc.read().decode('utf-8', 'replace')
1327
1388
  except Exception:
1328
1389
  detail = ''
1329
- raise RuntimeError('HTTP %s from %s: %s' % (getattr(exc, 'code', '?'), _url_origin(url), detail[:300]))
1390
+ raise RuntimeError(_http_error_reason(exc, url, detail))
1330
1391
 
1331
1392
 
1332
1393
  def _parse_llm_object(content):
@@ -1533,20 +1594,16 @@ def post_event(url, token, payload, timeout):
1533
1594
  import urllib.error
1534
1595
  import urllib.request
1535
1596
 
1536
- class NoRedirect(urllib.request.HTTPRedirectHandler):
1537
- def redirect_request(self, *args, **kwargs):
1538
- return None
1539
-
1540
1597
  headers = {'Content-Type': 'application/json'}
1541
1598
  if token:
1542
1599
  headers['Authorization'] = 'Bearer ' + _http_header(token, 2000)
1543
1600
  request = urllib.request.Request(_strip_userinfo(url), data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST')
1544
1601
  try:
1545
1602
  # A 2xx status is the answer; the body is not read, so a stalled one cannot turn it into a failure.
1546
- with urllib.request.build_opener(NoRedirect).open(request, timeout=timeout):
1603
+ with _open_url(request, timeout):
1547
1604
  pass
1548
1605
  except urllib.error.HTTPError as exc:
1549
- raise RuntimeError('HTTP %s from %s' % (getattr(exc, 'code', '?'), _url_origin(url)))
1606
+ raise RuntimeError(_http_error_reason(exc, url))
1550
1607
  except Exception as exc:
1551
1608
  reason = str(getattr(exc, 'reason', None) or exc) or type(exc).__name__
1552
1609
  if token:
@@ -2163,6 +2220,15 @@ def capture_messages(command_to_run, patterns, capture_time=300, output_folder=D
2163
2220
  earlier = deque()
2164
2221
  written = None # the open capture's record
2165
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
+
2166
2232
  def end_capture(now):
2167
2233
  nonlocal capture, capture_until, capture_ends_by, captured_line_counter, written
2168
2234
  reached_max = capture_ends_by is not None and now >= capture_ends_by
@@ -2203,16 +2269,22 @@ def capture_messages(command_to_run, patterns, capture_time=300, output_folder=D
2203
2269
  sync_due = capture.sync_due() if capture else None
2204
2270
  if sync_due is not None and (deadline is None or sync_due < deadline):
2205
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
2206
2277
  remaining = None if deadline is None else max(0, deadline - time.time())
2207
2278
  line = pending_read.result(timeout=remaining)
2208
2279
  pending_read = None
2209
2280
  except ReadTimeout:
2210
2281
  if journal_position is not None:
2211
- # 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.
2212
2283
  journal_position.save()
2213
2284
  # Keep the same pending read while the source is quiet.
2214
2285
  if capture and capture_until is not None and time.time() < capture_until:
2215
- capture.sync()
2286
+ if capture.dirty:
2287
+ capture.sync()
2216
2288
  continue
2217
2289
  end_capture(time.time())
2218
2290
  continue
@@ -2787,6 +2859,8 @@ class JournalPosition(object):
2787
2859
  self.ordinal = 0
2788
2860
  self.changed = False
2789
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
2790
2864
  self.save_failed = False
2791
2865
  # The time of self.stamp, for the context: a line read long after it was logged keeps its own time.
2792
2866
  self.stamp_time = None
@@ -2860,6 +2934,9 @@ class JournalPosition(object):
2860
2934
  def saw(self, line, now):
2861
2935
  """Record a line as read, before it is handled. The periodic save (at most once per POSITION_SAVE_INTERVAL)
2862
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
2863
2940
  if self.changed and now >= self.next_save:
2864
2941
  self.save(now)
2865
2942
  self.before = (self.stamp, self.stamp_time, self.ordinal, self.last_line, self.last_end, self.changed)
@@ -2883,12 +2960,16 @@ class JournalPosition(object):
2883
2960
  self.before = None
2884
2961
 
2885
2962
  def save(self, now=None, final=False):
2886
- """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."""
2887
2966
  import json
2888
2967
  now = time.time() if now is None else now
2889
2968
  self.next_save = now + POSITION_SAVE_INTERVAL
2890
2969
  if not self.changed:
2891
2970
  return
2971
+ if self.before_save is not None:
2972
+ self.before_save()
2892
2973
  self.changed = False
2893
2974
  import tempfile
2894
2975
  record = {
@@ -2904,9 +2985,13 @@ class JournalPosition(object):
2904
2985
  fd, unfinished = tempfile.mkstemp(prefix=os.path.basename(self.path) + '.', suffix='.tmp', dir=folder)
2905
2986
  with os.fdopen(fd, 'w', encoding='utf-8') as f:
2906
2987
  f.write(json.dumps(record) + '\n')
2907
- if final:
2908
- f.flush()
2909
- 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())
2910
2995
  os.replace(unfinished, self.path)
2911
2996
  except OSError as exc:
2912
2997
  self.changed = True
@@ -3019,6 +3104,8 @@ def main(argv=None):
3019
3104
  resolved.pattern_file = [DEFAULT_PATTERNS_DIR]
3020
3105
  else:
3021
3106
  parser.error('pattern file or directory required (for example /etc/firewatcher/patterns.d)')
3107
+ for row in userinfo_warnings(resolved):
3108
+ print(row, file=sys.stderr)
3022
3109
  if args.print_unit:
3023
3110
  print(render_unit_file(resolved, raw=args), end='')
3024
3111
  return 0
@@ -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.65'
107
+ assert fw.version == '1.67'
108
108
  assert fw.__version__ == fw.version
109
109
 
110
110