blob: e7249192f045c52b11969c51591ec2a6f0456c7b [file] [log] [blame]
Deepak Kodihalli6620e982017-08-05 13:09:54 -05001#pragma once
2
Patrick Venturea680d1e2018-10-14 13:34:26 -07003#include "config.h"
4
Deepak Kodihalli6620e982017-08-05 13:09:54 -05005#include <cereal/archives/json.hpp>
6#include <experimental/filesystem>
7#include <fstream>
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -05008#include <phosphor-logging/log.hpp>
9
Brad Bishop7dfd08f2018-12-12 21:40:26 -050010namespace phosphor
11{
12namespace inventory
13{
14namespace manager
Deepak Kodihalli6620e982017-08-05 13:09:54 -050015{
16
17namespace fs = std::experimental::filesystem;
18
Brad Bishop7dfd08f2018-12-12 21:40:26 -050019struct SerialOps
Deepak Kodihalli6620e982017-08-05 13:09:54 -050020{
Brad Bishop7dfd08f2018-12-12 21:40:26 -050021 /** @brief Serialize inventory item path
22 * Serializing only path for an empty interface to be consistent
23 * interfaces.
24 * @param[in] path - DBus object path
25 * @param[in] iface - Inventory interface name
26 */
27 static void serialize(const std::string& path, const std::string& iface)
Deepak Kodihallib28990f2017-08-08 07:19:34 -050028 {
Brad Bishop7dfd08f2018-12-12 21:40:26 -050029 fs::path p(PIM_PERSIST_PATH);
30 p /= path;
31 fs::create_directories(p);
32 p /= iface;
33 std::ofstream os(p, std::ios::binary);
34 }
35
36 /** @brief Serialize inventory item
37 *
38 * @param[in] path - DBus object path
39 * @param[in] iface - Inventory interface name
40 * @param[in] object - Object to be serialized
41 */
42 template <typename T>
43 static void serialize(const std::string& path, const std::string& iface,
44 const T& object)
45 {
46 fs::path p(PIM_PERSIST_PATH);
47 p /= path;
48 fs::create_directories(p);
49 p /= iface;
50 std::ofstream os(p, std::ios::binary);
51 cereal::JSONOutputArchive oarchive(os);
52 oarchive(object);
53 }
54
55 static void deserialize(const std::string&, const std::string&)
56 {
57 // This is intentionally a noop.
58 }
59
60 /** @brief Deserialize inventory item
61 *
62 * @param[in] path - DBus object path
63 * @param[in] iface - Inventory interface name
64 * @param[in] object - Object to be serialized
65 */
66 template <typename T>
67 static void deserialize(const std::string& path, const std::string& iface,
68 T& object)
69 {
70 fs::path p(PIM_PERSIST_PATH);
71 p /= path;
72 p /= iface;
73 try
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050074 {
Brad Bishop7dfd08f2018-12-12 21:40:26 -050075 if (fs::exists(p))
76 {
77 std::ifstream is(p, std::ios::in | std::ios::binary);
78 cereal::JSONInputArchive iarchive(is);
79 iarchive(object);
80 }
81 }
82 catch (cereal::Exception& e)
83 {
84 phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
85 fs::remove(p);
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050086 }
87 }
Brad Bishop7dfd08f2018-12-12 21:40:26 -050088};
89} // namespace manager
90} // namespace inventory
91} // namespace phosphor