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