openpilot0/common/params.cc

320 lines
11 KiB
C++
Raw Normal View History

#include "common/params.h"
#include <dirent.h>
#include <sys/file.h>
#include <algorithm>
#include <csignal>
#include <unordered_map>
#include "common/swaglog.h"
#include "common/util.h"
#include "system/hardware/hw.h"
namespace {
volatile sig_atomic_t params_do_exit = 0;
void params_sig_handler(int signal) {
params_do_exit = 1;
}
int fsync_dir(const std::string &path) {
int result = -1;
int fd = HANDLE_EINTR(open(path.c_str(), O_RDONLY, 0755));
if (fd >= 0) {
result = fsync(fd);
close(fd);
}
return result;
}
bool create_params_path(const std::string &param_path, const std::string &key_path) {
// Make sure params path exists
if (!util::file_exists(param_path) && !util::create_directories(param_path, 0775)) {
return false;
}
// See if the symlink exists, otherwise create it
if (!util::file_exists(key_path)) {
// 1) Create temp folder
// 2) Symlink it to temp link
// 3) Move symlink to <params>/d
std::string tmp_path = param_path + "/.tmp_XXXXXX";
// this should be OK since mkdtemp just replaces characters in place
char *tmp_dir = mkdtemp((char *)tmp_path.c_str());
if (tmp_dir == NULL) {
return false;
}
std::string link_path = std::string(tmp_dir) + ".link";
if (symlink(tmp_dir, link_path.c_str()) != 0) {
return false;
}
// don't return false if it has been created by other
if (rename(link_path.c_str(), key_path.c_str()) != 0 && errno != EEXIST) {
return false;
}
}
return true;
}
std::string ensure_params_path(const std::string &prefix, const std::string &path = {}) {
std::string params_path = path.empty() ? Path::params() : path;
if (!create_params_path(params_path, params_path + prefix)) {
throw std::runtime_error(util::string_format("Failed to ensure params path, errno=%d", errno));
}
return params_path;
}
class FileLock {
public:
FileLock(const std::string &fn) {
fd_ = HANDLE_EINTR(open(fn.c_str(), O_CREAT, 0775));
if (fd_ < 0 || HANDLE_EINTR(flock(fd_, LOCK_EX)) < 0) {
LOGE("Failed to lock file %s, errno=%d", fn.c_str(), errno);
}
}
~FileLock() { close(fd_); }
private:
int fd_ = -1;
};
std::unordered_map<std::string, uint32_t> keys = {
{"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG},
{"AssistNowToken", PERSISTENT},
{"AthenadPid", PERSISTENT},
{"AthenadUploadQueue", PERSISTENT},
{"CalibrationParams", PERSISTENT},
{"CameraDebugExpGain", CLEAR_ON_MANAGER_START},
{"CameraDebugExpTime", CLEAR_ON_MANAGER_START},
{"CarBatteryCapacity", PERSISTENT},
{"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"CarParamsCache", CLEAR_ON_MANAGER_START},
{"CarParamsPersistent", PERSISTENT},
{"CarVin", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"CompletedTrainingVersion", PERSISTENT},
{"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"CurrentBootlog", PERSISTENT},
{"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"DisableLogging", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"DisablePowerDown", PERSISTENT},
{"ExperimentalMode", PERSISTENT},
{"ExperimentalModeConfirmed", PERSISTENT},
{"ExperimentalLongitudinalEnabled", PERSISTENT},
{"DisableUpdates", PERSISTENT},
Add Disengage on Accelerator Toggle (#23977) * Squashed commit of the following: commit 953bcf0ecf8d03f0fec9ce0d5442cc660ae2347d Merge: b4198608d efd04715e Author: Shane Smiskol <shane@smiskol.com> Date: Fri Apr 1 19:58:06 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit b4198608dac9595bfeb9443f95cd6c5d385cd62d Merge: 24f90b2c8 0e983562d Author: Shane Smiskol <shane@smiskol.com> Date: Fri Apr 1 14:32:54 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 24f90b2c8d6ae509c0776b6e33b743467aa08dee Author: Shane Smiskol <shane@smiskol.com> Date: Thu Mar 31 14:07:52 2022 -0700 revert changes and get ready for override commit aa514df6b5e8431f0faa07f6b25eb5cb6c9f2749 Author: Shane Smiskol <shane@smiskol.com> Date: Wed Mar 30 20:52:24 2022 -0700 temporary commit c874e10c2555968c683f629c4582ab22e51d431f Author: Shane Smiskol <shane@smiskol.com> Date: Wed Mar 30 00:30:13 2022 -0700 move gasPressed to controlsd commit fe670439dff5bc6dfc5963d79ca2febe0c5920c7 Merge: 49d3b6d11 c78701e47 Author: Shane Smiskol <shane@smiskol.com> Date: Wed Mar 30 00:15:48 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 49d3b6d1162893fa94b2294152f0718eeb4698ed Merge: 475b27e74 3e819bc5a Author: Shane Smiskol <shane@smiskol.com> Date: Mon Mar 28 13:06:08 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 475b27e74fd6479f1d148e9ded1eca6ee476865c Author: Shane Smiskol <shane@smiskol.com> Date: Thu Mar 24 20:24:59 2022 -0700 update SAFETY.md commit 0798eadb82749e12ecbaa86f4e57b21bd3dbc7e8 Author: Shane Smiskol <shane@smiskol.com> Date: Thu Mar 24 17:52:06 2022 -0700 ⛽ ➡️ 🔋 bump commit d2b64b89cf8d7265bc90848b4e3a2276c9a4cb78 Author: Shane Smiskol <shane@smiskol.com> Date: Thu Mar 24 16:19:34 2022 -0700 these changes will be in border PR these changes will be border PR commit bed31e63de2244c161729773978fef8a9246ddb5 Merge: 491417640 603e07793 Author: Shane Smiskol <shane@smiskol.com> Date: Thu Mar 24 16:17:31 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 49141764098e3a701ff123ead52de4656b31db4d Merge: 9291e9f00 46ed8bb8e Author: Shane Smiskol <shane@smiskol.com> Date: Wed Mar 23 19:00:26 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 9291e9f0045780669b2ffa7f08fb10373c03b070 Merge: 2aed64157 2c947f193 Author: Shane Smiskol <shane@smiskol.com> Date: Fri Mar 18 19:03:13 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 2aed64157d6e9dc993d103a2c6abf7e643410562 Author: Shane Smiskol <shane@smiskol.com> Date: Fri Mar 18 19:03:03 2022 -0700 Revert "send pre-enable state when gas is pressed" This reverts commit 8d82e697dc2efade307413e767d14b56b4d2d079. commit a219defe5342efa731a957b2ff4fd86292c1f239 Author: Shane Smiskol <shane@smiskol.com> Date: Thu Mar 17 12:50:46 2022 -0700 bump cereal commit 8d82e697dc2efade307413e767d14b56b4d2d079 Author: Shane Smiskol <shane@smiskol.com> Date: Wed Mar 16 22:40:13 2022 -0700 send pre-enable state when gas is pressed formatting and it's out forgot one allow gas press show toggle revert changes revert changes commit 5eb4d1ab1b77ac65bdd901f692ebfb848d5187ca Merge: bad1bdc74 d0ef25959 Author: Shane Smiskol <shane@smiskol.com> Date: Wed Mar 16 22:29:43 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit bad1bdc7428c5d8a4a765b259da504f0ade84424 Author: Shane Smiskol <shane@smiskol.com> Date: Tue Mar 15 23:03:56 2022 -0700 clean up a bit commit 7516ed9b786536a07f00a92b9c1742ca252a01d1 Author: Shane Smiskol <shane@smiskol.com> Date: Tue Mar 15 22:55:09 2022 -0700 these are null checks right now commit 408f5f1d633521b29b08d966c9b387fa79dff0d6 Author: Shane Smiskol <shane@smiskol.com> Date: Tue Mar 15 22:51:14 2022 -0700 should work commit be1978e29c03d8843cf073cc9ddf84020fd2b378 Author: Shane Smiskol <shane@smiskol.com> Date: Tue Mar 15 22:36:16 2022 -0700 stash commit f0bd4c47e9d27061c6cd3b88765a7c10995f42db Author: Shane Smiskol <shane@smiskol.com> Date: Tue Mar 15 22:26:24 2022 -0700 this was flipped commit d5b6e30389a727e8559331acd706422e1b246f60 Merge: 820b19894 c814c1383 Author: Shane Smiskol <shane@smiskol.com> Date: Tue Mar 15 22:25:49 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 820b1989496225df1f66f39b477f1e9402db1b19 Merge: 91763f9ff 6d2483ff9 Author: Shane Smiskol <shane@smiskol.com> Date: Mon Mar 14 23:39:34 2022 -0700 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 91763f9ff4321986babce1a7b1272fcf64c8f753 Author: Shane Smiskol <shane@smiskol.com> Date: Thu Feb 24 20:15:26 2022 -0800 add icon from jozef 🔥 commit 1885c9e2bacd9351c7e421b1436dcbfbde238436 Merge: 1f591736a eae207a84 Author: Shane Smiskol <shane@smiskol.com> Date: Thu Feb 24 20:08:07 2022 -0800 Merge remote-tracking branch 'upstream/master' into disengage-on-gas commit 1f591736a2767b1ed892c29ec5000cc7348f01c7 Merge: 465811f0b ebf5b27a7 Author: Jason Wen <47793918+sunnyhaibin@users.noreply.github.com> Date: Sat Feb 12 10:24:29 2022 -0500 Merge branch 'master' into disengage-on-gas commit 465811f0b4776e43a289398e4d4369362b7da58c Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Feb 11 11:20:32 2022 -0500 Add param to process replay commit 0344363a533505435cff87eb33356b2364a4156f Merge: 700efcb3f 1175355b7 Author: Jason Wen <47793918+sunnyhaibin@users.noreply.github.com> Date: Fri Feb 11 11:07:31 2022 -0500 Merge branch 'master' into disengage-on-gas commit 700efcb3f444092f99ef10e9908f83402429d742 Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Feb 11 11:04:39 2022 -0500 Add param to unsafeMode commit 220ce272fee1f7f5ace2a04052605a6e4f95712b Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Feb 11 10:54:16 2022 -0500 Add param to unsafeMode commit d273bb78acbc23ee5255e461fa71b2f0400a5e03 Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Feb 11 10:52:22 2022 -0500 Resolve conflicts commit 1a85afd60c2f0d3140dfa8e7cd574d6b88abd5e3 Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Feb 11 10:51:50 2022 -0500 Resolve conflicts commit e3be32afc2bb2423d29e2b4f85b3cff3fe72aab9 Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Feb 11 10:51:08 2022 -0500 Resolve conflicts commit f27203af3afe612173bf9a63e15c57118598b5b8 Author: Jason Wen <haibin.wen3@gmail.com> Date: Wed Jan 19 00:30:09 2022 -0500 Add param to process replay commit 04c0ad1a54f4fea5efe74b3203d9bdbd693b64a6 Author: Jason Wen <47793918+sunnyhaibin@users.noreply.github.com> Date: Wed Jan 19 00:28:49 2022 -0500 Update interfaces.py Co-authored-by: Willem Melching <willem.melching@gmail.com> commit 99cf13caeb4d9f2c95c25e1e78b6e353ea508cb6 Author: Jason Wen <haibin.wen3@gmail.com> Date: Sat Jan 15 00:03:38 2022 -0500 Fix missing params lib commit 2230254ca709625d591b0c73d1a6022c450f6ef6 Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Jan 14 23:38:46 2022 -0500 Disengage on gas toggle commit 87475e02cb63cc39c9b16edc67f303e02d17e6ef Author: Jason Wen <haibin.wen3@gmail.com> Date: Fri Jan 14 23:24:00 2022 -0500 Disengage on gas toggle * bump * use ALTERNATIVE_EXPERIENCE * or it * de-bump * update refs * update refs! * you can just ctrl+click ALTERNATIVE_EXPERIENCE! * already have a params * update text old-commit-hash: f1f40c117a65294e27f93f953a772c43078bdceb
2022-04-05 12:59:52 +08:00
{"DisengageOnAccelerator", PERSISTENT},
{"DongleId", PERSISTENT},
{"DoReboot", CLEAR_ON_MANAGER_START},
{"DoShutdown", CLEAR_ON_MANAGER_START},
{"DoUninstall", CLEAR_ON_MANAGER_START},
{"FirmwareQueryDone", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"ForcePowerDown", CLEAR_ON_MANAGER_START},
{"GitBranch", PERSISTENT},
{"GitCommit", PERSISTENT},
{"GitDiff", PERSISTENT},
{"GithubSshKeys", PERSISTENT},
{"GithubUsername", PERSISTENT},
{"GitRemote", PERSISTENT},
{"GsmApn", PERSISTENT},
{"GsmMetered", PERSISTENT},
{"GsmRoaming", PERSISTENT},
{"HardwareSerial", PERSISTENT},
{"HasAcceptedTerms", PERSISTENT},
{"IMEI", PERSISTENT},
{"InstallDate", PERSISTENT},
{"IsDriverViewEnabled", CLEAR_ON_MANAGER_START},
{"IsEngaged", PERSISTENT},
{"IsLdwEnabled", PERSISTENT},
{"IsMetric", PERSISTENT},
{"IsOffroad", CLEAR_ON_MANAGER_START},
{"IsOnroad", PERSISTENT},
{"IsRhdDetected", PERSISTENT},
{"IsTakingSnapshot", CLEAR_ON_MANAGER_START},
{"IsTestedBranch", CLEAR_ON_MANAGER_START},
{"IsReleaseBranch", CLEAR_ON_MANAGER_START},
{"IsUpdateAvailable", CLEAR_ON_MANAGER_START},
{"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"LaikadEphemerisV3", PERSISTENT | DONT_LOG},
UI: Internationalization support (#21212) * rough multiple language demo * more wrappings * stash * add some bad translations * updates * map from french to spanish still has same problem of needing to call setText on everything * add files * restart UI * use return code * relative path * more translations * don't loop restart * Toggle and prime translations * try on device * try QComboBox with readable style * stash * not yet scrollable * stash * dynamic translations (doesn't work for dynamic widget strings yet) * clean up multiple option selector * store languages in json * try transparent * Try transparent popup * see how this looks * tweaks * clean up * update names * Add Chinese (Simplified) translations * Do missing French translations * unit tests caught that :) * fix test * fix other test (on PC) * add entries to dialog to test * add cancel button, clean up a bit * just chinese * some clean up * use quotes * clean up * Just quit, set timeout to 0 * half a second * use exitcode * don't print if it's expected * this comment is outdated * update translations * Update translations * re-order input classes * Update line numbers * use enabled property for button style * Get rid of ListWidget * Update line numbers * Log failed to load language * Log failed to load language * Move to utils and fix english logging extra line * Update translations * spacing * looks a bit better * try this instead of exitcode fixes fix * only one function * comment * Update line numbers * fixup some japanese translations * clean up multi option dialog * Update line numbers old-commit-hash: 949de4d2b6b293d9f77d83c58212f5dee176cbf1
2022-07-09 11:25:54 +08:00
{"LanguageSetting", PERSISTENT},
{"LastAthenaPingTime", CLEAR_ON_MANAGER_START},
{"LastGPSPosition", PERSISTENT},
{"LastManagerExitReason", CLEAR_ON_MANAGER_START},
{"LastPowerDropDetected", CLEAR_ON_MANAGER_START},
{"LastSystemShutdown", CLEAR_ON_MANAGER_START},
{"LastUpdateException", CLEAR_ON_MANAGER_START},
{"LastUpdateTime", PERSISTENT},
{"LiveParameters", PERSISTENT},
Live torque (#25456) * wip torqued * add basic logic * setup in manager * check sanity and publish msg * add first order filter to outputs * wire up controlsd, and update gains * rename intercept to offset * add cloudlog, live values are not updated * fix bugs, do not reset points for now * fix crashes * rename to main * fix bugs, works offline * fix float in cereal bug * add latacc filter * randomly choose points, approx for iid * add variable decay * local param to capnp instead of dict * verify works in replay * use torqued output in controlsd * use in controlsd; use points from past routes * controlsd bugfix * filter before updating gains, needs to be replaced * save all points to ensure smooth transition across routes, revert friction factor to 1.5 * add filters to prevent noisy low-speed data points; improve fit sanity * add engaged buffer * revert lat_acc thresh * use paramsd realtime process config * make latacc-to-torque generic, and overrideable * move freq to 4Hz, avoid storing in np.array, don't publish points in the message * float instead of np * remove constant while storing pts * rename slope, offset to lat_accet_factor, offset * resolve issues * use camelcase in all capnp params * use camelcase everywhere * reduce latacc threshold or sanity, add car_sane todo, save points properly * add and check tag * write param to disk at end of route * remove args * rebase op, cereal * save on exit * restore default handler * cpu usage check * add to process replay * handle reset better, reduce unnecessary computation * always publish raw values - useful for debug * regen routes * update refs * checks on cache restore * check tuning vals too * clean that up * reduce cpu usage * reduce cpu usage by 75% * cleanup * optimize further * handle reset condition better, don't put points in init, use only in corolla * bump cereal after rebasing * update refs * Update common/params.cc Co-authored-by: Adeeb Shihadeh <adeebshihadeh@gmail.com> * remove unnecessary checks * Update RELEASES.md Co-authored-by: Adeeb Shihadeh <adeebshihadeh@gmail.com> old-commit-hash: 4fa62f146426f76c9c1c2867d9729b33ec612b59
2022-09-20 06:19:26 +08:00
{"LiveTorqueCarParams", PERSISTENT},
{"LiveTorqueParameters", PERSISTENT | DONT_LOG},
{"NavDestination", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"NavDestinationWaypoints", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"NavSettingTime24h", PERSISTENT},
{"NavSettingLeftSide", PERSISTENT},
{"NavdRender", PERSISTENT},
{"ObdMultiplexingChanged", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"ObdMultiplexingEnabled", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"OpenpilotEnabledToggle", PERSISTENT},
{"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"PandaSignatures", CLEAR_ON_MANAGER_START},
{"Passive", PERSISTENT},
{"PrimeType", PERSISTENT},
{"RecordFront", PERSISTENT},
{"RecordFrontLock", PERSISTENT}, // for the internal fleet
{"ReplayControlsState", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"ShouldDoUpdate", CLEAR_ON_MANAGER_START},
{"SnoozeUpdate", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"SshEnabled", PERSISTENT},
{"SubscriberInfo", PERSISTENT},
{"TermsVersion", PERSISTENT},
{"Timezone", PERSISTENT},
{"TrainingVersion", PERSISTENT},
{"UbloxAvailable", PERSISTENT},
{"UpdateAvailable", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"UpdateFailedCount", CLEAR_ON_MANAGER_START},
{"UpdaterState", CLEAR_ON_MANAGER_START},
{"UpdaterFetchAvailable", CLEAR_ON_MANAGER_START},
{"UpdaterTargetBranch", CLEAR_ON_MANAGER_START},
{"UpdaterAvailableBranches", CLEAR_ON_MANAGER_START},
{"UpdaterCurrentDescription", CLEAR_ON_MANAGER_START},
{"UpdaterCurrentReleaseNotes", CLEAR_ON_MANAGER_START},
{"UpdaterNewDescription", CLEAR_ON_MANAGER_START},
{"UpdaterNewReleaseNotes", CLEAR_ON_MANAGER_START},
{"Version", PERSISTENT},
{"VisionRadarToggle", PERSISTENT},
{"WideCameraOnly", PERSISTENT},
{"ApiCache_Device", PERSISTENT},
{"ApiCache_DriveStats", PERSISTENT},
{"ApiCache_NavDestinations", PERSISTENT},
{"ApiCache_Owner", PERSISTENT},
{"Offroad_BadNvme", CLEAR_ON_MANAGER_START},
{"Offroad_CarUnrecognized", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START},
{"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START},
{"Offroad_InvalidTime", CLEAR_ON_MANAGER_START},
{"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START},
{"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START},
{"Offroad_NoFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"Offroad_StorageMissing", CLEAR_ON_MANAGER_START},
{"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START},
{"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START},
{"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START},
};
} // namespace
Params::Params(const std::string &path) {
prefix = "/" + util::getenv("OPENPILOT_PREFIX", "d");
params_path = ensure_params_path(prefix, path);
}
std::vector<std::string> Params::allKeys() const {
std::vector<std::string> ret;
for (auto &p : keys) {
ret.push_back(p.first);
}
return ret;
}
bool Params::checkKey(const std::string &key) {
return keys.find(key) != keys.end();
}
ParamKeyType Params::getKeyType(const std::string &key) {
return static_cast<ParamKeyType>(keys[key]);
}
int Params::put(const char* key, const char* value, size_t value_size) {
// Information about safely and atomically writing a file: https://lwn.net/Articles/457667/
// 1) Create temp file
// 2) Write data to temp file
// 3) fsync() the temp file
// 4) rename the temp file to the real name
// 5) fsync() the containing directory
std::string tmp_path = params_path + "/.tmp_value_XXXXXX";
int tmp_fd = mkstemp((char*)tmp_path.c_str());
if (tmp_fd < 0) return -1;
int result = -1;
do {
// Write value to temp.
ssize_t bytes_written = HANDLE_EINTR(write(tmp_fd, value, value_size));
if (bytes_written < 0 || (size_t)bytes_written != value_size) {
result = -20;
break;
}
// fsync to force persist the changes.
if ((result = fsync(tmp_fd)) < 0) break;
FileLock file_lock(params_path + "/.lock");
// Move temp into place.
if ((result = rename(tmp_path.c_str(), getParamPath(key).c_str())) < 0) break;
// fsync parent directory
result = fsync_dir(getParamPath());
} while (false);
close(tmp_fd);
::unlink(tmp_path.c_str());
return result;
}
int Params::remove(const std::string &key) {
FileLock file_lock(params_path + "/.lock");
int result = unlink(getParamPath(key).c_str());
if (result != 0) {
return result;
}
return fsync_dir(getParamPath());
}
std::string Params::get(const std::string &key, bool block) {
if (!block) {
return util::read_file(getParamPath(key));
} else {
// blocking read until successful
params_do_exit = 0;
void (*prev_handler_sigint)(int) = std::signal(SIGINT, params_sig_handler);
void (*prev_handler_sigterm)(int) = std::signal(SIGTERM, params_sig_handler);
std::string value;
while (!params_do_exit) {
if (value = util::read_file(getParamPath(key)); !value.empty()) {
break;
}
util::sleep_for(100); // 0.1 s
}
std::signal(SIGINT, prev_handler_sigint);
std::signal(SIGTERM, prev_handler_sigterm);
return value;
}
}
std::map<std::string, std::string> Params::readAll() {
FileLock file_lock(params_path + "/.lock");
return util::read_files_in_dir(getParamPath());
}
void Params::clearAll(ParamKeyType key_type) {
FileLock file_lock(params_path + "/.lock");
if (key_type == ALL) {
util::remove_files_in_dir(getParamPath());
} else {
for (auto &[key, type] : keys) {
if (type & key_type) {
unlink(getParamPath(key).c_str());
}
}
}
fsync_dir(getParamPath());
}