1 #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" 14 CEREAL_CLASS_VERSION(phosphor::network::snmp::Client, CLASS_VERSION); 15 16 namespace phosphor 17 { 18 namespace network 19 { 20 namespace snmp 21 { 22 23 using 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 */ 32 template <class Archive> 33 void 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 */ 45 template <class Archive> 46 void 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 57 fs::path serialize(Id id, const Client& manager, const fs::path& dir) 58 { 59 fs::path fileName = dir; 60 fs::create_directories(dir); 61 fileName /= std::to_string(id); 62 63 std::ofstream os(fileName.string(), std::ios::binary); 64 cereal::BinaryOutputArchive oarchive(os); 65 oarchive(manager); 66 return fileName; 67 } 68 69 bool deserialize(const fs::path& path, Client& manager) 70 { 71 try 72 { 73 if (fs::exists(path)) 74 { 75 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary); 76 cereal::BinaryInputArchive iarchive(is); 77 iarchive(manager); 78 return true; 79 } 80 return false; 81 } 82 catch (cereal::Exception& e) 83 { 84 log<level::ERR>(e.what()); 85 std::error_code ec; 86 fs::remove(path, ec); 87 return false; 88 } 89 catch (const fs::filesystem_error& e) 90 { 91 return false; 92 } 93 } 94 95 } // namespace snmp 96 } // namespace network 97 } // namespace phosphor 98