blob: 1e6b7223fe3dd5944bfb6c8afc54f7cc5d7bc69f [file] [log] [blame] [edit]
#include "internal_boot_counter.h"
#include <fstream>
#include <optional>
#include <string>
#include <utility>
#include "daemon_context.h"
#include "state_persistence.pb.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#include "bmc/status_macros.h"
namespace safepower_agent {
InternalBootCounter::InternalBootCounter(std::string boot_id_path)
: boot_id_path_(std::move(boot_id_path)) {}
absl::Status InternalBootCounter::CheckAndIncrement() {
absl::MutexLock lock(mutex_);
std::ifstream boot_id_file(boot_id_path_);
if (!boot_id_file.is_open()) {
return absl::InternalError(absl::StrCat("Failed to open ", boot_id_path_));
}
std::string current_boot_id;
std::getline(boot_id_file, current_boot_id);
absl::StripAsciiWhitespace(&current_boot_id);
if (current_boot_id.empty()) {
return absl::InternalError("Boot ID is empty");
}
ASSIGN_OR_RETURN(
auto saved_actions,
DaemonContext::Get().persistent_storage_manager().ReadSavedActions());
int boot_counter = saved_actions.boot_counter();
if (saved_actions.boot_id() == current_boot_id) {
boot_counter_ = boot_counter;
return absl::OkStatus();
}
boot_counter++;
// Create a delta with only the updated boot info.
safepower_agent_persistence_proto::SavedActions delta;
delta.set_boot_id(current_boot_id);
delta.set_boot_counter(boot_counter);
LOG(INFO) << "Boot ID changed from " << saved_actions.boot_id() << " to "
<< current_boot_id << ". Incrementing boot counter to "
<< delta.boot_counter();
boot_counter_ = boot_counter;
return DaemonContext::Get()
.persistent_storage_manager()
.WriteSavedActionsChange(delta);
}
std::optional<int> InternalBootCounter::value() const {
absl::MutexLock lock(mutex_);
return boot_counter_;
}
} // namespace safepower_agent