Repository navigation
util: write JSON atomically in WriteJson - #35763
kevkevinpal wants to merge 2 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
|
Concept ACK Thanks for picking these up. cc: @sys-dev @ryanofsky |
|
ACK 07ec5af, with two non-blocking observations: The test is useful, but it also passes when CBanDB::Write is changed back to direct writing. Negative control proved this. It therefore does not verify the rename behavior named by the test. The generalized WriteJsonUnsafe helper still reports “settings file” errors when writing banlist.json.tmp. “JSON file” or “file” would be accurate for both callers. |
these need attention. so, i think they are blocking |
|
while going through this, another thought came to mind. right now i was wondering if it is worth making this a bit harder to misuse. two possible approaches came to mind approach A: add
|
07ec5af to
e524b77
Compare
e524b77 to
0e67947
Compare
|
@Herb-ops @winterrdog, can you review this again? |
winterrdog
left a comment
There was a problem hiding this comment.
approach ACK
now, we can update the PR title & description to match what the current code
actually does. they still mention WriteJsonUnsafe and callers doing the
atomic rename, while the current implementation is self-contained and handles
the "temp write + RenameOver()" itself
0e67947 to
0260a68
Compare
0260a68 to
ed55f14
Compare
winterrdog
left a comment
There was a problem hiding this comment.
tACK ed55f14
successfully built and tested on FreeBSD 15.0/clang++-19.1.7/x86_64. the changes herein LGTM as well
| for (const auto& value : values) { | ||
| out.pushKVEnd(value.first, value.second); | ||
| } | ||
| const fs::path path_tmp{path + ".tmp"}; |
There was a problem hiding this comment.
In commit "util: atomically write banlist.json and settings.json" (ed55f14)
This ended up different from what I suggested in #35384 (comment), and from an earlier version of this PR: keep WriteSettings a low-level function that writes the path it is given, rename it to make clear it is unsafe to use without RenameOver, and have callers do the rename. I still slightly prefer that, because I like functions that do one thing well, and once a write function also manages the temporary file it has to make choices for every caller (how the temporary file is named, whether to fsync) that some callers might want to make differently. But I don't see a problem with the current approach, and it is simpler for the two callers that exist now, so please go with whichever makes more sense to you.
There was a problem hiding this comment.
re: #35763 (comment)
once a write function also manages the temporary file it has to make choices for every caller
A small example of this is error messages. Because WriteSettings is now shared by two kinds of files, this PR changes its errors from "settings file" to "JSON file", which is less clear for settings.json. ReadSettings has the opposite problem: its parse error talks about a settings file and says removing it "will reset settings to default values", which is wrong for banlist.json (#35763 (comment)). This PR doesn't change ReadSettings, so it doesn't make that harder to fix, but in both cases the caller is what knows which file it is (CBanDB::Read already adds "Cannot load banlist" to the message) and what happens if it is removed. I think messages are easier to get right if low-level functions just read and write JSON and callers add the context as I originally suggested #35384 (comment). Still not a blocker for me.
|
@kevkevinpal do you want to take ryanofsky's suggestions? |
Yes, this completely slipped my mind. Will address it right now |
Before this change, CBanDB::Write() passed banlist.json directly to common::WriteSettings(), which truncates the file and then writes it. If the node crashed during the write, or the write failed because the disk was full, banlist.json could be left empty or partly written. On the next startup the ban list would fail to load and all bans would be dropped. settings.json did not have this problem, because ArgsManager::WriteSettingsFile() writes settings.json.tmp and renames it over settings.json. Write banlist.json the same way: write banlist.json.tmp and use RenameOver() to replace banlist.json. If writing banlist.json fails now, the previous banlist.json is kept and banlist.json.tmp is left behind, to be overwritten by the next write.
Both callers of common::WriteSettings(), ArgsManager::WriteSettingsFile() for settings.json and CBanDB::Write() for banlist.json, now write a .tmp file and use RenameOver() to replace the destination. Move that step into WriteSettings() itself, remove it from both callers, and drop the now unused temp parameter of ArgsManager::GetSettingsPath(). There is no behavior change, except that write errors for settings.json now say "JSON file" instead of "settings file".
ed55f14 to
9f2077d
Compare
winterrdog
left a comment
There was a problem hiding this comment.
reACK 9f2077d
successfully built and tested on FreeBSD 15.0/clang++-19.1.7/x86_64.
generally, the new changes bring in more clarity which is good for future maintenance
There was a problem hiding this comment.
Code review ACK 9f2077d. banlist.json is now written through a temporary file and RenameOver(), like settings.json, so a crash or full disk during the write can no longer leave it truncated.
Thanks for the updates and the clear commit messages. Remaining comments are minor and can be ignored: the PR title and description still describe the earlier WriteJson version (#35763 (comment)), the commits could be simpler, with a minimal fix in the first commit and no second commit (#35763 (comment)), and there is a possible follow-up about how a corrupt banlist.json is handled (#35763 (comment)).
| for (const auto& value : values) { | ||
| out.pushKVEnd(value.first, value.second); | ||
| } | ||
| const fs::path path_tmp{path + ".tmp"}; |
There was a problem hiding this comment.
re: #35763 (comment)
once a write function also manages the temporary file it has to make choices for every caller
A small example of this is error messages. Because WriteSettings is now shared by two kinds of files, this PR changes its errors from "settings file" to "JSON file", which is less clear for settings.json. ReadSettings has the opposite problem: its parse error talks about a settings file and says removing it "will reset settings to default values", which is wrong for banlist.json (#35763 (comment)). This PR doesn't change ReadSettings, so it doesn't make that harder to fix, but in both cases the caller is what knows which file it is (CBanDB::Read already adds "Cannot load banlist" to the message) and what happens if it is removed. I think messages are easier to get right if low-level functions just read and write JSON and callers add the context as I originally suggested #35384 (comment). Still not a blocker for me.
| errors.emplace_back(strprintf("Settings file %s does not contain valid JSON. This may be caused by a crash, power loss, full disk, or storage error, " | ||
| "and can be fixed by removing the file, which will reset settings to default values.", |
There was a problem hiding this comment.
In commit "refactor: move .tmp handling into common::WriteSettings" (9f2077d)
Note: not for this PR, but a possible follow-up. The PR makes a truncated banlist.json less likely, but the way the truncated file is handled still seems unsafe to me. A truncated settings.json fails to parse and is reported as an error at startup. A truncated banlist.json fails to parse the same way, but CBanDB::Read only logs a warning, and BanMan::LoadBanlist resets to an empty banlist, which the BanMan constructor immediately writes over the corrupt file. So the bans are lost, and the file that would show what happened is gone.
| bool CBanDB::Write(const banmap_t& banSet) | ||
| { | ||
| const fs::path banlist_tmp{m_banlist_json + ".tmp"}; | ||
| std::vector<std::string> errors; | ||
| if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { | ||
| return true; | ||
| if (!common::WriteSettings(banlist_tmp, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { | ||
| for (const auto& err : errors) { | ||
| LogError("%s\n", err); | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| for (const auto& err : errors) { | ||
| LogError("%s\n", err); | ||
| if (!RenameOver(banlist_tmp, m_banlist_json)) { | ||
| LogError("Failed renaming JSON file %s to %s\n", fs::PathToString(banlist_tmp), fs::PathToString(m_banlist_json)); | ||
| return false; | ||
| } | ||
| return false; | ||
| return true; | ||
| } |
There was a problem hiding this comment.
In commit "util: write banlist.json through a temporary file" (4a0f491)
The second commit reverts the changes this commit makes to CBanDB::Write, so across the PR addrdb.cpp doesn't change at all. That would seem more reasonable if the change being reverted were minimal, but this commit also restructures the function to return early on failure instead of on success, which the fix doesn't need.
Ideally I'd like to see (1) this commit reduced to a minimal bugfix without the restructuring, something like:
bool CBanDB::Write(const banmap_t& banSet)
{
+ const fs::path banlist_tmp{m_banlist_json + ".tmp"};
std::vector<std::string> errors;
- if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
- return true;
+ if (common::WriteSettings(banlist_tmp, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
+ if (RenameOver(banlist_tmp, m_banlist_json)) return true;
+ errors.emplace_back(strprintf("Failed renaming JSON file %s to %s", fs::PathToString(banlist_tmp), fs::PathToString(m_banlist_json)));
}and (2) the second commit dropped, which would also match the design I'd prefer (#35763 (comment)). But I'm also happy to see this merged as-is, or in any other form that fixes the bug.

Summary
Follow-up to #35384 (comment)
common::WriteSettingstocommon::WriteJson.WriteJsonwrites topath + ".tmp"andRenameOver()s into place, so a failed or interrupted write cannot leave a truncated destination. Bothsettings.jsonandbanlist.jsonuse this helper..tmpis gone after success, that rename failure is detected, and that a second failed write overwrites the same.tmprather than creating another.