Skip to content
This repository was archived by the owner on Apr 27, 2026. It is now read-only.

Commit 6f6b26a

Browse files
authored
fix: update OCPP 1.6 configuration via a separate file (#1113)
If there is a crash or power outage while writing a file it can be left in a corrupt state. Updates are instead written to a new file and once complete the new file is renamed to replace the original file. This reduces the window where a file update could be lost and reduces the chance that a file is corrupted. Using a journalling file system can also help. Signed-off-by: James Chapman <james.chapman@pionix.de>
1 parent 89c7b62 commit 6f6b26a

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

lib/ocpp/v16/charge_point_configuration.cpp

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// SPDX-License-Identifier: Apache-2.0
22
// Copyright Pionix GmbH and Contributors to EVerest
3+
4+
#include <filesystem>
35
#include <fstream>
46
#include <future>
57
#include <mutex>
@@ -209,11 +211,23 @@ json ChargePointConfiguration::get_user_config() {
209211
}
210212

211213
void ChargePointConfiguration::setInUserConfig(std::string profile, std::string key, const json value) {
212-
json user_config = this->get_user_config();
213-
user_config[profile][key] = value;
214-
std::ofstream ofs(this->user_config_path.c_str());
215-
ofs << user_config << std::endl;
216-
ofs.close();
214+
// write to a separate file to minimise corruption and data loss; then rename
215+
namespace fs = std::filesystem;
216+
217+
try {
218+
const auto tmp_file = user_config_path.string() + '$';
219+
fs::remove(tmp_file);
220+
221+
json user_config = get_user_config();
222+
user_config[profile][key] = value;
223+
std::ofstream ofs(tmp_file);
224+
ofs << user_config << std::endl;
225+
ofs.close();
226+
227+
fs::rename(tmp_file, user_config_path);
228+
} catch (const fs::filesystem_error& ex) {
229+
EVLOG_error << "Error updating user config: " << ex.path1() << ' ' << ex.path2() << ": " << ex.what();
230+
}
217231
}
218232

219233
std::string to_csl(const std::vector<std::string>& vec) {

0 commit comments

Comments
 (0)