Import g3_shared_lib: boottime_api. The boottime_api is a shared library separate from boot-time-monitor which managing api and resource usage for several daemons of Deoxys for code reusability. Including bmcweb, grpc-blob, boot-time-monitor. Also removed the test/api_test.cpp since it's already moved to the g3_shared_lib. Test result: - multi-hosts: https://paste.googleplex.com/5984440182112256 - multi-hosts with mixed sequence and `TrayPowerCycle`: https://paste.googleplex.com/6198410016980992 Google-Bug-Id: 398991424 Change-Id: I520a4d696cd72f2bcaeb897c00a9f40d50eafa0c Signed-off-by: Jack Huang <huangweichieh@google.com>
diff --git a/include/api.hpp b/include/api.hpp deleted file mode 100644 index c35dc3c..0000000 --- a/include/api.hpp +++ /dev/null
@@ -1,207 +0,0 @@ -#pragma once - -#include "node_config.hpp" -#include "resource.hpp" - -#include <map> -#include <memory> -#include <string_view> - -namespace boot_time_monitor -{ - -namespace api -{ - -namespace btm = boot_time_monitor; - -/** - * @brief Interface for managing boot time monitoring data for different nodes. - * - * This interface defines the contract for setting and retrieving boot - * checkpoints and durations for specific nodes or groups of nodes identified - * by tags. It also handles notifications for boot completion and provides - * methods to check the reboot status of a node. - */ -class IApi -{ - public: - virtual ~IApi() = default; - - /** - * @brief Sets a boot checkpoint for a specific node. - * - * @param nodeConfig The configuration of the target node. - * @param checkpointName The name of the checkpoint. - * @param wallTime The wall clock time (epoch time in ms) when the - * checkpoint was reached. If 0, the current time is used. - * @param selfMeasuredDuration The duration (in ms) measured by the - * component reporting the checkpoint. If - * non-zero, an additional checkpoint marking the beginning of this duration - * might be recorded. - */ - virtual void SetNodeCheckpoint(const btm::NodeConfig& nodeConfig, - std::string_view checkpointName, - int64_t wallTime, - int64_t selfMeasuredDuration) = 0; - - /** - * @brief Sets a boot checkpoint for all nodes matching a specific tag. - * - * @param tag The tag to identify the target nodes. - * @param checkpointName The name of the checkpoint. - * @param wallTime The wall clock time (epoch time in ms) when the - * checkpoint was reached. If 0, the current time is used. - * @param selfMeasuredDuration The duration (in ms) measured by the - * component reporting the checkpoint. - */ - virtual void SetNodesCheckpointByTag(std::string_view tag, - std::string_view checkpointName, - int64_t wallTime, - int64_t selfMeasuredDuration) = 0; - - /** - * @brief Sets a boot duration measurement for a specific node. - * - * @param nodeConfig The configuration of the target node. - * @param durationName The name of the duration measurement. - * @param duration The measured duration in milliseconds. - */ - virtual void SetNodeDuration(const btm::NodeConfig& nodeConfig, - std::string_view durationName, - int64_t duration) = 0; - - /** - * @brief Sets a boot duration measurement for all nodes matching a specific - * tag. - * - * @param tag The tag to identify the target nodes. - * @param durationName The name of the duration measurement. - * @param duration The measured duration in milliseconds. - */ - virtual void SetNodesDurationByTag(std::string_view tag, - std::string_view durationName, - int64_t duration) = 0; - - /** - * @brief Sets a Power Supply Unit (PSU) related boot checkpoint for all - * nodes. PSU events are typically broadcast to all nodes. - * - * @param checkpointName The name of the PSU checkpoint. - * @param wallTime The wall clock time (epoch time in ms). - * @param selfMeasuredDuration The self-measured duration (in ms). - */ - virtual void SetPSUCheckpoint(std::string_view checkpointName, - int64_t wallTime, - int64_t selfMeasuredDuration) = 0; - - /** - * @brief Sets a Power Supply Unit (PSU) related boot duration for all - * nodes. PSU events are typically broadcast to all nodes. - * - * @param durationName The name of the PSU duration. - * @param duration The measured duration in milliseconds. - */ - virtual void SetPSUDuration(std::string_view durationName, - int64_t duration) = 0; - - /** - * @brief Notifies that the boot process for a specific node is complete. - * This typically involves finalizing the current boot record. - * - * @param nodeConfig The configuration of the completed node. - */ - virtual void NotifyNodeComplete(const btm::NodeConfig& nodeConfig) = 0; - - /** - * @brief Notifies that the boot process for all nodes matching a specific - * tag is complete. - * - * @param tag The tag identifying the completed nodes. - */ - virtual void NotifyNodesCompleteByTag(std::string_view tag) = 0; - - /** - * @brief Retrieves the list of recorded checkpoints for a specific node. - * - * @param nodeConfig The configuration of the target node. - * @return A vector of tuples, each containing (checkpoint name, wall time - * ms, monotonic time ms). - */ - virtual std::vector<std::tuple<std::string, int64_t, int64_t>> - GetNodeCheckpointList(const btm::NodeConfig& nodeConfig) = 0; - - /** - * @brief Retrieves the list of recorded additional durations for a specific - * node. - * - * @param nodeConfig The configuration of the target node. - * @return A vector of tuples, each containing (duration name, duration ms). - */ - virtual std::vector<std::tuple<std::string, int64_t>> - GetNodeAdditionalDurations(const btm::NodeConfig& nodeConfig) = 0; - - /** - * @brief Checks if a specific node is currently in the process of - * rebooting. - * - * @param nodeConfig The configuration of the target node. - * @return True if the node is considered to be rebooting, false otherwise. - */ - virtual bool IsNodeRebooting(const btm::NodeConfig& nodeConfig) = 0; -}; - -/** - * @brief Concrete implementation of the IApi interface. - * - * This class manages multiple `IResource` instances (one per node) - * and provides thread-safe access to them via a mutex. It acts as the central - * point for interacting with boot time data storage. - */ -class Api : public IApi -{ - public: - ~Api() override; - void SetNodeCheckpoint(const btm::NodeConfig& nodeConfig, - std::string_view checkpointName, int64_t wallTime, - int64_t selfMeasuredDuration) override; - void SetNodesCheckpointByTag(std::string_view tag, - std::string_view checkpointName, - int64_t wallTime, - int64_t selfMeasuredDuration) override; - void SetNodeDuration(const btm::NodeConfig& nodeConfig, - std::string_view durationName, - int64_t duration) override; - void SetNodesDurationByTag(std::string_view tag, - std::string_view durationName, - int64_t duration) override; - void SetPSUCheckpoint(std::string_view checkpointName, int64_t wallTime, - int64_t selfMeasuredDuration) override; - void SetPSUDuration(std::string_view durationName, - int64_t duration) override; - void NotifyNodeComplete(const btm::NodeConfig& nodeConfig) override; - void NotifyNodesCompleteByTag(std::string_view tag) override; - std::vector<std::tuple<std::string, int64_t, int64_t>> - GetNodeCheckpointList(const btm::NodeConfig& nodeConfig) override; - std::vector<std::tuple<std::string, int64_t>> - GetNodeAdditionalDurations(const btm::NodeConfig& nodeConfig) override; - bool IsNodeRebooting(const btm::NodeConfig& nodeConfig) override; - - /** - * @brief Registers a new node with the API. - * - * This creates a corresponding resource handler (e.g., a File resource) - * for the given node configuration. - * - * @param nodeConfig The configuration of the node to register. - */ - void RegisterNode(const btm::NodeConfig& nodeConfig); - - private: - // Map storing the resource handler for each registered node. - std::map<NodeConfig, std::unique_ptr<resource::IResource>> mResourceMap; - std::mutex mApiMutex; // An api mutex is required for protecting - // misordering of the record. -}; -} // namespace api -} // namespace boot_time_monitor
diff --git a/include/dbus_handler.hpp b/include/dbus_handler.hpp index b8d39e1..af689e5 100644 --- a/include/dbus_handler.hpp +++ b/include/dbus_handler.hpp
@@ -1,5 +1,5 @@ #pragma once -#include "api.hpp" +#include "boottime_api/boottime_api.h" #include <fmt/printf.h> @@ -37,7 +37,7 @@ * This class implements the D-Bus interfaces for Checkpoint, Duration, and * Statistic defined under `xyz.openbmc_project.Time.Boot`. It acts as a * bridge between incoming D-Bus calls and the underlying boot time monitoring - * API (`api::IApi`). Each instance of this handler is associated with a + * API (`api::IBoottimeApi`). Each instance of this handler is associated with a * specific node configuration (`NodeConfig`) and interacts with the central API * to record or retrieve boot time data for that node. */ @@ -60,7 +60,7 @@ */ Handler(sdbusplus::bus::bus& dbus, const btm::NodeConfig& nodeConfig, const btm::dbus::DbusConfig& dbusConfig, - std::shared_ptr<btm::api::IApi> api); + std::shared_ptr<btm::api::IBoottimeApi> api); /** * @brief D-Bus method implementation for setting a boot checkpoint. @@ -127,7 +127,7 @@ /** @brief Configuration of the node associated with this handler. */ NodeConfig mNodeConfig; /** @brief Shared pointer to the central boot time monitoring API. */ - std::shared_ptr<api::IApi> mApi; + std::shared_ptr<api::IBoottimeApi> mApi; }; } // namespace dbus } // namespace boot_time_monitor
diff --git a/include/gen.hpp b/include/gen.hpp index e7c51c7..8ba5e54 100644 --- a/include/gen.hpp +++ b/include/gen.hpp
@@ -1,7 +1,7 @@ #pragma once +#include "boottime_api/node_config.h" #include "dbus_handler.hpp" -#include "node_config.hpp" #include "psm_handler.hpp" #include <fmt/printf.h>
diff --git a/include/log.hpp b/include/log.hpp new file mode 100644 index 0000000..3df4335 --- /dev/null +++ b/include/log.hpp
@@ -0,0 +1,27 @@ +#pragma once +#include "boottime_api/boottime_api.h" + +#include <fmt/printf.h> + +namespace boot_time_monitor +{ +namespace log +{ +/** + * @brief Logs an error message to stderr if the given status is not OK. + * + * This is a utility function that checks an `absl::Status` object. If the + * status represents an error condition (`!status.ok()`), the function + * prints the detailed error string to the standard error stream. + * + * @param status The `absl::Status` to check. + */ +inline void LogIfError(const absl::Status& status) +{ + if (!status.ok()) + { + fmt::print(stderr, "{}\n", status.ToString()); + } +} +} // namespace log +} // namespace boot_time_monitor
diff --git a/include/node_config.hpp b/include/node_config.hpp deleted file mode 100644 index 5899481..0000000 --- a/include/node_config.hpp +++ /dev/null
@@ -1,65 +0,0 @@ -#pragma once - -#include <iostream> -#include <string> -#include <string_view> - -namespace boot_time_monitor -{ -/** @brief Tag identifying a BMC node. Used for grouping operations. */ -inline constexpr std::string_view kBootTimeTagBMC = "BMC"; -/** @brief Tag identifying a Host node. Used for grouping operations. */ -inline constexpr std::string_view kBootTimeTagHost = "Host"; - -/** - * @brief Represents the configuration for a specific node being monitored. - * - * This structure holds the unique name of a node (e.g., "host0", "bmc") and - * an optional tag (e.g., "Host", "BMC") used for grouping nodes. It provides - * comparison operators for use in containers like `std::map` and an output - * stream operator for easy printing. - */ -struct NodeConfig -{ - /** - * @brief The unique identifier name for the node (e.g., "host0", "bmc"). - */ - std::string nodeName; - /** @brief An optional tag for grouping nodes (e.g., "Host", "BMC"). */ - std::string tag; - - /** - * @brief Less-than comparison operator based on `nodeName`. - * @param other The NodeConfig to compare against. - * @return True if this nodeName is lexicographically less than - * other.nodeName. - */ - bool operator<(const NodeConfig& other) const - { - return nodeName < other.nodeName; - } - - /** - * @brief Equality comparison operator based on `nodeName`. - * @param other The NodeConfig to compare against. - * @return True if nodeNames are equal. - */ - bool operator==(const NodeConfig& other) const - { - return nodeName == other.nodeName; - } - - /** - * @brief Output stream operator for printing the NodeConfig. - * @param os The output stream. - * @param k The NodeConfig object to print. - * @return The output stream with the NodeConfig printed in the format: - * `{"<nodeName>", "<tag>"}`. - */ - friend std::ostream& operator<<(std::ostream& os, const NodeConfig& k) - { - os << "{\"" << k.nodeName << "\", \"" << k.tag << "\"}"; - return os; - } -}; -} // namespace boot_time_monitor
diff --git a/include/psm_handler.hpp b/include/psm_handler.hpp index db2b5ab..d00d83b 100644 --- a/include/psm_handler.hpp +++ b/include/psm_handler.hpp
@@ -1,7 +1,7 @@ #pragma once -#include "api.hpp" -#include "node_config.hpp" +#include "boottime_api/boottime_api.h" +#include "boottime_api/node_config.h" #include <boost/container/flat_map.hpp> #include <sdbusplus/bus.hpp> @@ -72,7 +72,7 @@ */ Handler(sdbusplus::bus::bus& bus, const btm::NodeConfig& nodeConfig, const btm::psm::PSMConfig& psmConfig, - std::shared_ptr<btm::api::IApi> api); + std::shared_ptr<btm::api::IBoottimeApi> api); private: /** @brief D-Bus match rule watcher for Host State property changes. */ @@ -88,7 +88,7 @@ /** @brief Configuration of the node associated with this handler. */ btm::NodeConfig mNodeConfig; /** @brief Shared pointer to the central boot time monitoring API. */ - std::shared_ptr<btm::api::IApi> mApi; + std::shared_ptr<btm::api::IBoottimeApi> mApi; }; } // namespace psm } // namespace boot_time_monitor
diff --git a/include/resource.hpp b/include/resource.hpp deleted file mode 100644 index 75e5d52..0000000 --- a/include/resource.hpp +++ /dev/null
@@ -1,282 +0,0 @@ -#pragma once - -#include <fstream> -#include <memory> -#include <mutex> -#include <optional> -#include <string_view> -#include <vector> - -namespace boot_time_monitor -{ - -/** - * @brief Contains interfaces and implementations for resource management (data - * storage). - * - * This namespace defines how boot time data (checkpoints and durations) is - * stored and retrieved. Currently, it provides a file-based implementation. - */ -namespace resource -{ - -namespace btm = boot_time_monitor; - -/** @brief Default directory for storing boot time monitor data files. */ -extern std::string BTMonitorDir; - -/** @brief Reboot complete checkpoint name */ -const std::string kRebootCompleteCheckpoint = "RebootEnd"; -/** @brief Suffix appended to filenames when a boot cycle is completed. */ -const std::string kCompletedSuffix = ".completed"; -/** @brief Suffix added to a checkpoint name to indicate the start of a - * self-measured duration. */ -const std::string kBeginStageSuffix = ":BEGIN"; -/** @brief Base filename for storing checkpoint data. */ -const std::string kCheckpointFile = "checkpoints.csv"; -/** @brief Base filename for storing duration data. */ -const std::string kDurationFile = "durations.csv"; - -/** - * @brief Represents a single boot checkpoint record. - */ -struct Checkpoint -{ - /** @brief The name identifying the checkpoint. */ - std::string name; - /** @brief The wall clock time (epoch time in ms) when the checkpoint was - * reached. */ - int64_t wallTime; - /** @brief The monotonic clock time (uptime in ms) when the checkpoint was - * reached. */ - int64_t monoTime; - - /** @brief Constructs a Checkpoint object. */ - Checkpoint(std::string name, int64_t wallTime, int64_t monoTime) : - name(std::move(name)), wallTime(wallTime), monoTime(monoTime) - {} -}; - -/** - * @brief Represents a single boot duration measurement record. - */ -struct Duration -{ - /** @brief The name identifying the duration measurement. */ - std::string name; - /** @brief The measured duration in milliseconds. */ - int64_t duration; - - /** @brief Constructs a Duration object. */ - Duration(std::string name, int64_t duration) : - name(std::move(name)), duration(duration) - {} -}; - -/** - * @brief Interface for managing boot time data storage for a single node. - * - * Defines the contract for storing checkpoints and durations, retrieving cached - * data, marking a boot cycle as complete, and checking the current reboot - * status. - */ -class IResource -{ - public: - virtual ~IResource() = default; - - /** - * @brief Records a boot checkpoint. - * - * @param name The name of the checkpoint. - * @param epochTime The wall clock time (epoch time in ms). If 0, current - * time is used. - * @param duration The self-measured duration (in ms). If non-zero, a - * ":BEGIN" checkpoint might be added. - */ - virtual void SetCheckpoint(std::string_view name, int64_t epochTime, - int64_t duration) = 0; - - /** - * @brief Records a boot duration measurement. - * - * @param name The name of the duration measurement. - * @param duration The measured duration in milliseconds. - */ - virtual void SetDuration(std::string_view name, int64_t duration) = 0; - - /** - * @brief Retrieves the cached list of checkpoints for the current or last - * completed boot. - * - * @return A vector of Checkpoint objects. Returns current boot data if - * IsRebooting() is true, otherwise returns data from the last completed - * boot. - */ - virtual std::vector<btm::resource::Checkpoint> GetCheckpointCache() = 0; - - /** - * @brief Retrieves the cached list of durations for the current or last - * completed boot. - * - * @return A vector of Duration objects. Returns current boot data if - * IsRebooting() is true, otherwise returns data from the last completed - * boot. - */ - virtual std::vector<btm::resource::Duration> GetDurationCache() = 0; - - /** - * @brief Marks the current boot cycle as complete. - * This typically involves finalizing storage (e.g., renaming files) - * and clearing current caches. - */ - virtual void MarkComplete() = 0; - - /** - * @brief Checks if the node is currently considered to be in a reboot - * cycle. - * - * @return True if data is being actively recorded for the current boot, - * false otherwise. - */ - virtual bool IsRebooting() = 0; -}; - -/** - * @brief File-based implementation of the IResource interface. - * - * Stores checkpoint and duration data in separate CSV files per node. - * Manages current boot data and data from the last completed boot cycle. - * Provides caching for efficient retrieval. - */ -class File : public IResource -{ - public: - /** - * @brief Constructs a File resource handler for a specific node. - * - * Initializes file streams and loads data from existing files (current and - * completed). - * - * @param nodeName The name of the node this resource belongs to. - */ - explicit File(std::string_view nodeName); - - ~File() override = default; - - // Declare noncopyable - File(const File&) = delete; - File& operator=(const File&) = delete; - - // Declare nonmoveable - File(File&&) = delete; - File& operator=(File&&) = delete; - - /** @copydoc IResource::SetCheckpoint */ - void SetCheckpoint(std::string_view name, int64_t epochTime, - int64_t duration) override; - - /** @copydoc IResource::SetDuration */ - void SetDuration(std::string_view name, int64_t duration) override; - - /** @copydoc IResource::GetCheckpointCache */ - std::vector<btm::resource::Checkpoint> GetCheckpointCache() override; - - /** @copydoc IResource::GetDurationCache */ - std::vector<btm::resource::Duration> GetDurationCache() override; - - /** @copydoc IResource::MarkComplete */ - void MarkComplete() override; - - /** @copydoc IResource::IsRebooting */ - bool IsRebooting() override; - - private: - /** @brief Mutex protecting file access and cache modifications. */ - std::mutex mFileMutex; - /** @brief The name of the node associated with this resource. */ - std::string mNodeName; - /** @brief Output file stream for the current checkpoint file. */ - std::ofstream mCpOfs; - /** @brief Output file stream for the current duration file. */ - std::ofstream mDurOfs; - /** @brief Cache for checkpoints recorded during the current boot cycle. */ - std::vector<btm::resource::Checkpoint> mCheckpointCache; - /** @brief Cache for checkpoints from the last completed boot cycle. */ - std::vector<btm::resource::Checkpoint> mCheckpointCompletedCache; - /** @brief Cache for durations recorded during the current boot cycle. */ - std::vector<btm::resource::Duration> mDurationCache; - /** @brief Cache for durations from the last completed boot cycle. */ - std::vector<btm::resource::Duration> mDurationCompletedCache; - - /** - * @brief Appends a checkpoint record to the current checkpoint file and - * cache. - * @param name Checkpoint name. - * @param wallTimeInMs Wall clock time (ms). - * @param monoTimeInMs Monotonic clock time (ms). - */ - void AppendCheckpointToFile(const std::string& name, int64_t wallTimeInMs, - int64_t monoTimeInMs); - /** - * @brief Appends a duration record to the current duration file and cache. - * @param name Duration name. - * @param durationInMs Duration value (ms). - */ - void AppendDurationToFile(const std::string& name, int64_t durationInMs); - /** - * @brief Opens or creates a file for appending and returns the stream. - * @param filename Full path to the file. - * @return std::ofstream The opened file stream. - * @throws std::invalid_argument if the stream cannot be opened. - */ - std::ofstream StartFileInstance(std::string_view filename); - /** - * @brief Finalizes a data file by closing it and renaming it with the - * ".complete" suffix. Reopens the original filename for the next boot. - * @param ofs The output stream to close and manage. - * @param filename The base filename (without suffix). - */ - void CompleteCurrentFile(std::ofstream& ofs, const std::string& filename); - /** - * @brief Checks if the file associated with the stream is currently empty. - * @param ofs The output stream to check. - * @return True if the file is empty, false otherwise. - * @throws std::runtime_error if `tellp` fails. - */ - bool IsEmptyFile(std::ofstream& ofs); - /** - * @brief Loads checkpoint data from a specified file (current or - * completed). - * @param loadComplete If true, loads from the ".complete" file; otherwise, - * loads from the current file. - * @return std::vector<btm::resource::Checkpoint> The loaded checkpoints. - */ - std::vector<btm::resource::Checkpoint> LoadCheckpoints(bool loadComplete); - /** - * @brief Loads duration data from a specified file (current or completed). - * @param loadComplete If true, loads from the ".complete" file; otherwise, - * loads from the current file. - * @return std::vector<btm::resource::Duration> The loaded durations. - */ - std::vector<btm::resource::Duration> LoadDurations(bool loadComplete); - /** - * @brief Gets the current system uptime in milliseconds from /proc/uptime. - * @return std::optional<int64_t> Uptime in ms, or std::nullopt if reading - * fails. - */ - static std::optional<int64_t> GetUpTimeInMs(); - - /** @brief Gets the current wall clock time (epoch) in milliseconds. */ - static inline int64_t GetWallTimeInMs(); - /** @brief Validates if a name contains only allowed characters - * ([0-9a-zA-Z_:]). */ - static inline bool IsValidName(std::string_view name); - /** @brief Constructs the full path for the checkpoint file for this node. - */ - inline std::string GetCpFullFileName(); - /** @brief Constructs the full path for the duration file for this node. */ - inline std::string GetDurFullFileName(); -}; -} // namespace resource -} // namespace boot_time_monitor
diff --git a/include/systemd_handler.hpp b/include/systemd_handler.hpp index 4b5a0e0..da2e625 100644 --- a/include/systemd_handler.hpp +++ b/include/systemd_handler.hpp
@@ -1,6 +1,6 @@ #pragma once -#include "api.hpp" +#include "boottime_api/boottime_api.h" #include <boost/asio/steady_timer.hpp> #include <sdbusplus/asio/connection.hpp> @@ -47,7 +47,7 @@ * @param api Shared pointer to the central boot time monitoring API. */ Handler(std::shared_ptr<sdbusplus::asio::connection> conn, - std::shared_ptr<btm::api::IApi> api); + std::shared_ptr<btm::api::IBoottimeApi> api); private: /** @brief Interval for polling systemd properties until boot is finished. @@ -68,7 +68,7 @@ std::shared_ptr<sdbusplus::asio::connection>& conn); /** @brief Shared pointer to the central boot time monitoring API. */ - std::shared_ptr<btm::api::IApi> mApi; + std::shared_ptr<btm::api::IBoottimeApi> mApi; /** @brief ASIO timer used to periodically check for systemd boot * completion. */ boost::asio::steady_timer mBMCFinishTimer;
diff --git a/src/api.cpp b/src/api.cpp deleted file mode 100644 index f7faa4d..0000000 --- a/src/api.cpp +++ /dev/null
@@ -1,200 +0,0 @@ -#include "api.hpp" - -#include <fmt/printf.h> - -namespace boot_time_monitor -{ - -namespace api -{ - -namespace btm = boot_time_monitor; - -Api::~Api() = default; - -void Api::SetNodeCheckpoint(const btm::NodeConfig& nodeConfig, - std::string_view checkpointName, int64_t wallTime, - int64_t selfMeasuredDuration) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.find(nodeConfig); - - if (it == mResourceMap.end()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - nodeConfig.nodeName); - return; - } - - it->second->SetCheckpoint(checkpointName, wallTime, selfMeasuredDuration); -} - -void Api::SetNodeDuration(const btm::NodeConfig& nodeConfig, - std::string_view durationName, int64_t duration) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.find(nodeConfig); - - if (it == mResourceMap.end()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - nodeConfig.nodeName); - return; - } - - it->second->SetDuration(durationName, duration); -} - -void Api::SetNodesCheckpointByTag(std::string_view tag, - std::string_view checkpointName, - int64_t wallTime, - int64_t selfMeasuredDuration) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - for (const auto& [config, node] : mResourceMap) - { - if (config.tag == tag) - { - node.get()->SetCheckpoint(checkpointName, wallTime, - selfMeasuredDuration); - } - } -} - -void Api::SetNodesDurationByTag(std::string_view tag, - std::string_view durationName, int64_t duration) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - for (const auto& [config, node] : mResourceMap) - { - if (config.tag == tag) - { - node.get()->SetDuration(durationName, duration); - } - } -} - -void Api::SetPSUCheckpoint(std::string_view checkpointName, int64_t wallTime, - int64_t selfMeasuredDuration) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - // For "Power Supply Unit" checkpoint should broadcast to all nodes. - for (const auto& [_, node] : mResourceMap) - { - node.get()->SetCheckpoint(checkpointName, wallTime, - selfMeasuredDuration); - } -} - -void Api::SetPSUDuration(std::string_view durationName, int64_t duration) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - // For "Power Supply Unit" duration should broadcast to all nodes. - for (const auto& [_, node] : mResourceMap) - { - node.get()->SetDuration(durationName, duration); - } -} - -void Api::NotifyNodeComplete(const btm::NodeConfig& nodeConfig) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.find(nodeConfig); - - if (it == mResourceMap.end()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - nodeConfig.nodeName); - return; - } - - it->second->MarkComplete(); -} - -void Api::NotifyNodesCompleteByTag(std::string_view tag) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - for (const auto& [config, node] : mResourceMap) - { - if (config.tag == tag) - { - node.get()->MarkComplete(); - } - } -} - -std::vector<std::tuple<std::string, int64_t, int64_t>> - Api::GetNodeCheckpointList(const btm::NodeConfig& nodeConfig) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.find(nodeConfig); - - if (it == mResourceMap.end()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - nodeConfig.nodeName); - return {}; - } - - std::vector<std::tuple<std::string, int64_t, int64_t>> result; - - for (const auto& cp : it->second->GetCheckpointCache()) - { - result.emplace_back(std::make_tuple(cp.name, cp.wallTime, cp.monoTime)); - } - - return result; -} -std::vector<std::tuple<std::string, int64_t>> - Api::GetNodeAdditionalDurations(const btm::NodeConfig& nodeConfig) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.find(nodeConfig); - - if (it == mResourceMap.end()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - nodeConfig.nodeName); - return {}; - } - - std::vector<std::tuple<std::string, int64_t>> result; - - for (const auto& dur : it->second->GetDurationCache()) - { - result.emplace_back(std::make_tuple(dur.name, dur.duration)); - } - - return result; -} - -bool Api::IsNodeRebooting(const btm::NodeConfig& nodeConfig) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.find(nodeConfig); - - if (it == mResourceMap.end()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - nodeConfig.nodeName); - return false; - } - - return it->second->IsRebooting(); -} - -void Api::RegisterNode(const btm::NodeConfig& nodeConfig) -{ - std::lock_guard<std::mutex> guard(mApiMutex); - auto it = mResourceMap.try_emplace( - nodeConfig, std::make_unique<resource::File>(nodeConfig.nodeName)); - - if (!it.second) - { - fmt::print( - "[{}] Failed to register `{}` due to the key duplicated. Skip it.\n", - __FUNCTION__, nodeConfig.nodeName); - } -} -} // namespace api -} // namespace boot_time_monitor
diff --git a/src/dbus_handler.cpp b/src/dbus_handler.cpp index 6ab184c..2451de7 100644 --- a/src/dbus_handler.cpp +++ b/src/dbus_handler.cpp
@@ -1,5 +1,7 @@ #include "dbus_handler.hpp" +#include "log.hpp" + namespace boot_time_monitor { namespace dbus @@ -12,7 +14,7 @@ Handler::Handler(sdbusplus::bus::bus& dbus, const btm::NodeConfig& nodeConfig, const btm::dbus::DbusConfig& dbusConfig, - std::shared_ptr<btm::api::IApi> api) : + std::shared_ptr<btm::api::IBoottimeApi> api) : sdbusplus::server::object::object<Duration>(dbus, dbusConfig.dbusObjPath.c_str()), sdbusplus::server::object::object<Checkpoint>( @@ -27,12 +29,15 @@ { if (checkpointName == kPSUCheckpointName) { - mApi->SetPSUCheckpoint(checkpointName, wallTime, selfMeasuredDuration); + absl::Status status = mApi->SetPSUCheckpoint(checkpointName, wallTime, + selfMeasuredDuration); + btm::log::LogIfError(status); } else { - mApi->SetNodeCheckpoint(mNodeConfig, checkpointName, wallTime, - selfMeasuredDuration); + absl::Status status = mApi->SetNodeCheckpoint( + mNodeConfig, checkpointName, wallTime, selfMeasuredDuration); + btm::log::LogIfError(status); } } @@ -52,18 +57,22 @@ return; } - mApi->NotifyNodeComplete(mNodeConfig); + absl::Status status = mApi->NotifyNodeComplete(mNodeConfig); + btm::log::LogIfError(status); } void Handler::setDuration(std::string durationName, int64_t duration) { if (durationName == kPSUDurationName) { - mApi->SetPSUDuration(durationName, duration); + absl::Status status = mApi->SetPSUDuration(durationName, duration); + btm::log::LogIfError(status); } else { - mApi->SetNodeDuration(mNodeConfig, durationName, duration); + absl::Status status = mApi->SetNodeDuration(mNodeConfig, durationName, + duration); + btm::log::LogIfError(status); } }
diff --git a/src/main.cpp b/src/main.cpp index 35e0e5e..2ae2436 100644 --- a/src/main.cpp +++ b/src/main.cpp
@@ -1,6 +1,8 @@ -#include "api.hpp" +#include "boottime_api/boottime_api.h" + #include "dbus_handler.hpp" #include "gen.hpp" +#include "log.hpp" #include "psm_handler.hpp" #include "systemd_handler.hpp" @@ -103,7 +105,8 @@ std::vector<btm::psm::Handler> psmHandlers; - std::shared_ptr<btm::api::Api> api = std::make_shared<btm::api::Api>(); + std::shared_ptr<btm::api::BoottimeApi> api = + std::make_shared<btm::api::BoottimeApi>(); hostNodeConfigs.reserve(hostCount); for (int i = 0; i < hostCount; i++) @@ -121,7 +124,8 @@ for (auto& nodeConfig : hostNodeConfigs) { - api->RegisterNode(nodeConfig); + absl::Status status = api->RegisterNode(nodeConfig); + btm::log::LogIfError(status); hostDbusHandlers.emplace_back(std::make_unique<btm::dbus::Handler>( bus, nodeConfig, btm::gen::GenDbusConfig(nodeConfig), api)); @@ -132,7 +136,8 @@ for (auto& nodeConfig : bmcNodeConfigs) { - api->RegisterNode(nodeConfig); + absl::Status status = api->RegisterNode(nodeConfig); + btm::log::LogIfError(status); bmcDbusHandlers.emplace_back(std::make_unique<btm::dbus::Handler>( bus, nodeConfig, btm::gen::GenDbusConfig(nodeConfig), api));
diff --git a/src/meson.build b/src/meson.build index 17538c7..28bed51 100644 --- a/src/meson.build +++ b/src/meson.build
@@ -1,5 +1,19 @@ boost_dep = dependency('boost', required : false) phosphor_dbus_interfaces_dep = dependency('phosphor-dbus-interfaces') +boottime_api_dep = dependency('boottime_api') + +# absl Dependencies +abseils = [ + 'base', + 'log', + 'synchronization', + 'status', + 'statusor', +] +abseil_deps = [] +foreach absl : abseils + abseil_deps += dependency('absl_' + absl) +endforeach fmt_dep = dependency('fmt', required: false) if not fmt_dep.found() @@ -21,16 +35,15 @@ phosphor_dbus_interfaces_dep, config_dependencies, boot_time_monitor_dbus_dep, + boottime_api_dep, + abseil_deps, ] boot_time_monitor_lib = static_library( 'boot_time_monitor', - 'api.cpp', 'dbus_handler.cpp', 'psm_handler.cpp', - 'resource.cpp', 'systemd_handler.cpp', - generated_sources, include_directories: boot_time_monitor_incs, implicit_include_directories: false, dependencies: boot_time_monitor_pre,
diff --git a/src/psm_handler.cpp b/src/psm_handler.cpp index ab0ec66..de59e09 100644 --- a/src/psm_handler.cpp +++ b/src/psm_handler.cpp
@@ -1,5 +1,7 @@ #include "psm_handler.hpp" +#include "log.hpp" + #include <fmt/printf.h> #include <variant> @@ -29,7 +31,7 @@ Handler::Handler(sdbusplus::bus::bus& bus, const btm::NodeConfig& nodeConfig, const btm::psm::PSMConfig& psmConfig, - std::shared_ptr<btm::api::IApi> api) : + std::shared_ptr<btm::api::IBoottimeApi> api) : mNodeConfig(nodeConfig), mApi(std::move(api)) { // Initialize mPreHostState @@ -78,8 +80,9 @@ stderr, "[hostStateWatcher] CurrentHostState has changed from {} to {}\n", mPreHostState, curHostState); - mApi->SetNodeCheckpoint(mNodeConfig, - translateHostStateName(curHostState), 0, 0); + absl::Status status = mApi->SetNodeCheckpoint( + mNodeConfig, translateHostStateName(curHostState), 0, 0); + btm::log::LogIfError(status); mPreHostState = curHostState; } }); @@ -133,8 +136,9 @@ stderr, "[osStatusWatcher] curOSStatus has changed from {} to {}\n", mPreOSState, curOSStatus); - mApi->SetNodeCheckpoint(mNodeConfig, translateOSStatus(curOSStatus), - 0, 0); + absl::Status status = mApi->SetNodeCheckpoint( + mNodeConfig, translateOSStatus(curOSStatus), 0, 0); + btm::log::LogIfError(status); mPreOSState = curOSStatus; } });
diff --git a/src/resource.cpp b/src/resource.cpp deleted file mode 100644 index a78e442..0000000 --- a/src/resource.cpp +++ /dev/null
@@ -1,310 +0,0 @@ - -#include "resource.hpp" - -#include <fmt/printf.h> - -#include <chrono> -#include <filesystem> -#include <regex> -#include <string> - -namespace boot_time_monitor -{ - -namespace resource -{ - -namespace fs = std::filesystem; -namespace btm = boot_time_monitor; - -// Definition of the global variable -std::string BTMonitorDir = "/var/google/boot_time_monitor/"; - -constexpr uint32_t kMaxCheckpointCnt = 100; -constexpr uint32_t kMaxDurationCnt = 100; - -File::File(std::string_view nodeName) : mNodeName(nodeName) -{ - mCpOfs = StartFileInstance(GetCpFullFileName()); - mDurOfs = StartFileInstance(GetDurFullFileName()); - - mCheckpointCache = LoadCheckpoints(false); - mDurationCache = LoadDurations(false); - mCheckpointCompletedCache = LoadCheckpoints(true); - mDurationCompletedCache = LoadDurations(true); -} - -void File::SetCheckpoint(std::string_view name, int64_t epochTime, - int64_t duration) -{ - auto wallTime = epochTime == 0 ? GetWallTimeInMs() : epochTime; - auto upTime = GetUpTimeInMs(); - if (upTime == std::nullopt) - { - fmt::print("[{}] Can't get up time. Skip this checkpoint.\n", - __FUNCTION__); - return; - } - if (!IsValidName(name)) - { - fmt::print( - "[{}] Name is invalid. Only allows [0-9a-zA-Z_:] but get: {}\n", - __FUNCTION__, name); - return; - } - - if (mCheckpointCache.size() >= kMaxCheckpointCnt) - { - fmt::print("[{}] Drop incoming checkpoint due to hit the limit. " - "name={}, epochTime={}, duration={}\n", - __FUNCTION__, name, epochTime, duration); - return; - } - // `boot_manager` helps to calculate the transition time from one stage to - // next stage if the user can provide a self measured duration for the - // current stage. - // For example, if the interval between checkpoint A and B is 10 seconds and - // the user knows B stage only uses 8 seconds to boot up. Then that means 2 - // seconds transition time was cost from A stage to B stage. - // `duration == 0` means "I don't have self measured duration, so no need to - // calculate transition time for me". - if (duration != 0) - { - AppendCheckpointToFile(std::string(name) + kBeginStageSuffix, - wallTime - duration, upTime.value() - duration); - - if (mCheckpointCache.size() >= kMaxCheckpointCnt) - { - fmt::print( - "[{}] Incoming checkpoint has `duration` so `To_{}` has been " - "created and added. Since the size is full so the incoming " - "checkpoint has been dropped\n", - __FUNCTION__, name); - return; - } - } - - AppendCheckpointToFile(std::string(name), wallTime, upTime.value()); -} - -void File::SetDuration(std::string_view name, int64_t duration) -{ - if (!IsValidName(name)) - { - fmt::print( - "[{}] Name is invalid. Only allows [0-9a-zA-Z_:] but get: {}\n", - __FUNCTION__, name); - return; - } - - if (mDurationCache.size() >= kMaxDurationCnt) - { - fmt::print("[{}] Drop incoming duration due to hit the limit. " - "name={}, duration={}\n", - __FUNCTION__, name, duration); - return; - } - - AppendDurationToFile(std::string(name), duration); -} - -std::vector<btm::resource::Checkpoint> File::GetCheckpointCache() -{ - return IsRebooting() ? mCheckpointCache : mCheckpointCompletedCache; -} - -std::vector<btm::resource::Duration> File::GetDurationCache() -{ - return IsRebooting() ? mDurationCache : mDurationCompletedCache; -} - -void File::MarkComplete() -{ - SetCheckpoint(kRebootCompleteCheckpoint, 0, 0); - std::swap(mCheckpointCompletedCache, mCheckpointCache); - mCheckpointCache.clear(); - std::swap(mDurationCompletedCache, mDurationCache); - mDurationCache.clear(); - - CompleteCurrentFile(mCpOfs, GetCpFullFileName()); - CompleteCurrentFile(mDurOfs, GetDurFullFileName()); -} -bool File::IsRebooting() -{ - return !(IsEmptyFile(mCpOfs) && IsEmptyFile(mDurOfs)); -} - -std::ofstream File::StartFileInstance(std::string_view filename) -{ - std::lock_guard<std::mutex> guard(mFileMutex); - fs::path dir = fs::path(filename).remove_filename(); - if (!dir.empty() && !fs::exists(dir)) - { - fs::create_directories(dir); - } - std::ofstream ofs = std::ofstream(std::string(filename), - std::fstream::out | std::fstream::app); - if (!ofs.good()) - { - throw std::invalid_argument("ofstream is not available."); - } - return ofs; -} - -bool File::IsEmptyFile(std::ofstream& ofs) -{ - std::lock_guard<std::mutex> guard(mFileMutex); - const auto result = ofs.tellp(); - if (result < 0) - { - throw std::runtime_error("File can't be `tellp`"); - } - - return result == 0; -} - -void File::CompleteCurrentFile(std::ofstream& ofs, const std::string& filename) -{ - std::lock_guard<std::mutex> guard(mFileMutex); - ofs.close(); - fs::rename(filename, filename + kCompletedSuffix); - - // Reopen for next reboot - ofs.open(filename.c_str(), std::fstream::out | std::fstream::app); - if (!ofs.good()) - { - throw std::invalid_argument("ofstream is not available."); - } -} - -void File::AppendCheckpointToFile(const std::string& name, int64_t wallTimeInMs, - int64_t monoTimeInMs) -{ - std::lock_guard<std::mutex> guard(mFileMutex); - mCheckpointCache.emplace_back(name, wallTimeInMs, monoTimeInMs); - mCpOfs << name << "," << wallTimeInMs << "," << monoTimeInMs << "\n"; - mCpOfs.flush(); -} - -void File::AppendDurationToFile(const std::string& name, int64_t durationInMs) -{ - std::lock_guard<std::mutex> guard(mFileMutex); - mDurationCache.emplace_back(name, durationInMs); - mDurOfs << name << "," << durationInMs << "\n"; - mDurOfs.flush(); -} - -std::vector<btm::resource::Checkpoint> File::LoadCheckpoints(bool loadCompleted) -{ - std::vector<btm::resource::Checkpoint> result = - std::vector<btm::resource::Checkpoint>(); - std::string cpFilename = GetCpFullFileName() + - (loadCompleted ? kCompletedSuffix : ""); - std::ifstream ifs(cpFilename); - if (!ifs.good()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - cpFilename); - return result; - } - - constexpr uint32_t kBufSize = 1024; - constexpr uint32_t kMatchCount = 4; - - std::array<char, kBufSize> buf; - std::cmatch match; - const std::regex reg("^([0-9a-zA-Z_:]*),([0-9]+),([0-9]+)$"); - while (ifs.getline(buf.data(), kBufSize)) - { - if (regex_match(buf.data(), match, reg)) - { - if (match.size() != kMatchCount) - { - // This line is problematic. Skip it. - continue; - } - - result.emplace_back(match[1].str(), std::stoll(match[2].str()), - std::stoll(match[3].str())); - } - } - return result; -} - -std::vector<btm::resource::Duration> File::LoadDurations(bool loadComplete) -{ - std::vector<btm::resource::Duration> result = - std::vector<btm::resource::Duration>(); - std::string durFilename = GetDurFullFileName() + - (loadComplete ? kCompletedSuffix : ""); - std::ifstream ifs(durFilename); - if (!ifs.good()) - { - fmt::print("[{}] Failed to load `{}`. Skip it.\n", __FUNCTION__, - durFilename); - return result; - } - - constexpr uint32_t kBufSize = 1024; - constexpr uint32_t kMatchCount = 3; - - std::array<char, kBufSize> buf; - std::cmatch match; - const std::regex reg("^([0-9a-zA-Z_:]*),([0-9]+)$"); - while (ifs.getline(buf.data(), kBufSize)) - { - if (regex_match(buf.data(), match, reg)) - { - if (match.size() != kMatchCount) - { - // This line is problematic. Skip it. - continue; - } - - result.emplace_back(match[1].str(), std::stoll(match[2].str())); - } - } - return result; -} - -std::optional<int64_t> File::GetUpTimeInMs() -{ - constexpr int32_t kMillisecondPerSecond = 1000; - std::ifstream fin("/proc/uptime"); - if (!fin.is_open()) - { - fmt::print(stderr, "[{}]: Can not read \"/proc/uptime\"\n", - __FUNCTION__); - return std::nullopt; - } - double uptimeSec; - fin >> uptimeSec; - fin.close(); - - return static_cast<int64_t>(uptimeSec * kMillisecondPerSecond); -} - -int64_t File::GetWallTimeInMs() -{ - return std::chrono::system_clock::now().time_since_epoch() / - std::chrono::milliseconds(1); -} - -bool File::IsValidName(std::string_view name) -{ - return !std::regex_search(std::string(name).c_str(), - std::regex("[^0-9a-zA-Z_:]")); -} - -inline std::string File::GetCpFullFileName() -{ - return std::string() + btm::resource::BTMonitorDir + mNodeName + "_" + - kCheckpointFile; -} -inline std::string File::GetDurFullFileName() -{ - return std::string() + btm::resource::BTMonitorDir + mNodeName + "_" + - kDurationFile; -} -} // namespace resource -} // namespace boot_time_monitor
diff --git a/src/systemd_handler.cpp b/src/systemd_handler.cpp index dc005ec..acbc4a5 100644 --- a/src/systemd_handler.cpp +++ b/src/systemd_handler.cpp
@@ -1,5 +1,7 @@ #include "systemd_handler.hpp" +#include "log.hpp" + #include <fmt/printf.h> #include <regex> @@ -92,7 +94,7 @@ } // namespace Handler::Handler(std::shared_ptr<sdbusplus::asio::connection> conn, - std::shared_ptr<btm::api::IApi> api) : + std::shared_ptr<btm::api::IBoottimeApi> api) : mApi(std::move(api)), mBMCFinishTimer(conn->get_io_context()) { mBMCFinishTimer.expires_after(std::chrono::seconds(0)); @@ -187,22 +189,28 @@ }); } + absl::Status status; SystemdDuration durations = CalculateSystemdDuration(times); - mApi->SetNodesDurationByTag(btm::kBootTimeTagBMC, - convertName(kSystemdFirmwareTime), - durations.firmware / kMillisecondPerSecond); - mApi->SetNodesDurationByTag(btm::kBootTimeTagBMC, - convertName(kSystemdLoaderTime), - durations.loader / kMillisecondPerSecond); - mApi->SetNodesDurationByTag(btm::kBootTimeTagBMC, - convertName(kSystemdKernelTime), - durations.kernel / kMillisecondPerSecond); - mApi->SetNodesDurationByTag(btm::kBootTimeTagBMC, - convertName(kSystemdInitRDTime), - durations.initRD / kMillisecondPerSecond); - mApi->SetNodesDurationByTag(btm::kBootTimeTagBMC, - convertName(kSystemdUserspaceTime), - durations.userspace / kMillisecondPerSecond); + status = mApi->SetNodesDurationByTag( + btm::kBootTimeTagBMC, convertName(kSystemdFirmwareTime), + durations.firmware / kMillisecondPerSecond); + btm::log::LogIfError(status); + status = mApi->SetNodesDurationByTag( + btm::kBootTimeTagBMC, convertName(kSystemdLoaderTime), + durations.loader / kMillisecondPerSecond); + btm::log::LogIfError(status); + status = mApi->SetNodesDurationByTag( + btm::kBootTimeTagBMC, convertName(kSystemdKernelTime), + durations.kernel / kMillisecondPerSecond); + btm::log::LogIfError(status); + status = mApi->SetNodesDurationByTag( + btm::kBootTimeTagBMC, convertName(kSystemdInitRDTime), + durations.initRD / kMillisecondPerSecond); + btm::log::LogIfError(status); + status = mApi->SetNodesDurationByTag( + btm::kBootTimeTagBMC, convertName(kSystemdUserspaceTime), + durations.userspace / kMillisecondPerSecond); + btm::log::LogIfError(status); #ifdef NPCM7XX_OR_NEWER // NPCM7XX or newer Nuvoton BMC has a register that starts counting from @@ -214,17 +222,21 @@ auto upTimeMS = util->getUpTimeInMs(); if (powerOnSec != std::nullopt && upTimeMS != std::nullopt) { - mApi->SetNodeDurationByTag(btm::kBootTimeTagBMC, "FirmwarePlusLoader", - powerOnSec.value() * 1000 - - upTimeMS.value()); + status = mApi->SetNodeDurationByTag( + btm::kBootTimeTagBMC, "FirmwarePlusLoader", + powerOnSec.value() * 1000 - upTimeMS.value()); + btm::log::LogIfError(status); } #endif // BMC marks the boot process as `completed` automatically if we do *NOT* have // external daemon to do so. #ifdef AUTO_BMC_COMPLETE - mApi->SetNodesCheckpointByTag(btm::kBootTimeTagBMC, "UserspaceEnd", 0, 0); - mApi->NotifyNodesCompleteByTag(btm::kBootTimeTagBMC); + status = mApi->SetNodesCheckpointByTag(btm::kBootTimeTagBMC, "UserspaceEnd", + 0, 0); + btm::log::LogIfError(status); + status = mApi->NotifyNodesCompleteByTag(btm::kBootTimeTagBMC); + btm::log::LogIfError(status); #endif } } // namespace systemd
diff --git a/test/api_test.cpp b/test/api_test.cpp deleted file mode 100644 index c70a6ca..0000000 --- a/test/api_test.cpp +++ /dev/null
@@ -1,326 +0,0 @@ -#include "api.hpp" -#include "resource.hpp" - -#include <fmt/format.h> - -#include <algorithm> -#include <cstddef> -#include <cstdlib> -#include <filesystem> -#include <fstream> -#include <string> -#include <string_view> -#include <tuple> -#include <vector> - -#include <gtest/gtest.h> - -namespace boot_time_monitor -{ - -namespace btm = boot_time_monitor; - -namespace fs = std::filesystem; -namespace -{ - -class ApiTest : public ::testing::Test -{ - public: - // Wall time (second param) equals zero means BMC will get wall time by - // itself. - const std::vector<std::tuple<std::string_view, int64_t, int64_t>> inCP = { - {"reboot_start", 1000, 0}, - {"Shutdown1", 0 /*will be 2000*/, 1000}, - {"thisIs_2_shutdown", 0 /*will be 3000*/, 50}, - {"000S0", 0 /*will be 4000*/, 0}, - {"_PowerBack_", 0 /*will be 5000*/, 100}, - {"start1", 0 /*will be 6000*/, 500}, - {"start2", 0 /*will be 7000*/, 100}, - {"reboot_end", 8000, 0}, - }; - - const std::vector<std::tuple<std::string_view, int64_t>> inDur = { - {"nic1", 0}, - {"A_nic", 1000}, - {"_nextNIC", 4}, - {"99NNN", 99}, - }; - - ApiTest() - { - // Use a temporary directory for test files - // Prefer TMPDIR environment variable if set, otherwise use /tmp - const char* tmp_env = std::getenv("TMPDIR"); - std::string base_tmp = (tmp_env != nullptr) ? tmp_env : "/tmp"; - testDir = base_tmp + "/api_test_temp_" + std::to_string(getpid()) + "/"; - - // Clean up the temporary directory and its contents - // Check if the directory exists before removing - if (fs::exists(testDir)) - { - fs::remove_all(testDir); - } - else - { - fs::create_directories(testDir); // Ensure the directory exists - } - - // Use a temporary directory for test files - btm::resource::BTMonitorDir = - testDir; // Set the global monitor dir for this test scope - } - - protected: - std::string testDir; -}; - -/* - * Verifies that setting multiple checkpoints, including those that generate - * an additional ":BEGIN" entry due to a non-zero duration, results in the - * correct total count when retrieved via GetNodeCheckpointList immediately - * after setting. - */ -TEST_F(ApiTest, checkpoint_set) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host0NodeConfig("host0", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host0NodeConfig); - - // Calculate expected lines: checkpoints with duration != 0 add two lines - std::size_t expectedLines = 0; - for (const auto& cp : inCP) - { - expectedLines += (std::get<2>(cp) != 0) ? 2 : 1; - } - - // Set checkpoints for host0 - for (const auto& cp : inCP) - { - api->SetNodeCheckpoint(host0NodeConfig, std::get<0>(cp), - std::get<1>(cp), std::get<2>(cp)); - } - - EXPECT_EQ(api->GetNodeCheckpointList(host0NodeConfig).size(), - expectedLines); -} - -/* - * Verifies that calling SetNodeCheckpoint with a non-zero duration specifically - * creates both the original checkpoint entry and the associated ":BEGIN" entry. - */ -TEST_F(ApiTest, checkpoint_set_with_duration) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host1NodeConfig("host1", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host1NodeConfig); - - // Test on host1 - const std::string_view testName = "StageWithDuration"; - const int64_t testDuration = 500; - const std::string expectedBeginName = std::string(testName) + - btm::resource::kBeginStageSuffix; - - api->SetNodeCheckpoint(host1NodeConfig, testName, 0, testDuration); - - auto checkpoints = api->GetNodeCheckpointList(host1NodeConfig); - EXPECT_EQ(checkpoints.size(), 2); - - // Check if both the original and the :BEGIN checkpoints exist - bool foundOriginal = false; - bool foundBegin = false; - for (const auto& cp : checkpoints) - { - if (std::get<0>(cp) == testName) - { - foundOriginal = true; - } - else if (std::get<0>(cp) == expectedBeginName) - { - foundBegin = true; - } - } - EXPECT_TRUE(foundOriginal); - EXPECT_TRUE(foundBegin); -} - -/* - * Verifies that setting multiple durations via SetNodeDuration results in the - * correct total count when retrieved via GetNodeAdditionalDurations - * immediately after setting. - */ -TEST_F(ApiTest, duration_set) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host2NodeConfig("host2", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host2NodeConfig); - - // Test on host2 - // Set durations for host2 - for (const auto& dur : inDur) - { - api->SetNodeDuration(host2NodeConfig, std::get<0>(dur), - std::get<1>(dur)); - } - EXPECT_EQ(api->GetNodeAdditionalDurations(host2NodeConfig).size(), - inDur.size()); -} - -/* - * Verifies the state transitions of the IsNodeRebooting flag. - * It should be false initially, true after a checkpoint is set, false after - * NotifyNodeComplete is called, and true again after another checkpoint is set. - */ -TEST_F(ApiTest, rebootcomplete_behavior) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host3NodeConfig("host3", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host3NodeConfig); - - // Test on host3 - // Initially, no files exist or are empty, so not rebooting - EXPECT_FALSE(api->IsNodeRebooting(host3NodeConfig)); - - // Setting a checkpoint starts the "reboot" process for the node - api->SetNodeCheckpoint(host3NodeConfig, "FirstCheckpoint", 0, 0); - EXPECT_TRUE(api->IsNodeRebooting(host3NodeConfig)); - - // Marking complete finishes the reboot process - api->NotifyNodeComplete(host3NodeConfig); - EXPECT_FALSE(api->IsNodeRebooting(host3NodeConfig)); - - // Setting another checkpoint starts a new reboot cycle - api->SetNodeCheckpoint(host3NodeConfig, "SecondCheckpoint", 0, 0); - EXPECT_TRUE(api->IsNodeRebooting(host3NodeConfig)); -} - -/* - * Verifies that GetNodeCheckpointList retrieves the list of checkpoints - * belonging to the *current* boot cycle (i.e., since the last - * NotifyNodeComplete). Checkpoints from the previous completed cycle are not - * included. - */ -TEST_F(ApiTest, checkpoint_get) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host4NodeConfig("host4", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host4NodeConfig); - - // Test on host4 - // Set the initial checkpoints - for (const auto& cp : inCP) - { - api->SetNodeCheckpoint(host4NodeConfig, std::get<0>(cp), - std::get<1>(cp), std::get<2>(cp)); - } - // Calculate expected lines for the initial set - std::size_t expectedLines = - api->GetNodeCheckpointList(host4NodeConfig).size(); - - // Mark the initial set as complete - api->NotifyNodeComplete(host4NodeConfig); - // GetCheckpointList should return the *completed* list, also add one to the - // "RebootEnd" checkpoint - EXPECT_EQ(api->GetNodeCheckpointList(host4NodeConfig).size(), - expectedLines + 1); - - // Set a new checkpoint (part of the *next* boot cycle) - api->SetNodeCheckpoint(host4NodeConfig, "NewCycleCheckpoint", 0, 0); - - // GetCheckpointList should return the checkpoint amount after previous - // RebootComplete - EXPECT_EQ(api->GetNodeCheckpointList(host4NodeConfig).size(), 1); -} - -/* - * Verifies that when SetNodeCheckpoint is called with wallTime=0, the system - * automatically assigns non-zero values for both the wall time (epoch) and - * monotonic time in the recorded checkpoint data. - */ -TEST_F(ApiTest, checkpoint_monotory) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host5NodeConfig("host5", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host5NodeConfig); - - // Test on host5 - api->SetNodeCheckpoint(host5NodeConfig, "AutoTimestamp", 0, 0); - - auto checkpoints = api->GetNodeCheckpointList(host5NodeConfig); - ASSERT_EQ(checkpoints.size(), 1); - - // Wall time (index 1) and monotonic time (index 2) should be non-zero - EXPECT_NE(std::get<1>(checkpoints[0]), 0); - EXPECT_NE(std::get<2>(checkpoints[0]), 0); -} - -/* - * Verifies that calls to SetPSUCheckpoint and SetPSUDuration are broadcast - * and correctly recorded for *all* registered nodes. - */ -TEST_F(ApiTest, powercycle_behavior) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - std::vector<btm::NodeConfig> ncs; - for (int i = 6; i < 8; i++) - { - ncs.emplace_back("host6", std::string(btm::kBootTimeTagHost)); - api->RegisterNode(ncs.back()); - } - - // This test inherently checks all nodes - const std::string_view psuCpName = "PSU_PowerOn"; - const std::string_view psuDurName = "PSU_Stabilize"; - - api->SetPSUCheckpoint(psuCpName, 0, 0); - api->SetPSUDuration(psuDurName, 1234); - - for (const auto& nc : ncs) // Iterate through all created nodes - { - auto checkpoints = api->GetNodeCheckpointList(nc); - EXPECT_EQ(checkpoints.size(), 1); - EXPECT_EQ(std::get<0>(checkpoints.back()), psuCpName); - - auto durations = api->GetNodeAdditionalDurations(nc); - EXPECT_EQ(durations.size(), 1); - EXPECT_EQ(std::get<0>(durations.back()), psuDurName); - EXPECT_EQ(std::get<1>(durations.back()), 1234); - } -} - -/* - * Verifies that the NotifyNodeComplete(RebootComplete) should be individule, - * not boardcast to all of the nodes. - */ -TEST_F(ApiTest, notify_complete_is_individual) -{ - std::unique_ptr<btm::api::Api> api = std::make_unique<btm::api::Api>(); - btm::NodeConfig host9NodeConfig("host9", - std::string(btm::kBootTimeTagHost)); - btm::NodeConfig host10NodeConfig("host10", - std::string(btm::kBootTimeTagHost)); - api->RegisterNode(host9NodeConfig); - api->RegisterNode(host10NodeConfig); - - // Set checkpoints on two different nodes to mark them as rebooting - api->SetNodeCheckpoint(host9NodeConfig, "Node0_BootStart", 0, 0); - api->SetNodeCheckpoint(host10NodeConfig, "Node1_BootStart", 0, 0); - - EXPECT_TRUE(api->IsNodeRebooting(host9NodeConfig)); - EXPECT_TRUE(api->IsNodeRebooting(host10NodeConfig)); - - // Notify only the first node as complete - api->NotifyNodeComplete(host9NodeConfig); - - // Verify the first node is no longer rebooting, but the second one still is - EXPECT_FALSE(api->IsNodeRebooting(host9NodeConfig)); - EXPECT_TRUE(api->IsNodeRebooting(host10NodeConfig)); -} -} // namespace -} // namespace boot_time_monitor
diff --git a/test/meson.build b/test/meson.build index ed84efc..4486f52 100644 --- a/test/meson.build +++ b/test/meson.build
@@ -21,12 +21,12 @@ endif tests = [ - 'api_test', ] foreach t : tests - test(t, executable(t.underscorify(), t + '.cpp', - build_by_default: false, - implicit_include_directories: false, - dependencies: [boot_time_monitor_dep, gtest, gmock])) + test(t, executable( + t.underscorify(), t + '.cpp', + build_by_default: false, + implicit_include_directories: false, + dependencies: [boot_time_monitor_dep, gtest, gmock])) endforeach