blob: 7f15dc3d10089e014971e2e6a3cce9af32219e24 [file] [log] [blame]
#ifndef THIRD_PARTY_MILOTIC_EXTERNAL_CC_TLBMC_HAL_SHARED_MEM_SEGMENT_MANAGER_H_
#define THIRD_PARTY_MILOTIC_EXTERNAL_CC_TLBMC_HAL_SHARED_MEM_SEGMENT_MANAGER_H_
#include <memory>
#include <string_view>
#include <utility>
#include "boost/interprocess/managed_shared_memory.hpp" // NOLINT
#include "tlbmc/hal/shared_mem/metrics.h"
#include "tlbmc/hal/shared_mem/sensors.h"
namespace milotic_tlbmc {
constexpr std::string_view kShareMemInitializedFile =
"/run/tlbmc/shm_initialized";
// The class is thread-safe.
class SegmentManager {
public:
virtual ~SegmentManager() = default;
// Reads `initialized_file_path` to check if the shared memory is
// initialized. If not, creates the shared memory and touches the file.
// Returns nullptr on errors.
// This API shall only be called by the server (tlbmc).
static std::unique_ptr<SegmentManager> Create(
std::string_view initialized_file_path = kShareMemInitializedFile);
// Returns the shared memory segment.
// This API shall only be called by clients (telemetry daemons).
static std::unique_ptr<SegmentManager> Get(
std::string_view initialized_file_path = kShareMemInitializedFile);
// Returns the sensor with the given name. If the sensor does not exist,
// creates the sensor.
// This API is very expensive. Callers should cache the returned pointer.
virtual IpcSensor* GetOrCreateSensor(const char* sensor_name);
// Returns the metrics. If the metrics does not exist, creates the metrics.
// This API is very expensive. Callers should cache the returned pointer.
virtual TlbmcMetrics* GetOrCreateMetrics();
protected:
SegmentManager() = default;
static std::unique_ptr<SegmentManager> CreateHelper(
std::string_view initialized_file_path);
boost::interprocess::managed_shared_memory& GetMemory() { return memory_; }
private:
explicit SegmentManager(boost::interprocess::managed_shared_memory&& memory)
: memory_(std::move(memory)) {}
boost::interprocess::managed_shared_memory memory_;
};
// A dummy segment manager that does nothing.
// This is used when the shared memory is not available due to system error or
// library error.
class SegmentManagerDummy : public SegmentManager {
public:
SegmentManagerDummy() = default;
IpcSensor* GetOrCreateSensor(
[[maybe_unused]] const char* sensor_name) override {
return nullptr;
}
TlbmcMetrics* GetOrCreateMetrics() override { return nullptr; }
};
} // namespace milotic_tlbmc
#endif // THIRD_PARTY_MILOTIC_EXTERNAL_CC_TLBMC_HAL_SHARED_MEM_SEGMENT_MANAGER_H_