blob: ea4794580e651cfbf319faecd2262d8df13277cb [file] [log] [blame]
Ratan Gupta212f53e2018-04-30 17:28:05 +05301#include <cereal/types/string.hpp>
2#include <cereal/types/vector.hpp>
3#include <cereal/archives/binary.hpp>
4#include <fstream>
5
6#include "snmp_serialize.hpp"
7#include "snmp_client.hpp"
8#include <phosphor-logging/log.hpp>
9#include "config.h"
10
11// Register class version
12// From cereal documentation;
13// "This macro should be placed at global scope"
14CEREAL_CLASS_VERSION(phosphor::network::snmp::Client, CLASS_VERSION);
15
16namespace phosphor
17{
18namespace network
19{
20namespace snmp
21{
22
23using namespace phosphor::logging;
24
25/** @brief Function required by Cereal to perform serialization.
26 * @tparam Archive - Cereal archive type (binary in our case).
27 * @param[in] archive - reference to Cereal archive.
28 * @param[in] manager - const reference to snmp manager info.
29 * @param[in] version - Class version that enables handling
30 * a serialized data across code levels
31 */
32template <class Archive>
33void save(Archive& archive, const Client& manager, const std::uint32_t version)
34{
35 archive(manager.address(), manager.port());
36}
37
38/** @brief Function required by Cereal to perform deserialization.
39 * @tparam Archive - Cereal archive type (binary in our case).
40 * @param[in] archive - reference to Cereal archive.
41 * @param[in] manager - reference to snmp manager info.
42 * @param[in] version - Class version that enables handling
43 * a serialized data across code levels
44 */
45template <class Archive>
46void load(Archive& archive, Client& manager, const std::uint32_t version)
47{
48 std::string ipaddress{};
49 uint16_t port{};
50
51 archive(ipaddress, port);
52
53 manager.address(ipaddress);
54 manager.port(port);
55}
56
57fs::path serialize(const Client& manager, const fs::path& dir)
58{
59 fs::path fileName = dir;
60 fs::create_directories(dir);
61 auto address = manager.address();
62 auto port = manager.port();
63 fileName /= address + SEPRATOR + std::to_string(port);
64
65 std::ofstream os(fileName.string(), std::ios::binary);
66 cereal::BinaryOutputArchive oarchive(os);
67 oarchive(manager);
68 return fileName;
69}
70
71bool deserialize(const fs::path& path, Client& manager)
72{
73 try
74 {
75 if (fs::exists(path))
76 {
77 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary);
78 cereal::BinaryInputArchive iarchive(is);
79 iarchive(manager);
80 return true;
81 }
82 return false;
83 }
84 catch (cereal::Exception& e)
85 {
86 log<level::ERR>(e.what());
87 std::error_code ec;
88 fs::remove(path, ec);
89 return false;
90 }
91 catch (const fs::filesystem_error& e)
92 {
93 return false;
94 }
95}
96
97} // namespace snmp
98} // namespace network
99} // namespace phosphor