| #include "persistent_storage_impl.h" | |
| #include <algorithm> | |
| #include <cerrno> | |
| #include <cstddef> | |
| #include <cstdint> | |
| #include <cstring> | |
| #include <filesystem> // NOLINT(build/c++17) | |
| #include <iterator> | |
| #include <optional> | |
| #include <ostream> | |
| #include <string> | |
| #include <system_error> // NOLINT(build/c++11) | |
| #include <vector> | |
| #include "google/protobuf/timestamp.pb.h" | |
| #include "action_context.h" | |
| #include "flight_record.h" | |
| #include "safepower_agent.pb.h" | |
| #include "safepower_agent_config.pb.h" | |
| #include "state_persistence.pb.h" | |
| #include "proto_reader.h" | |
| #include "absl/container/flat_hash_map.h" | |
| #include "absl/log/log.h" | |
| #include "absl/status/status.h" | |
| #include "absl/status/statusor.h" | |
| #include "absl/strings/numbers.h" | |
| #include "absl/strings/str_cat.h" | |
| #include "absl/strings/str_split.h" | |
| #include "absl/strings/string_view.h" | |
| #include "absl/synchronization/mutex.h" | |
| #include "absl/time/clock.h" | |
| #include "absl/time/time.h" | |
| #include "absl/types/span.h" | |
| #include "google/protobuf/io/zero_copy_stream_impl.h" | |
| #include "bmc/status_macros.h" | |
| namespace persistent_storage { | |
| using safepower_agent::ActionContext; | |
| using safepower_agent::FlightRecordWrapper; | |
| using safepower_agent_persistence_proto::SavedAction; | |
| using safepower_agent_persistence_proto::SavedActionRecord; | |
| using safepower_agent_persistence_proto::SavedActions; | |
| // TODO: b/493660834 - | |
| // Convert this to use posix file APIs, and not std::filesystem | |
| inline absl::Status WriteSavedActions(const std::string& proto_path, | |
| const SavedActions& in_proto) { | |
| int fd = open(proto_path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644); | |
| if (fd < 0) { | |
| int ec = errno; | |
| LOG(ERROR) << "Failed to open file " << proto_path << " " << strerror(ec); | |
| return absl::UnavailableError( | |
| absl::StrCat("Failed to open file: ", proto_path, ":", strerror(ec))); | |
| } | |
| google::protobuf::io::FileOutputStream stream(fd); | |
| stream.SetCloseOnDelete(true); | |
| if (!in_proto.SerializeToZeroCopyStream(&stream)) { | |
| int ec = stream.GetErrno(); | |
| LOG(ERROR) << "Failed to serialize the proto file" << proto_path | |
| << " error:" << strerror(ec); | |
| return absl::InternalError( | |
| absl::StrCat("Failed to serialize the proto file: ", proto_path, | |
| " error:", strerror(ec))); | |
| } | |
| if (!stream.Flush()) { | |
| int ec = stream.GetErrno(); | |
| LOG(ERROR) << "Failed to flush the proto file" << proto_path | |
| << " error:" << strerror(ec); | |
| return absl::InternalError( | |
| absl::StrCat("Failed to flush the proto file: ", proto_path, | |
| " error:", strerror(ec))); | |
| } | |
| int ret = fsync(fd); | |
| if (ret < 0) { | |
| int ec = errno; | |
| LOG(ERROR) << "Failed to sync the file " << proto_path << " " | |
| << strerror(ec); | |
| return absl::DataLossError(absl::StrCat( | |
| "Failed to sync the file: ", proto_path, ":", strerror(ec))); | |
| } | |
| return absl::OkStatus(); | |
| } | |
| PersistentStorageManagerImpl::PersistentStorageManagerImpl( | |
| const safepower_agent_config::PersistentStorageConfig& config) { | |
| if (!config.dir_path().empty()) { | |
| dir_path_ = config.dir_path(); | |
| } | |
| if (config.max_file_size() > 0) { | |
| max_file_size_ = config.max_file_size(); | |
| } | |
| if (config.proto_keep_number() > 0) { | |
| proto_keep_number_ = config.proto_keep_number(); | |
| } | |
| } | |
| // use the data in the input arg to make several records | |
| // if this is the first time writing the file, write the record log | |
| // append the records to the record log, by saving them in wire format | |
| // check the file size, | |
| // if it is too large, | |
| // merge, and convert to map, and back to append log | |
| // and rewrite the file | |
| // TODO: b/469169011 - Rename these functions | |
| absl::Status PersistentStorageManagerImpl::WriteSavedActionsChange( | |
| const SavedActions& actions) { | |
| absl::MutexLock lock(mu_); | |
| std::string write_string; | |
| auto files = listFiles(dir_path_); | |
| if (!files.ok()) { | |
| return files.status(); | |
| } | |
| std::optional<uint64_t> id = findLargestFileId(files.value()); | |
| uint64_t current_id_val = id.has_value() ? id.value() : 0; | |
| std::string file_path = MakeFilePath(dir_path_, current_id_val); | |
| // write the new record to the file, and close it | |
| // this ensures that the data is always written before the file is collated | |
| RETURN_IF_ERROR(WriteSavedActions(file_path, actions)); | |
| // if the file is too large, merge the files | |
| std::error_code ec; | |
| std::uintmax_t file_size = std::filesystem::file_size(file_path, ec); | |
| if (ec) { | |
| return absl::UnavailableError( | |
| absl::StrCat("Failed to get file size", ec.message())); | |
| } | |
| if (file_size > max_file_size_) { | |
| if (!id.has_value()) { | |
| LOG(WARNING) << "A single record written to a new file " << file_path | |
| << " exceeds max_file_size " << max_file_size_ | |
| << ". File size is " << file_size; | |
| } | |
| LOG(INFO) << "file size too large merging" << std::endl; | |
| absl::StatusOr<SavedActions> saved_actions_write_ordered = | |
| proto_reader::ReadProto<SavedActions>(file_path); | |
| if (!saved_actions_write_ordered.ok()) { | |
| return saved_actions_write_ordered.status(); | |
| } | |
| absl::flat_hash_map<FlightRecordWrapper, SavedAction> new_saved_actions_map; | |
| absl::Status status = this->ConvertAppendToMap( | |
| new_saved_actions_map, *saved_actions_write_ordered); | |
| if (!status.ok()) { | |
| return status; | |
| } | |
| // only keep the most recent protos | |
| absl::Status keep_status = keepMostRecentProtos(new_saved_actions_map); | |
| if (!keep_status.ok()) { | |
| return keep_status; | |
| } | |
| // convert map to append log to save it again | |
| // TODO: b/474407879 - Reuse CompressLogs for this | |
| SavedActions new_log; | |
| for (auto& i : new_saved_actions_map) { | |
| SavedActionRecord* ptr_record = new_log.add_saved_action_records(); | |
| *(ptr_record->mutable_actions()) = i.second; | |
| } | |
| if (!saved_actions_write_ordered->boot_id().empty()) { | |
| new_log.set_boot_id(saved_actions_write_ordered->boot_id()); | |
| } | |
| if (saved_actions_write_ordered->boot_counter() != 0) { | |
| new_log.set_boot_counter(saved_actions_write_ordered->boot_counter()); | |
| } | |
| std::string next_file = MakeFilePath(dir_path_, current_id_val + 1); | |
| RETURN_IF_ERROR(WriteSavedActions(next_file, new_log)); | |
| return deleteAllFilesExceptLargest(dir_path_); | |
| } | |
| return absl::OkStatus(); | |
| } | |
| absl::Status PersistentStorageManagerImpl::ConvertAppendToMap( | |
| absl::flat_hash_map<FlightRecordWrapper, SavedAction>& map, | |
| const SavedActions& saved_actions) { | |
| for (const auto& i : saved_actions.saved_action_records()) { | |
| FlightRecordWrapper flight_record( | |
| i.actions().original_request().flight_record()); | |
| auto [it, inserted] = map.try_emplace(flight_record, i.actions()); | |
| if (!inserted) { | |
| it->second.MergeFrom(i.actions()); | |
| } | |
| } | |
| return absl::OkStatus(); | |
| } | |
| absl::StatusOr<SavedActions> PersistentStorageManagerImpl::CompressLogs( | |
| const SavedActions& saved_actions) { | |
| // convert to map, and back to append log | |
| absl::flat_hash_map<FlightRecordWrapper, SavedAction> new_saved_actions_map; | |
| absl::Status status = | |
| this->ConvertAppendToMap(new_saved_actions_map, saved_actions); | |
| if (!status.ok()) { | |
| return status; | |
| } | |
| SavedActions new_log; | |
| for (auto& i : new_saved_actions_map) { | |
| SavedActionRecord* ptr_record = new_log.add_saved_action_records(); | |
| *(ptr_record->mutable_actions()) = i.second; | |
| } | |
| if (!saved_actions.boot_id().empty()) { | |
| new_log.set_boot_id(saved_actions.boot_id()); | |
| } | |
| if (saved_actions.boot_counter() != 0) { | |
| new_log.set_boot_counter(saved_actions.boot_counter()); | |
| } | |
| return new_log; | |
| } | |
| absl::StatusOr<SavedActions> PersistentStorageManagerImpl::ReadSavedActions() { | |
| absl::MutexLock lock(mu_); | |
| auto files = listFiles(dir_path_); | |
| if (!files.ok()) { | |
| return files.status(); | |
| } | |
| std::optional<uint64_t> id = findLargestFileId(files.value()); | |
| if (!id.has_value()) { | |
| return SavedActions(); | |
| } | |
| std::string file_path = MakeFilePath(dir_path_, id.value()); | |
| auto saved_actions = proto_reader::ReadProto<SavedActions>(file_path); | |
| LOG_IF(ERROR, !saved_actions.ok()) | |
| << "Unable to read SavedActions proto file \"" << file_path | |
| << "\": " << saved_actions.status(); | |
| absl::StatusOr<SavedActions> compressed_saved_actions; | |
| if (saved_actions.ok()) { | |
| compressed_saved_actions = CompressLogs(saved_actions.value()); | |
| if (compressed_saved_actions.ok()) { | |
| return compressed_saved_actions.value(); | |
| } | |
| LOG(ERROR) << "Unable to compress SavedActions proto file \"" << file_path | |
| << "\": " << compressed_saved_actions.status(); | |
| } | |
| absl::Status original_failing_status = saved_actions.status().ok() | |
| ? compressed_saved_actions.status() | |
| : saved_actions.status(); | |
| if (id.value() == 0) { | |
| // The file index is 0, so there are no older files to fallback to. | |
| // Return the original error since we can't recover. | |
| return original_failing_status; | |
| } | |
| // Attempt to recover by reading the next oldest file. | |
| file_path = MakeFilePath(dir_path_, id.value() - 1); | |
| LOG(ERROR) << "Trying to read older state:" << file_path; | |
| auto saved_actions_older = proto_reader::ReadProto<SavedActions>(file_path); | |
| if (!saved_actions_older.ok()) { | |
| // return the value of the original message, print the status of the | |
| // second read, and return the original status | |
| LOG(ERROR) << "reading older status failed, (probably file not present): " | |
| << saved_actions_older.status(); | |
| return original_failing_status; | |
| } | |
| auto compressed_logs_older = CompressLogs(saved_actions_older.value()); | |
| if (!compressed_logs_older.ok()) { | |
| LOG(ERROR) << "compressing older logs failed: " | |
| << compressed_logs_older.status(); | |
| return original_failing_status; | |
| } | |
| return compressed_logs_older.value(); | |
| } | |
| google::protobuf::Timestamp getChangeTime(const SavedAction& action) { | |
| if (!action.has_action_state_log() || | |
| (action.action_state_log().history().empty())) { | |
| // if there is no history, return the time of the last 24 hours | |
| absl::Time now = absl::Now(); | |
| absl::Time one_day_ago = now - absl::Hours(24); | |
| google::protobuf::Timestamp timestamp; | |
| timestamp.set_seconds(absl::ToUnixSeconds(one_day_ago)); | |
| return timestamp; | |
| } | |
| return action.action_state_log().history().rbegin()->changed_at(); | |
| } | |
| bool AtEndState(const SavedAction& action) { | |
| if ((!action.has_action_state_log()) || | |
| !action.action_state_log().has_current_state()) { | |
| return false; // if there is no state | |
| // we should depend on the timing logic to clear it | |
| } | |
| const safepower_agent_proto::ActionState& state = | |
| action.action_state_log().current_state(); | |
| return ActionContext::IsFinalState(state); | |
| } | |
| // when the persistence proto is cleaned up, we need to remove the protos that | |
| // we need to keep the most recent N protos | |
| absl::Status PersistentStorageManagerImpl::keepMostRecentProtos( | |
| absl::flat_hash_map<FlightRecordWrapper, SavedAction>& map) { | |
| if (map.size() < proto_keep_number_) { | |
| LOG(WARNING) << " Assumptions about the size of the" | |
| << " saved protos are wrong" << std::endl | |
| << "The number of saved protos is " << map.size() | |
| << "less than the number we want to keep " | |
| << proto_keep_number_; | |
| return absl::OkStatus(); | |
| } | |
| // sort the protos by time | |
| std::vector<SavedActionRecord> records; | |
| for (const auto& i : map) { | |
| SavedActionRecord record; | |
| *(record.mutable_actions()) = i.second; | |
| records.push_back(record); | |
| } | |
| // Sort the records so that all records in a final state come before those | |
| // that do not. Within each grouping, sort from oldest to youngest. | |
| std::stable_sort(records.begin(), records.end(), | |
| [](const SavedActionRecord& a, const SavedActionRecord& b) { | |
| bool final_a = AtEndState(a.actions()); | |
| bool final_b = AtEndState(b.actions()); | |
| if (final_a != final_b) { | |
| // If a is in a final state, it is "<" b, which is not. | |
| // If a is _not_ in a final state, b is, and a ">" b. | |
| return final_a; | |
| } | |
| // In ascending time, so oldest to youngest | |
| auto time_a = getChangeTime(a.actions()); | |
| auto time_b = getChangeTime(b.actions()); | |
| return (time_a.seconds() < time_b.seconds()) || | |
| (time_a.seconds() == time_b.seconds() && | |
| time_a.nanos() < time_b.nanos()); | |
| }); | |
| // erase the oldest protos, keeping proto_keep_number_ protos | |
| LOG(INFO) << "cleaning up the saved protos"; | |
| LOG(INFO) << "current:" << records.size(); | |
| LOG(INFO) << "keeping:" << proto_keep_number_; | |
| const size_t num_to_delete = records.size() - proto_keep_number_; | |
| LOG(INFO) << "deleting:" << num_to_delete; | |
| if (proto_keep_number_ > records.size()) { | |
| LOG(INFO) << "keeping all protos"; | |
| return absl::OkStatus(); | |
| } | |
| auto end_delete = std::next(records.begin(), num_to_delete); | |
| for (auto i = records.begin(); i != end_delete; i++) { | |
| FlightRecordWrapper action_to_delete( | |
| i->actions().original_request().flight_record()); | |
| // In ideal circumstances, only actions that are completed are deleted. | |
| if (AtEndState(i->actions())) { | |
| LOG(INFO) << "deleting end-state action record:" << action_to_delete; | |
| } else { | |
| LOG(ERROR) << "deleting an unfinished action record:" << action_to_delete; | |
| } | |
| map.erase(action_to_delete); | |
| } | |
| return absl::OkStatus(); | |
| } | |
| // find the largest file id, and return it | |
| // the file id is a number, and the file name is in the format of | |
| // "savedactions_1" | |
| // "savedactions_2" | |
| // where the largest id is the most recent file | |
| std::optional<uint64_t> PersistentStorageManagerImpl::findLargestFileId( | |
| absl::Span<const std::string> files) { | |
| std::optional<uint64_t> largest_id; | |
| for (const auto& entry : files) { | |
| std::vector<absl::string_view> file_name_parts = absl::StrSplit(entry, '_'); | |
| if (file_name_parts.size() != 2) { | |
| LOG(WARNING) << "unable to parse the file name in the directory " << entry | |
| << " size:" << file_name_parts.size(); | |
| continue; | |
| } | |
| uint64_t file_id; | |
| if (!absl::SimpleAtoi(file_name_parts[1], &file_id)) { | |
| LOG(WARNING) << "unable to parse the file ID as unint64_t" << entry; | |
| continue; | |
| } | |
| if (file_name_parts[0] != kfileNamePrefix) { | |
| LOG(WARNING) << "unknown file name prefix" << entry; | |
| continue; | |
| } | |
| if (!largest_id.has_value() || file_id > *largest_id) { | |
| largest_id = file_id; | |
| } | |
| } | |
| return largest_id; | |
| } | |
| absl::StatusOr<std::vector<std::string> > | |
| PersistentStorageManagerImpl::listFiles(absl::string_view file_path) { | |
| // check if the file path exists and is a directory | |
| std::error_code ec_is_directory; | |
| bool is_directory = std::filesystem::is_directory(file_path, ec_is_directory); | |
| if (ec_is_directory) { | |
| const std::string error_message = | |
| absl::StrCat("Failed to check if file is a directory ", file_path, | |
| " error:", ec_is_directory.message()); | |
| LOG(ERROR) << error_message; | |
| return absl::InternalError(error_message); | |
| } | |
| if (!is_directory) { | |
| const std::string error_message = | |
| absl::StrCat("File path is not a directory:", file_path, | |
| "is_directory: ", is_directory); | |
| LOG(ERROR) << error_message; | |
| return absl::InternalError(error_message); | |
| } | |
| // list the files in the directory | |
| std::vector<std::string> files; | |
| std::error_code ec; | |
| std::filesystem::directory_iterator it(file_path, ec), end; | |
| if (ec) { | |
| const std::string error_message = | |
| absl::StrCat("Failed to create directory iterator ", file_path, | |
| " error:", ec.message()); | |
| LOG(ERROR) << error_message; | |
| return absl::InternalError(error_message); | |
| } | |
| while (it != end) { | |
| files.push_back(it->path().filename().string()); | |
| std::error_code ec_increment; | |
| it.increment(ec_increment); | |
| if (ec_increment) { | |
| const std::string error_message = | |
| absl::StrCat("Failed to iterate the directory ", file_path, | |
| " error:", ec_increment.message()); | |
| LOG(ERROR) << error_message; | |
| return absl::InternalError(error_message); | |
| } | |
| } | |
| return files; | |
| } | |
| absl::Status PersistentStorageManagerImpl::deleteAllFilesExceptLargest( | |
| absl::string_view file_path) { | |
| auto files = listFiles(file_path); | |
| if (!files.ok()) { | |
| return files.status(); | |
| } | |
| std::optional<uint64_t> largest = findLargestFileId(files.value()); | |
| if (!largest.has_value()) { | |
| LOG(ERROR) | |
| << "No largest file found, but expected to find files to delete."; | |
| return absl::OkStatus(); | |
| } | |
| const std::string largest_file_name = MakeFileName(largest.value()); | |
| for (const auto& entry : files.value()) { | |
| if (entry == largest_file_name) { | |
| continue; | |
| } | |
| const std::string del_path = absl::StrCat(file_path, "/", entry); | |
| std::error_code ec; | |
| bool removed = std::filesystem::remove(del_path, ec); | |
| if (!removed || ec) { | |
| LOG(ERROR) << "Failed to delete the file " << del_path | |
| << "remove result:" << removed << " error:" << ec.message(); | |
| return absl::InternalError(absl::StrCat( | |
| "Failed to delete file: ", del_path, " error:", ec.message())); | |
| } | |
| } | |
| return absl::OkStatus(); | |
| } | |
| absl::Status PersistentStorageManagerImpl::InitializeSavedActions() { | |
| absl::MutexLock lock(mu_); | |
| std::error_code ec; | |
| if (!std::filesystem::is_directory(dir_path_, ec)) { | |
| return absl::FailedPreconditionError( | |
| absl::StrCat("Directory does not exist: ", dir_path_)); | |
| } | |
| if (ec) { | |
| const std::string error_message = | |
| absl::StrCat("Failed to check if directory exists ", dir_path_, | |
| " error:", ec.message()); | |
| LOG(ERROR) << error_message; | |
| return absl::InternalError(error_message); | |
| } | |
| std::filesystem::directory_iterator it(dir_path_, ec), end; | |
| if (ec) { | |
| const std::string error_message = | |
| absl::StrCat("Failed to create directory iterator ", dir_path_, | |
| " error:", ec.message()); | |
| LOG(ERROR) << error_message; | |
| return absl::InternalError(error_message); | |
| } | |
| while (it != end) { | |
| const std::filesystem::path& file = it->path(); | |
| std::error_code remove_ec; | |
| bool removed = std::filesystem::remove(file, remove_ec); | |
| if (!removed || remove_ec) { | |
| const std::string error_message = | |
| absl::StrCat("Failed to delete the file ", file.string(), | |
| ": error:", remove_ec.message()); | |
| LOG(ERROR) << error_message; | |
| return absl::UnavailableError(error_message); | |
| } | |
| LOG(WARNING) << "Deleted " << file.string(); | |
| std::error_code ec_increment; | |
| it.increment(ec_increment); | |
| if (ec_increment) { | |
| LOG(ERROR) << "Failed to iterate the directory " << dir_path_ | |
| << " error:" << ec_increment.message(); | |
| return absl::InternalError(absl::StrCat( | |
| "Failed to iterate the directory, file_path: ", dir_path_, | |
| " error:", ec_increment.message())); | |
| } | |
| } | |
| return absl::OkStatus(); | |
| } | |
| std::string PersistentStorageManagerImpl::MakeFileName(const uint64_t file_id) { | |
| return absl::StrCat(kfileNamePrefix, "_", std::to_string(file_id)); | |
| } | |
| std::string PersistentStorageManagerImpl::MakeFilePath( | |
| absl::string_view dir_path, const uint64_t file_id) { | |
| return absl::StrCat(dir_path, "/", MakeFileName(file_id)); | |
| } | |
| } // namespace persistent_storage |