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, const std::uint32_t version) 37 { 38 archive(manager.address(), manager.port()); 39 } 40 41 /** @brief Function required by Cereal to perform deserialization. 42 * @tparam Archive - Cereal archive type (binary in our case). 43 * @param[in] archive - reference to Cereal archive. 44 * @param[in] manager - reference to snmp manager info. 45 * @param[in] version - Class version that enables handling 46 * a serialized data across code levels 47 */ 48 template <class Archive> 49 void load(Archive& archive, Client& manager, const std::uint32_t version) 50 { 51 std::string ipaddress{}; 52 uint16_t port{}; 53 54 archive(ipaddress, port); 55 56 manager.address(ipaddress); 57 manager.port(port); 58 } 59 60 fs::path serialize(Id id, const Client& manager, const fs::path& dir) 61 { 62 fs::path fileName = dir; 63 fs::create_directories(dir); 64 fileName /= std::to_string(id); 65 66 std::ofstream os(fileName.string(), std::ios::binary); 67 cereal::BinaryOutputArchive oarchive(os); 68 oarchive(manager); 69 return fileName; 70 } 71 72 bool deserialize(const fs::path& path, Client& manager) 73 { 74 try 75 { 76 if (fs::exists(path)) 77 { 78 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary); 79 cereal::BinaryInputArchive iarchive(is); 80 iarchive(manager); 81 return true; 82 } 83 return false; 84 } 85 catch (cereal::Exception& e) 86 { 87 log<level::ERR>(e.what()); 88 std::error_code ec; 89 fs::remove(path, ec); 90 return false; 91 } 92 catch (const fs::filesystem_error& e) 93 { 94 return false; 95 } 96 } 97 98 } // namespace snmp 99 } // namespace network 100 } // namespace phosphor 101