fix(FileManager): SD log pruning caused stack-canary panic on MQTT connect task
Confirmed on hardware: enabling SD logging at INFO level caused a boot loop within seconds — "Guru Meditation Error... Stack canary watchpoint triggered (mqttConnect)". appendLogLine() was running pruneLogDirectory() (a full SD.open() directory scan + std::vector<pair<String,size_t>> build) on every single log write, and the first write happened to land on MQTTDriver's 3KB-stack connect task. Fixes: - Prune check now throttled to once per 50 writes instead of every write — removes the expensive directory scan from the hot logging path entirely. - Bumped mqttConnect/mqttRecon/mqttHB task stacks from 3072 to 4096 bytes as defense-in-depth, since these tasks can still trigger SD log writes. - Removed a LOG_INFO call inside pruneLogDirectory that could have re-entered Logging::writeToSd() from within the SD write path itself.
This commit is contained in:
@@ -622,9 +622,11 @@ Fixes a bug where SD logging was a silent no-op: `FileManager::appendLine` never
|
||||
New `FileManager::appendLogLine(logDir, line, timestamp, maxTotalBytes)` replaces the direct `appendLine` call as the SD log channel's write path:
|
||||
- Ensures `logDir` exists before every write.
|
||||
- Names the file `YYYY-MM-DD.log` from the supplied timestamp (`time(nullptr)`, works with or without an RTC once NTP has synced). Falls back to `unset-date.log` if no wall clock is available yet, rather than dropping early-boot lines.
|
||||
- Prunes oldest whole files once the directory exceeds a 512KB total budget (`SD_LOG_MAX_TOTAL_BYTES` in `CommunicationRouter.cpp`).
|
||||
- Every 50 writes (not every write), sums directory size and prunes oldest whole files once over a 512KB total budget (`SD_LOG_MAX_TOTAL_BYTES` in `CommunicationRouter.cpp`).
|
||||
|
||||
Subsystems: `src/FileManager/FileManager.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`
|
||||
**Fixed after initial testing:** the first version pruned on every write, which does a full `SD.open()` directory scan + `std::vector` build on the calling task's own stack. The first device test (SD log level set to INFO) hit this from `MQTTDriver`'s 3KB-stack connect task and panicked with a stack canary trigger, causing a reboot loop. Fixed by throttling the prune check to once per 50 writes and bumping the three MQTT driver task stacks (connect/reconnect/heartbeat) from 3072 to 4096 bytes.
|
||||
|
||||
Subsystems: `src/FileManager/FileManager.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp`
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -345,7 +345,7 @@ void MQTTDriver::mqttReconnectTaskFn(void* param) {
|
||||
|
||||
void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTDriver::_instance) {
|
||||
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTDriver::_instance, 5, NULL);
|
||||
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 4096, MQTTDriver::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,7 +445,7 @@ void MQTTDriver::heartbeatTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTDriver::_instance->_heartbeatTaskHandle != nullptr) {
|
||||
return;
|
||||
}
|
||||
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTDriver::_instance, 3,
|
||||
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 4096, MQTTDriver::_instance, 3,
|
||||
&MQTTDriver::_instance->_heartbeatTaskHandle);
|
||||
}
|
||||
}
|
||||
@@ -469,7 +469,7 @@ void MQTTDriver::mqttConnectTaskFn(void* param) {
|
||||
void MQTTDriver::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTDriver::_instance) {
|
||||
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
|
||||
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, MQTTDriver::_instance, 5, NULL);
|
||||
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 4096, MQTTDriver::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -355,9 +355,16 @@ bool FileManager::appendLogLine(const String& logDir, const String& line, time_t
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pruning does a full directory scan — too expensive (stack and I/O) to
|
||||
// run on every write. Check periodically instead; a day-rotated file
|
||||
// growing past budget between checks is fine, the next check catches it.
|
||||
if (maxTotalBytes > 0) {
|
||||
logWriteCountSinceProbe++;
|
||||
if (logWriteCountSinceProbe >= LOG_PRUNE_CHECK_INTERVAL) {
|
||||
logWriteCountSinceProbe = 0;
|
||||
pruneLogDirectory(logDir, maxTotalBytes);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -413,7 +420,11 @@ void FileManager::pruneLogDirectory(const String& logDir, size_t maxTotalBytes)
|
||||
|
||||
String fullPath = dirPath + name;
|
||||
if (SD.remove(fullPath.c_str())) {
|
||||
LOG_INFO(TAG, "Log rotation: removed oldest log file %s (%u bytes)", fullPath.c_str(), (unsigned)entry.second);
|
||||
// Deliberately not logged: this runs from inside the SD log write
|
||||
// path itself (appendLogLine -> pruneLogDirectory), and LOG_* here
|
||||
// would re-enter Logging::writeToSd() if FileManager's SD level is
|
||||
// enabled. Serial-only would be safe but adds complexity for a
|
||||
// rotation event that isn't actionable at runtime.
|
||||
totalBytes -= entry.second;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,13 @@ private:
|
||||
bool ensureDirectoryExists(const String& dirPath);
|
||||
String logFileNameForTimestamp(time_t timestamp) const;
|
||||
void pruneLogDirectory(const String& logDir, size_t maxTotalBytes);
|
||||
|
||||
// pruneLogDirectory() does a full directory scan (SD.open + iterate every
|
||||
// file) — too expensive to run on every single log line, and the calling
|
||||
// task's stack may not have room for it (e.g. the 3KB MQTT connect task).
|
||||
// Only check every LOG_PRUNE_CHECK_INTERVAL writes.
|
||||
static constexpr uint16_t LOG_PRUNE_CHECK_INTERVAL = 50;
|
||||
uint16_t logWriteCountSinceProbe = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -94,7 +94,11 @@ Prior to this feature, `appendLine` was called directly with a single hardcoded
|
||||
|
||||
1. Calls `ensureDirectoryExists(logDir)` before every write.
|
||||
2. Names the file `YYYY-MM-DD.log` (UTC, derived from the `timestamp` argument via `gmtime_r`). If `timestamp <= 0` — no RTC and NTP hasn't synced yet — lines are bucketed into `unset-date.log` rather than being lost.
|
||||
3. After each write, if `maxTotalBytes > 0`, sums the size of every file in `logDir` and, if over budget, deletes whole files oldest-filename-first (lexicographic sort on `YYYY-MM-DD.log` sorts chronologically) until back under budget.
|
||||
3. Every `LOG_PRUNE_CHECK_INTERVAL` (50) writes, if `maxTotalBytes > 0`, sums the size of every file in `logDir` and, if over budget, deletes whole files oldest-filename-first (lexicographic sort on `YYYY-MM-DD.log` sorts chronologically) until back under budget.
|
||||
|
||||
**Pruning is throttled, not run on every write.** The prune check does a full `SD.open()` directory scan and builds a `std::vector` of every file's name and size — real stack and I/O cost. Running it on every single log line was the original implementation and caused a stack-canary panic in `MQTTDriver`'s 3KB-stack connect task the first time SD logging was enabled at INFO level (the scan pushed that task's stack usage over its limit). It's now checked once every 50 writes instead — a day's file can grow up to ~50 lines past budget between checks, which is an acceptable trade for not doing directory I/O on every log call. The three MQTT driver tasks that can trigger a log write (`mqttConnect`, `mqttRecon`, `mqttHB`) were also bumped from 3072 to 4096 bytes as defense-in-depth.
|
||||
|
||||
**No logging from inside `pruneLogDirectory`.** Deleting a file during pruning is deliberately not logged — this code runs from inside the SD log write path itself (`appendLogLine` → `pruneLogDirectory`), and a `LOG_*` call here would attempt to re-enter `Logging::writeToSd()`. The `isWriting` re-entrancy guard in `Logging` would silently drop that inner call rather than infinite-loop, but it's simpler to just not log here.
|
||||
|
||||
The caller (`CommunicationRouter::setFileManagerReference`) supplies `time(nullptr)` as the timestamp — this works regardless of `HAS_RTC`, since `configTime()`/NTP sync (in `Timekeeper::syncTimeWithNTP()`) sets the ESP32's system clock independently of any RTC peripheral. Before NTP has synced, `time(nullptr)` returns a small epoch value, which is treated as "no wall clock" and routed to `unset-date.log`.
|
||||
|
||||
|
||||
@@ -167,7 +167,7 @@ Command example:
|
||||
|
||||
**MQTT feedback loop.** Any subsystem whose logs are emitted on the MQTT channel must not call `Logging` from within the MQTT publish path. `MQTTClient` and `CommRouter` are silenced on MQTT by default for this reason. The `isPublishing` guard is a secondary safeguard.
|
||||
|
||||
**SD writes are synchronous.** `setSdWriteCallback` delegates to `FileManager::appendLine`, which acquires the SD card mutex. Calling `LOG_*` at high frequency with SD enabled can stall the calling task for the duration of the SD write.
|
||||
**SD writes are synchronous, on whatever task logged.** `setSdWriteCallback` delegates to `FileManager::appendLogLine`, which runs on the calling task's own stack — there is no dedicated logging task. Calling `LOG_*` at high frequency with SD enabled stalls the calling task for the duration of the write, and every 50th write additionally does a full `/logs` directory scan (see [FileManager's log rotation notes](../FileManager/README.md#log-file-rotation)). Tasks with small stacks that may log at an SD-enabled level need enough headroom for this — the MQTT driver's connect/reconnect/heartbeat tasks were bumped to 4096 bytes after a stack-canary panic surfaced this.
|
||||
|
||||
**`isLevelEnabled` checks Serial only.** If you need to guard an expensive log-string build (e.g. formatting a large buffer before calling `LOG_DEBUG`), use `Logging::isLevelEnabled(Logging::DEBUG)`. Be aware this ignores MQTT and SD levels.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user