diff --git a/common/flight_recorder.hpp b/common/flight_recorder.hpp index ff270ed85..11a64546d 100644 --- a/common/flight_recorder.hpp +++ b/common/flight_recorder.hpp @@ -1,18 +1,19 @@ #pragma once -#include - #include +#include #include #include #include #include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace flightrecorder { - using ReqOrResponse = bool; using FlightRecorderData = std::vector; using FlightRecorderTimeStamp = std::string; @@ -91,8 +92,8 @@ class FlightRecorder if (flightRecorderPolicy) { std::ofstream recorderOutputFile(flightRecorderDumpPath); - std::cout << "Dumping the flight recorder into : " - << flightRecorderDumpPath << "\n"; + info("Dumping the flight recorder into : {FLIGHT_REC_DUMP}", + "FLIGHT_REC_DUMP", flightRecorderDumpPath); for (const auto& message : tapeRecorder) { @@ -117,7 +118,7 @@ class FlightRecorder } else { - std::cerr << "Fight recorder policy is disabled\n"; + error("Fight recorder policy is disabled"); } } }; diff --git a/common/test/meson.build b/common/test/meson.build index b3380b43c..9e5517ead 100644 --- a/common/test/meson.build +++ b/common/test/meson.build @@ -17,6 +17,7 @@ foreach t : tests libpldm_dep, nlohmann_json, phosphor_dbus_interfaces, + phosphor_logging_dep, libpldmutils, sdbusplus]), workdir: meson.current_source_dir()) diff --git a/common/utils.cpp b/common/utils.cpp index 0e4acf367..506ad1905 100644 --- a/common/utils.cpp +++ b/common/utils.cpp @@ -1,5 +1,3 @@ -#include "config.h" - #include "utils.hpp" #include "libpldm/pdr.h" @@ -7,6 +5,7 @@ #include +#include #include #include @@ -20,6 +19,8 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace utils @@ -75,8 +76,8 @@ std::vector> findStateEffecterPDR(uint8_t /*tid*/, } catch (const std::exception& e) { - std::cerr << " Failed to obtain a record. ERROR =" << e.what() - << std::endl; + error(" Failed to obtain a record. ERROR = {ERR_EXCEP}", "ERR_EXCEP", + e.what()); } return pdrs; @@ -129,8 +130,8 @@ std::vector> findStateSensorPDR(uint8_t /*tid*/, } catch (const std::exception& e) { - std::cerr << " Failed to obtain a record. ERROR =" << e.what() - << std::endl; + error(" Failed to obtain a record. ERROR = {ERR_EXCEP}", "ERR_EXCEP", + e.what()); } return pdrs; @@ -142,7 +143,8 @@ uint8_t readHostEID() std::ifstream eidFile{HOST_EID_PATH}; if (!eidFile.good()) { - std::cerr << "Could not open host EID file: " << HOST_EID_PATH << "\n"; + error("Could not open host EID file: {HOST_EID_PATH}", "HOST_EID_PATH", + std::string(HOST_EID_PATH)); } else { @@ -154,8 +156,7 @@ uint8_t readHostEID() } else { - std::cerr << "Host EID file was empty" - << "\n"; + error("Host EID file was empty"); } } @@ -235,7 +236,9 @@ std::string DBusHandler::getService(const char* path, mapper.append(path, DbusInterfaceList({})); } - auto mapperResponseMsg = bus.call(mapper); + auto mapperResponseMsg = bus.call( + mapper, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); mapperResponseMsg.read(mapperResponse); return mapperResponse.begin()->first; } @@ -251,13 +254,16 @@ GetSubTreeResponse auto method = bus.new_method_call(mapperBusName, mapperPath, mapperInterface, "GetSubTree"); method.append(searchPath, depth, ifaceList); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(response); } catch (const std::exception& e) { - std::cerr << "failed GetSubTree query for interface " << ifaceList[0] - << " with ERROR=" << e.what() << "\n"; + error( + "failed GetSubTree query for interface {FACE_LIST} with ERROR = {ERR_EXCEP}", + "FACE_LIST", ifaceList[0], "ERR_EXCEP", e.what()); } return response; } @@ -284,12 +290,15 @@ void reportError(const char* errorMsg, const Severity& sev) } std::map addlData{}; method.append(errorMsg, severity, addlData); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call to create error log, ERROR=" - << e.what() << "\n"; + error( + "failed to make a d-bus call to create error log, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -318,7 +327,9 @@ void DBusHandler::setDbusProperty(const DBusMapping& dBusMap, service.c_str(), "/xyz/openbmc_project/inventory", "xyz.openbmc_project.Inventory.Manager", "Notify"); method.append(std::move(objectValueTree)); - bus.call_noreply(method); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } else { @@ -330,14 +341,16 @@ void DBusHandler::setDbusProperty(const DBusMapping& dBusMap, dBusMap.objectPath == "/xyz/openbmc_project/network/hypervisor/eth1/ipv4/addr0") { - std::cout << " ,service :" << service.c_str() - << " , interface : " << dBusMap.interface.c_str() - << " , path : " << dBusMap.objectPath.c_str() - << std::endl; + info( + " service :{SERV} , interface : {INTF} , path : {DBUS_OBJ_PATH}", + "SERV", service.c_str(), "INTF", dBusMap.interface.c_str(), + "DBUS_OBJ_PATH", dBusMap.objectPath.c_str()); } method.append(dBusMap.interface.c_str(), dBusMap.propertyName.c_str(), variant); - bus.call_noreply(method); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } }; @@ -354,7 +367,7 @@ void DBusHandler::setDbusProperty(const DBusMapping& dBusMap, dBusMap.objectPath == "/xyz/openbmc_project/network/hypervisor/eth1/ipv4/addr0") { - std::cout << " value : " << std::get(value); + info(" value : {VAL}", "VAL", std::get(value)); } if (strstr(dBusMap.objectPath.c_str(), "dimm") && (dBusMap.interface == @@ -362,8 +375,8 @@ void DBusHandler::setDbusProperty(const DBusMapping& dBusMap, { if (!std::get(value)) { - std::cerr << "Guard event on DIMM : [ " - << dBusMap.objectPath.c_str() << " ] \n"; + error("Guard event on DIMM : [ {DBUS_OBJ_PATH} ]", + "DBUS_OBJ_PATH", dBusMap.objectPath.c_str()); } } @@ -411,7 +424,8 @@ void DBusHandler::setDbusProperty(const DBusMapping& dBusMap, } else { - std::cerr << "Property Type is:" << dBusMap.propertyType << std::endl; + error("Property Type is: {DBUS_PROP_TYP} ", "DBUS_PROP_TYP", + dBusMap.propertyType); throw std::invalid_argument("UnSpported Dbus Type"); } } @@ -425,7 +439,9 @@ PropertyValue DBusHandler::getDbusPropertyVariant( "Get"); method.append(dbusInterface, dbusProp); PropertyValue value{}; - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(value); return value; } @@ -438,7 +454,9 @@ ObjectValueTree DBusHandler::getManagedObj(const char* service, auto method = bus.new_method_call(service, rootPath, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(objects); return objects; } @@ -489,7 +507,8 @@ PropertyValue jsonEntryToDbusVal(std::string_view type, } else { - std::cerr << "Unknown D-Bus property type, TYPE=" << type << "\n"; + error("Unknown D-Bus property type, TYPE={DBUS_PROP_TYP}", + "DBUS_PROP_TYP", type); } return propValue; @@ -552,8 +571,8 @@ int emitStateSensorEventSignal(uint8_t tid, uint16_t sensorId, } catch (const std::exception& e) { - std::cerr << "Error emitting pldm event signal:" - << "ERROR=" << e.what() << "\n"; + error("Error emitting pldm event signal:ERROR={ERR_EXCEP}", "ERR_EXCEP", + e.what()); return PLDM_ERROR; } @@ -671,14 +690,16 @@ std::string getBiosAttrValue(const std::string& dbusAttrName) service.c_str(), biosConfigPath, "xyz.openbmc_project.BIOSConfig.Manager", "GetAttribute"); method.append(dbusAttrName); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(var1, var2, var3); } catch (const sdbusplus::exception::SdBusError& e) { - std::cout << "Error getting the bios attribute" - << "ERROR=" << e.what() << "ATTRIBUTE=" << dbusAttrName - << std::endl; + info( + "Error getting the bios attribute ERROR={ERR_EXCEP} ATTRIBUTE={BIOS_ATTR}", + "ERR_EXCEP", e.what(), "BIOS_ATTR", dbusAttrName); return {}; } @@ -713,13 +734,16 @@ void setBiosAttr(const BiosAttributeList& biosAttrList) method.append( biosConfigIntf, "PendingAttributes", std::variant(pendingAttributes)); - bus.call_noreply(method); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } catch (const sdbusplus::exception::SdBusError& e) { - std::cout << "Error setting the bios attribute" - << "ERROR=" << e.what() << "ATTRIBUTE=" << dbusAttrName - << "ATTRIBUTE VALUE=" << biosAttrStr << std::endl; + info( + "Error setting the bios attribute ERROR = {ERR_EXCEP} ATTRIBUTE= {DBUS_ATTR} ATTRIBUTE VALUE={BIOS_ATTR}", + "ERR_EXCEP", e.what(), "DBUS_ATTR", dbusAttrName.c_str(), + "BIOS_ATTR", biosAttrStr.c_str()); return; } } @@ -928,8 +952,9 @@ bool checkForFruPresence(const std::string& objPath) } catch (const sdbusplus::exception::SdBusError& e) { - std::cerr << "Failed to check for FRU presence for " << objPath - << " ERROR =" << e.what() << std::endl; + error( + "Failed to check for FRU presence for {OBJ_PATH} ERROR = {ERR_EXCEP}", + "OBJ_PATH", objPath.c_str(), "ERR_EXCEP", e.what()); } return isPresent; } diff --git a/common/utils.hpp b/common/utils.hpp index c62146835..5acaf6f81 100644 --- a/common/utils.hpp +++ b/common/utils.hpp @@ -22,6 +22,9 @@ #include #include +using microsec = std::chrono::microseconds; +using sec = std::chrono::seconds; + namespace pldm { using Severity = pldm::PelSeverity; diff --git a/fw-update/device_updater.cpp b/fw-update/device_updater.cpp index 96df1e636..a1fe3e317 100644 --- a/fw-update/device_updater.cpp +++ b/fw-update/device_updater.cpp @@ -5,14 +5,16 @@ #include "activation.hpp" #include "update_manager.hpp" +#include + #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace fw_update { - void DeviceUpdater::startFwUpdateFlow() { auto instanceId = updateManager->requester.getInstanceId(eid); @@ -45,8 +47,8 @@ void DeviceUpdater::startFwUpdateFlow() if (rc) { updateManager->requester.markFree(eid, instanceId); - std::cerr << "encode_request_update_req failed, EID=" << unsigned(eid) - << ", RC=" << rc << "\n"; + error("encode_request_update_req failed, EID = {EID}, RC = {RC}", "EID", + unsigned(eid), "RC", rc); // Handle error scenario } @@ -55,8 +57,8 @@ void DeviceUpdater::startFwUpdateFlow() std::move(std::bind_front(&DeviceUpdater::requestUpdate, this))); if (rc) { - std::cerr << "Failed to send RequestUpdate request, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error("Failed to send RequestUpdate request, EID = {EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); // Handle error scenario } } @@ -67,8 +69,8 @@ void DeviceUpdater::requestUpdate(mctp_eid_t eid, const pldm_msg* response, if (response == nullptr || !respMsgLen) { // Handle error scenario - std::cerr << "No response received for RequestUpdate, EID=" - << unsigned(eid) << "\n"; + error("No response received for RequestUpdate, EID = {EID}", "EID", + unsigned(eid)); return; } @@ -80,16 +82,15 @@ void DeviceUpdater::requestUpdate(mctp_eid_t eid, const pldm_msg* response, &fdMetaDataLen, &fdWillSendPkgData); if (rc) { - std::cerr << "Decoding RequestUpdate response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Decoding RequestUpdate response failed, EID = {EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } if (completionCode) { - std::cerr << "RequestUpdate response failed with error " - "completion code, EID=" - << unsigned(eid) << ", CC=" << unsigned(completionCode) - << "\n"; + error( + "RequestUpdate response failed with error completion code, EID = {EID}, CC = {CC}", + "EID", unsigned(eid), "CC", unsigned(completionCode)); return; } @@ -168,8 +169,8 @@ void DeviceUpdater::sendPassCompTableRequest(size_t offset) if (rc) { updateManager->requester.markFree(eid, instanceId); - std::cerr << "encode_pass_component_table_req failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("encode_pass_component_table_req failed, EID = {EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); // Handle error scenario } @@ -179,8 +180,9 @@ void DeviceUpdater::sendPassCompTableRequest(size_t offset) std::move(std::bind_front(&DeviceUpdater::passCompTable, this))); if (rc) { - std::cerr << "Failed to send PassComponentTable request, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error( + "Failed to send PassComponentTable request, EID = {EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); // Handle error scenario } } @@ -191,8 +193,8 @@ void DeviceUpdater::passCompTable(mctp_eid_t eid, const pldm_msg* response, if (response == nullptr || !respMsgLen) { // Handle error scenario - std::cerr << "No response received for PassComponentTable, EID=" - << unsigned(eid) << "\n"; + error("No response received for PassComponentTable, EID = {EID}", "EID", + unsigned(eid)); return; } @@ -206,17 +208,17 @@ void DeviceUpdater::passCompTable(mctp_eid_t eid, const pldm_msg* response, if (rc) { // Handle error scenario - std::cerr << "Decoding PassComponentTable response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Decoding PassComponentTable response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } if (completionCode) { // Handle error scenario - std::cerr << "PassComponentTable response failed with error " - "completion code, EID=" - << unsigned(eid) << ", CC=" << unsigned(completionCode) - << "\n"; + error( + "PassComponentTable response failed with error completion code, EID = {EID}, CC = {CC}", + "EID", unsigned(eid), "CC", unsigned(completionCode)); return; } // Handle ComponentResponseCode @@ -294,8 +296,8 @@ void DeviceUpdater::sendUpdateComponentRequest(size_t offset) if (rc) { updateManager->requester.markFree(eid, instanceId); - std::cerr << "encode_update_component_req failed, EID=" << unsigned(eid) - << ", RC=" << rc << "\n"; + error("encode_update_component_req failed, EID={EID}, RC = {RC}", "EID", + unsigned(eid), "RC", rc); // Handle error scenario } @@ -304,8 +306,8 @@ void DeviceUpdater::sendUpdateComponentRequest(size_t offset) std::move(std::bind_front(&DeviceUpdater::updateComponent, this))); if (rc) { - std::cerr << "Failed to send UpdateComponent request, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error("Failed to send UpdateComponent request, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); // Handle error scenario } } @@ -316,8 +318,8 @@ void DeviceUpdater::updateComponent(mctp_eid_t eid, const pldm_msg* response, if (response == nullptr || !respMsgLen) { // Handle error scenario - std::cerr << "No response received for updateComponent, EID=" - << unsigned(eid) << "\n"; + error("No response received for updateComponent, EID={EID}", "EID", + unsigned(eid)); return; } @@ -333,16 +335,15 @@ void DeviceUpdater::updateComponent(mctp_eid_t eid, const pldm_msg* response, &timeBeforeReqFWData); if (rc) { - std::cerr << "Decoding UpdateComponent response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Decoding UpdateComponent response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } if (completionCode) { - std::cerr << "UpdateComponent response failed with error " - "completion code, EID=" - << unsigned(eid) << ", CC=" << unsigned(completionCode) - << "\n"; + error( + "UpdateComponent response failed with error completion code, EID = {EID}, CC = {CC}", + "EID", unsigned(eid), "CC", unsigned(completionCode)); return; } } @@ -359,15 +360,17 @@ Response DeviceUpdater::requestFwData(const pldm_msg* request, &length); if (rc) { - std::cerr << "Decoding RequestFirmwareData request failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Decoding RequestFirmwareData request failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); rc = encode_request_firmware_data_resp( request->hdr.instance_id, PLDM_ERROR_INVALID_DATA, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding RequestFirmwareData response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding RequestFirmwareData response failed, EID = {EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } return response; } @@ -377,9 +380,8 @@ Response DeviceUpdater::requestFwData(const pldm_msg* request, const auto& comp = compImageInfos[applicableComponents[componentIndex]]; auto compOffset = std::get<5>(comp); auto compSize = std::get<6>(comp); - std::cerr << "offset = " << unsigned(offset) - << ", length = " << unsigned(length) << "\n"; - + error("offset = {OFFSET}, length = {LEN}", "OFFSET", unsigned(offset), + "LEN", unsigned(length)); if (length < PLDM_FWUP_BASELINE_TRANSFER_SIZE || length > maxTransferSize) { rc = encode_request_firmware_data_resp( @@ -387,8 +389,9 @@ Response DeviceUpdater::requestFwData(const pldm_msg* request, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding RequestFirmwareData response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding RequestFirmwareData response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } return response; } @@ -400,8 +403,9 @@ Response DeviceUpdater::requestFwData(const pldm_msg* request, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding RequestFirmwareData response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding RequestFirmwareData response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } return response; } @@ -424,8 +428,9 @@ Response DeviceUpdater::requestFwData(const pldm_msg* request, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding RequestFirmwareData response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding RequestFirmwareData response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return response; } @@ -444,15 +449,16 @@ Response DeviceUpdater::transferComplete(const pldm_msg* request, &transferResult); if (rc) { - std::cerr << "Decoding TransferComplete request failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Decoding TransferComplete request failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); rc = encode_transfer_complete_resp(request->hdr.instance_id, PLDM_ERROR_INVALID_DATA, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding TransferComplete response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding TransferComplete response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } return response; } @@ -464,22 +470,24 @@ Response DeviceUpdater::transferComplete(const pldm_msg* request, if (transferResult == PLDM_FWUP_TRANSFER_SUCCESS) { - std::cout << "Component Transfer complete, EID=" << unsigned(eid) - << ", COMPONENT_VERSION=" << compVersion << "\n"; + info( + "Component Transfer complete, EID = {EID}, COMPONENT_VERSION = {COMP_VERS}", + "EID", unsigned(eid), "COMP_VERS", compVersion); } else { - std::cerr << "Transfer of the component failed, EID=" << unsigned(eid) - << ", COMPONENT_VERSION=" << compVersion - << ", TRANSFER_RESULT=" << unsigned(transferResult) << "\n"; + error( + "Transfer of the component failed, EID={EID}, COMPONENT_VERSION = {COMP_VERS}, TRANSFER_RESULT = {TRANS_RES}", + "EID", unsigned(eid), "COMP_VERS", compVersion, "TRANS_RES", + unsigned(transferResult)); } rc = encode_transfer_complete_resp(request->hdr.instance_id, completionCode, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding TransferComplete response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Encoding TransferComplete response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return response; } @@ -497,15 +505,16 @@ Response DeviceUpdater::verifyComplete(const pldm_msg* request, auto rc = decode_verify_complete_req(request, payloadLength, &verifyResult); if (rc) { - std::cerr << "Decoding VerifyComplete request failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Decoding VerifyComplete request failed, EID = {EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); rc = encode_verify_complete_resp(request->hdr.instance_id, PLDM_ERROR_INVALID_DATA, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding VerifyComplete response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding VerifyComplete response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } return response; } @@ -517,22 +526,24 @@ Response DeviceUpdater::verifyComplete(const pldm_msg* request, if (verifyResult == PLDM_FWUP_VERIFY_SUCCESS) { - std::cout << "Component verification complete, EID=" << unsigned(eid) - << ", COMPONENT_VERSION=" << compVersion << "\n"; + info( + "Component verification complete, EID={EID}, COMPONENT_VERSION={COMP_VERS}", + "EID", unsigned(eid), "COMP_VERS", compVersion); } else { - std::cerr << "Component verification failed, EID=" << unsigned(eid) - << ", COMPONENT_VERSION=" << compVersion - << ", VERIFY_RESULT=" << unsigned(verifyResult) << "\n"; + error( + "Component verification failed, EID={EID}, COMPONENT_VERSION={COMP_VERS}, VERIFY_RESULT={VERIFY_RES}", + "EID", unsigned(eid), "COMP_VERS", compVersion, "VERIFY_RES", + unsigned(verifyResult)); } rc = encode_verify_complete_resp(request->hdr.instance_id, completionCode, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding VerifyComplete response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Encoding VerifyComplete response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return response; } @@ -552,15 +563,16 @@ Response DeviceUpdater::applyComplete(const pldm_msg* request, &compActivationModification); if (rc) { - std::cerr << "Decoding ApplyComplete request failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Decoding ApplyComplete request failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); rc = encode_apply_complete_resp(request->hdr.instance_id, PLDM_ERROR_INVALID_DATA, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding ApplyComplete response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Encoding ApplyComplete response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } return response; } @@ -573,23 +585,25 @@ Response DeviceUpdater::applyComplete(const pldm_msg* request, if (applyResult == PLDM_FWUP_APPLY_SUCCESS || applyResult == PLDM_FWUP_APPLY_SUCCESS_WITH_ACTIVATION_METHOD) { - std::cout << "Component apply complete, EID=" << unsigned(eid) - << ", COMPONENT_VERSION=" << compVersion << "\n"; + info( + "Component apply complete, EID = {EID}, COMPONENT_VERSION = {COMP_VERS}", + "EID", unsigned(eid), "COMP_VERS", compVersion); updateManager->updateActivationProgress(); } else { - std::cerr << "Component apply failed, EID=" << unsigned(eid) - << ", COMPONENT_VERSION=" << compVersion - << ", APPLY_RESULT=" << unsigned(applyResult) << "\n"; + error( + "Component apply failed, EID = {EID}, COMPONENT_VERSION = {COMP_VERS}, APPLY_RESULT = {APPLY_RES}", + "EID", unsigned(eid), "COMP_VERS", compVersion, "APPLY_RES", + unsigned(applyResult)); } rc = encode_apply_complete_resp(request->hdr.instance_id, completionCode, responseMsg, sizeof(completionCode)); if (rc) { - std::cerr << "Encoding ApplyComplete response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Encoding ApplyComplete response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return response; } @@ -626,8 +640,8 @@ void DeviceUpdater::sendActivateFirmwareRequest() if (rc) { updateManager->requester.markFree(eid, instanceId); - std::cerr << "encode_activate_firmware_req failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("encode_activate_firmware_req failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } rc = updateManager->handler.registerRequest( @@ -635,8 +649,8 @@ void DeviceUpdater::sendActivateFirmwareRequest() std::move(std::bind_front(&DeviceUpdater::activateFirmware, this))); if (rc) { - std::cerr << "Failed to send ActivateFirmware request, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error("Failed to send ActivateFirmware request, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } } @@ -646,8 +660,8 @@ void DeviceUpdater::activateFirmware(mctp_eid_t eid, const pldm_msg* response, if (response == nullptr || !respMsgLen) { // Handle error scenario - std::cerr << "No response received for ActivateFirmware, EID=" - << unsigned(eid) << "\n"; + error("No response received for ActivateFirmware, EID={EID}", "EID", + unsigned(eid)); return; } @@ -659,17 +673,16 @@ void DeviceUpdater::activateFirmware(mctp_eid_t eid, const pldm_msg* response, if (rc) { // Handle error scenario - std::cerr << "Decoding ActivateFirmware response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("Decoding ActivateFirmware response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } if (completionCode) { // Handle error scenario - std::cerr << "ActivateFirmware response failed with error " - "completion code, EID=" - << unsigned(eid) << ", CC=" << unsigned(completionCode) - << "\n"; + error( + "ActivateFirmware response failed with error completion code, EID = {EID}, CC = {CC}", + "EID", unsigned(eid), "CC", unsigned(completionCode)); return; } diff --git a/fw-update/inventory_manager.cpp b/fw-update/inventory_manager.cpp index cdcbebc7f..0205f1b21 100644 --- a/fw-update/inventory_manager.cpp +++ b/fw-update/inventory_manager.cpp @@ -5,14 +5,15 @@ #include "common/utils.hpp" #include "xyz/openbmc_project/Software/Version/server.hpp" +#include + #include +PHOSPHOR_LOG2_USING; namespace pldm { - namespace fw_update { - void InventoryManager::discoverFDs(const std::vector& eids) { for (const auto& eid : eids) @@ -26,8 +27,9 @@ void InventoryManager::discoverFDs(const std::vector& eids) if (rc) { requester.markFree(eid, instanceId); - std::cerr << "encode_query_device_identifiers_req failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "encode_query_device_identifiers_req failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); continue; } @@ -38,8 +40,9 @@ void InventoryManager::discoverFDs(const std::vector& eids) this))); if (rc) { - std::cerr << "Failed to send QueryDeviceIdentifiers request, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error( + "Failed to send QueryDeviceIdentifiers request, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } } } @@ -50,8 +53,8 @@ void InventoryManager::queryDeviceIdentifiers(mctp_eid_t eid, { if (response == nullptr || !respMsgLen) { - std::cerr << "No response received for QueryDeviceIdentifiers, EID=" - << unsigned(eid) << "\n"; + error("No response received for QueryDeviceIdentifiers, EID={EID}", + "EID", unsigned(eid)); return; } @@ -65,17 +68,17 @@ void InventoryManager::queryDeviceIdentifiers(mctp_eid_t eid, &descriptorCount, &descriptorPtr); if (rc) { - std::cerr << "Decoding QueryDeviceIdentifiers response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Decoding QueryDeviceIdentifiers response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } if (completionCode) { - std::cerr << "QueryDeviceIdentifiers response failed with error " - "completion code, EID=" - << unsigned(eid) << ", CC=" << unsigned(completionCode) - << "\n"; + error( + "QueryDeviceIdentifiers response failed with error completion code, EID={EID}, CC = {CC}", + "EID", unsigned(eid), "CC", unsigned(completionCode)); return; } @@ -90,9 +93,9 @@ void InventoryManager::queryDeviceIdentifiers(mctp_eid_t eid, &descriptorData); if (rc) { - std::cerr - << "Decoding descriptor type, length and value failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error( + "Decoding descriptor type, length and value failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } @@ -114,9 +117,9 @@ void InventoryManager::queryDeviceIdentifiers(mctp_eid_t eid, &vendorDefinedDescriptorData); if (rc) { - std::cerr - << "Decoding Vendor-defined descriptor value failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error( + "Decoding Vendor-defined descriptor value failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } @@ -155,8 +158,8 @@ void InventoryManager::sendGetFirmwareParametersRequest(mctp_eid_t eid) if (rc) { requester.markFree(eid, instanceId); - std::cerr << "encode_get_firmware_parameters_req failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error("encode_get_firmware_parameters_req failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } @@ -167,8 +170,9 @@ void InventoryManager::sendGetFirmwareParametersRequest(mctp_eid_t eid) std::bind_front(&InventoryManager::getFirmwareParameters, this))); if (rc) { - std::cerr << "Failed to send GetFirmwareParameters request, EID=" - << unsigned(eid) << ", RC=" << rc << "\n "; + error( + "Failed to send GetFirmwareParameters request, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); } } @@ -178,8 +182,8 @@ void InventoryManager::getFirmwareParameters(mctp_eid_t eid, { if (response == nullptr || !respMsgLen) { - std::cerr << "No response received for GetFirmwareParameters, EID=" - << unsigned(eid) << "\n"; + error("No response received for GetFirmwareParameters, EID={EID}", + "EID", unsigned(eid)); descriptorMap.erase(eid); return; } @@ -194,17 +198,17 @@ void InventoryManager::getFirmwareParameters(mctp_eid_t eid, &pendingCompImageSetVerStr, &compParamTable); if (rc) { - std::cerr << "Decoding GetFirmwareParameters response failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Decoding GetFirmwareParameters response failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } if (fwParams.completion_code) { - std::cerr << "GetFirmwareParameters response failed with error " - "completion code, EID=" - << unsigned(eid) - << ", CC=" << unsigned(fwParams.completion_code) << "\n"; + error( + "GetFirmwareParameters response failed with error completion code, EID={EID}, CC = {CC}", + "EID", unsigned(eid), "CC", unsigned(fwParams.completion_code)); return; } @@ -222,8 +226,9 @@ void InventoryManager::getFirmwareParameters(mctp_eid_t eid, &pendingCompVerStr); if (rc) { - std::cerr << "Decoding component parameter table entry failed, EID=" - << unsigned(eid) << ", RC=" << rc << "\n"; + error( + "Decoding component parameter table entry failed, EID={EID}, RC = {RC}", + "EID", unsigned(eid), "RC", rc); return; } diff --git a/fw-update/package_parser.cpp b/fw-update/package_parser.cpp index 28cbb6bbc..31025a6f3 100644 --- a/fw-update/package_parser.cpp +++ b/fw-update/package_parser.cpp @@ -5,17 +5,18 @@ #include "common/utils.hpp" +#include #include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace fw_update { - using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; @@ -39,8 +40,8 @@ size_t PackageParser::parseFDIdentificationArea( &compImageSetVersionStr, &recordDescriptors, &fwDevicePkgData); if (rc) { - std::cerr << "Decoding firmware device ID record failed, RC=" << rc - << "\n"; + error("Decoding firmware device ID record failed, RC={RC}", "RC", + rc); throw InternalFailure(); } @@ -56,9 +57,9 @@ size_t PackageParser::parseFDIdentificationArea( &descriptorType, &descriptorData); if (rc) { - std::cerr - << "Decoding descriptor type, length and value failed, RC=" - << rc << "\n"; + error( + "Decoding descriptor type, length and value failed, RC={RC}", + "RC", rc); throw InternalFailure(); } @@ -80,9 +81,9 @@ size_t PackageParser::parseFDIdentificationArea( &descTitleStrType, &descTitleStr, &vendorDefinedDescData); if (rc) { - std::cerr << "Decoding Vendor-defined descriptor value " - "failed, RC=" - << rc << "\n"; + error( + "Decoding Vendor-defined descriptor value failed, RC={RC}", + "RC", rc); throw InternalFailure(); } @@ -151,8 +152,8 @@ size_t PackageParser::parseCompImageInfoArea(ComponentImageCount compImageCount, &compImageInfo, &compVersion); if (rc) { - std::cerr << "Decoding component image information failed, RC=" - << rc << "\n"; + error("Decoding component image information failed, RC={RC}", "RC", + rc); throw InternalFailure(); } @@ -194,12 +195,12 @@ void PackageParser::validatePkgTotalSize(uintmax_t pkgSize) if (compLocOffset != calcPkgSize) { - std::cerr << "Validating the component location offset failed, " - "COMP_VERSION=" - << std::get( - ComponentImageInfoPos::CompVersionPos)>( - componentImageInfo) - << "\n"; + error( + "Validating the component location offset failed, COMP_VERSION={COMP_VERS}", + "COMP_VERS", + std::get( + ComponentImageInfoPos::CompVersionPos)>( + componentImageInfo)); throw InternalFailure(); } @@ -208,9 +209,9 @@ void PackageParser::validatePkgTotalSize(uintmax_t pkgSize) if (calcPkgSize != pkgSize) { - std::cerr - << "Package size does not match calculated package size, PKG_SIZE=" - << pkgSize << " ,CALC_PKG_SIZE=" << calcPkgSize << "\n"; + error( + "Package size does not match calculated package size, PKG_SIZE={PKG_SIZE}, CALC_PKG_SIZE={CALC_PKG_SIZE}", + "PKG_SIZE", pkgSize, "CALC_PKG_SIZE", calcPkgSize); throw InternalFailure(); } } @@ -220,16 +221,16 @@ void PackageParserV1::parse(const std::vector& pkgHdr, { if (pkgHeaderSize != pkgHdr.size()) { - std::cerr << "Package header size is invalid, PKG_HDR_SIZE=" - << pkgHeaderSize << "\n"; + error("Package header size is invalid, PKG_HDR_SIZE={PKG_HDR_SIZE}", + "PKG_HDR_SIZE", pkgHeaderSize); throw InternalFailure(); } size_t offset = sizeof(pldm_package_header_information) + pkgVersion.size(); if (offset + sizeof(DeviceIDRecordCount) >= pkgHeaderSize) { - std::cerr << "Parsing package header failed, PKG_HDR_SIZE=" - << pkgHeaderSize << "\n"; + error("Parsing package header failed, PKG_HDR_SIZE={PKG_HDR_SIZE}", + "PKG_HDR_SIZE", pkgHeaderSize); throw InternalFailure(); } @@ -239,15 +240,15 @@ void PackageParserV1::parse(const std::vector& pkgHdr, offset = parseFDIdentificationArea(deviceIdRecCount, pkgHdr, offset); if (deviceIdRecCount != fwDeviceIDRecords.size()) { - std::cerr - << "DeviceIDRecordCount entries not found, DEVICE_ID_REC_COUNT=" - << deviceIdRecCount << "\n"; + error( + "DeviceIDRecordCount entries not found, DEVICE_ID_REC_COUNT={DEVICE_ID_REC_CNT}", + "DEVICE_ID_REC_CNT", deviceIdRecCount); throw InternalFailure(); } if (offset + sizeof(ComponentImageCount) >= pkgHeaderSize) { - std::cerr << "Parsing package header failed, PKG_HDR_SIZE=" - << pkgHeaderSize << "\n"; + error("Parsing package header failed, PKG_HDR_SIZE={PKG_HDR_SIZE}", + "PKG_HDR_SIZE", pkgHeaderSize); throw InternalFailure(); } @@ -258,15 +259,16 @@ void PackageParserV1::parse(const std::vector& pkgHdr, offset = parseCompImageInfoArea(compImageCount, pkgHdr, offset); if (compImageCount != componentImageInfos.size()) { - std::cerr << "ComponentImageCount entries not found, COMP_IMAGE_COUNT=" - << compImageCount << "\n"; + error( + "ComponentImageCount entries not found, COMP_IMAGE_COUNT={COMP_IMAGE_COUNT}", + "COMP_IMAGE_COUNT", compImageCount); throw InternalFailure(); } if (offset + sizeof(PackageHeaderChecksum) != pkgHeaderSize) { - std::cerr << "Parsing package header failed, PKG_HDR_SIZE=" - << pkgHeaderSize << "\n"; + error("Parsing package header failed, PKG_HDR_SIZE={PKG_HDR_SIZE}", + "PKG_HDR_SIZE", pkgHeaderSize); throw InternalFailure(); } @@ -276,8 +278,9 @@ void PackageParserV1::parse(const std::vector& pkgHdr, (pkgHdr[offset + 2] << 16) | (pkgHdr[offset + 3] << 24))); if (calcChecksum != checksum) { - std::cerr << "Parsing package header failed, CALC_CHECKSUM=" - << calcChecksum << ", PKG_HDR_CHECKSUM=" << checksum << "\n"; + error( + "Parsing package header failed, CALC_CHECKSUM={CALC_CHECKSUM}, PKG_HDR_CHECKSUM={KEY1}", + "CALC_CHECKSUM", calcChecksum, "PKG_HDR_CHECKSUM", checksum); throw InternalFailure(); } @@ -297,8 +300,8 @@ std::unique_ptr parsePkgHeader(std::vector& pkgData) &pkgHeader, &pkgVersion); if (rc) { - std::cerr << "Decoding PLDM package header information failed, RC=" - << rc << "\n"; + error("Decoding PLDM package header information failed, RC={RC}", "RC", + rc); return nullptr; } diff --git a/fw-update/test/meson.build b/fw-update/test/meson.build index b85ed08a4..dee33f01e 100644 --- a/fw-update/test/meson.build +++ b/fw-update/test/meson.build @@ -23,6 +23,7 @@ foreach t : tests fw_update_test_src, gmock, gtest, + phosphor_logging_dep, libpldm_dep, libpldmutils, nlohmann_json, diff --git a/fw-update/update_manager.cpp b/fw-update/update_manager.cpp index 86ff0072c..6313169da 100644 --- a/fw-update/update_manager.cpp +++ b/fw-update/update_manager.cpp @@ -4,11 +4,14 @@ #include "common/utils.hpp" #include "package_parser.hpp" +#include + #include #include #include #include #include +PHOSPHOR_LOG2_USING; namespace pldm { @@ -35,9 +38,9 @@ int UpdateManager::processPackage(const std::filesystem::path& packageFilePath) if (activation->activation() == software::Activation::Activations::Activating) { - std::cerr - << "Activation of PLDM FW update package already in progress" - << ", PACKAGE_VERSION=" << parser->pkgVersion << "\n"; + error( + "Activation of PLDM FW update package already in progress, PACKAGE_VERSION={PKG_VERS}", + "PKG_VERS", parser->pkgVersion); std::filesystem::remove(packageFilePath); return -1; } @@ -51,9 +54,9 @@ int UpdateManager::processPackage(const std::filesystem::path& packageFilePath) std::ios::binary | std::ios::in | std::ios::ate); if (!package.good()) { - std::cerr << "Opening the PLDM FW update package failed, ERR=" - << unsigned(errno) << ", PACKAGEFILE=" << packageFilePath - << "\n"; + error( + "Opening the PLDM FW update package failed, ERR={ERR}, PACKAGEFILE={PKG_PATH}", + "ERR", unsigned(errno), "PKG_PATH", packageFilePath.c_str()); package.close(); std::filesystem::remove(packageFilePath); return -1; @@ -62,9 +65,9 @@ int UpdateManager::processPackage(const std::filesystem::path& packageFilePath) uintmax_t packageSize = package.tellg(); if (packageSize < sizeof(pldm_package_header_information)) { - std::cerr << "PLDM FW update package length less than the length of " - "the package header information, PACKAGESIZE=" - << packageSize << "\n"; + error( + "PLDM FW update package length less than the length of the package header information, PACKAGESIZE={PKG_SIZE}", + "PKG_SIZE", packageSize); package.close(); std::filesystem::remove(packageFilePath); return -1; @@ -89,8 +92,7 @@ int UpdateManager::processPackage(const std::filesystem::path& packageFilePath) parser = parsePkgHeader(packageHeader); if (parser == nullptr) { - std::cerr << "Invalid PLDM package header information" - << "\n"; + error("Invalid PLDM package header information"); package.close(); std::filesystem::remove(packageFilePath); return -1; @@ -110,8 +112,7 @@ int UpdateManager::processPackage(const std::filesystem::path& packageFilePath) } catch (const std::exception& e) { - std::cerr << "Invalid PLDM package header" - << "\n"; + error("Invalid PLDM package header"); activation = std::make_unique( pldm::utils::DBusHandler::getBus(), objPath, software::Activation::Activations::Invalid, this); @@ -125,9 +126,8 @@ int UpdateManager::processPackage(const std::filesystem::path& packageFilePath) totalNumComponentUpdates); if (!deviceUpdaterInfos.size()) { - std::cerr - << "No matching devices found with the PLDM firmware update package" - << "\n"; + error( + "No matching devices found with the PLDM firmware update package"); activation = std::make_unique( pldm::utils::DBusHandler::getBus(), objPath, software::Activation::Activations::Invalid, this); @@ -203,11 +203,9 @@ void UpdateManager::updateDeviceCompletion(mctp_eid_t eid, bool status) } auto endTime = std::chrono::steady_clock::now(); - std::cerr << "Firmware update time: " - << std::chrono::duration(endTime - - startTime) - .count() - << " ms\n"; + error("Firmware update time: {DUR} ms", "DUR", + std::chrono::duration(endTime - startTime) + .count()); activation->activation(software::Activation::Activations::Active); } return; diff --git a/host-bmc/dbus/custom_dbus.cpp b/host-bmc/dbus/custom_dbus.cpp index 24d4d6231..55169d0fb 100644 --- a/host-bmc/dbus/custom_dbus.cpp +++ b/host-bmc/dbus/custom_dbus.cpp @@ -5,6 +5,10 @@ #include "serialize.hpp" #include "type.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace dbus @@ -626,8 +630,8 @@ void CustomDBus::removeDBus(const std::vector types) continue; } - std::cerr << "Deleting the dbus objects of type : " << (unsigned)type - << std::endl; + error("Deleting the dbus objects of type : {DBUS_OBJ_TYP}", + "DBUS_OBJ_TYP", (unsigned)type); for (const auto& [path, entites] : savedObjs.at(type)) { deleteObject(path); diff --git a/host-bmc/dbus/deserialize.cpp b/host-bmc/dbus/deserialize.cpp index c7f8dbae7..fa64cabe6 100644 --- a/host-bmc/dbus/deserialize.cpp +++ b/host-bmc/dbus/deserialize.cpp @@ -6,6 +6,9 @@ #include "serialize.hpp" #include +#include + +PHOSPHOR_LOG2_USING; namespace pldm { @@ -179,8 +182,8 @@ std::pair, std::set> if (!fs::exists(path) || fs::is_empty(path)) { - std::cerr << "The file does not exist or is empty, FILE_PATH = " << path - << std::endl; + error("The file does not exist or is empty, FILE_PATH = {FILE_PATH}", + "FILE_PATH", path.c_str()); return std::make_pair(restoreTypes, storeTypes); } @@ -207,8 +210,9 @@ std::pair, std::set> } catch (const std::exception& e) { - std::cerr << "Failed to parse config file, FILE_PATH = " << path - << ", ERROR = " << e.what() << std::endl; + error( + "Failed to parse config file, FILE_PATH = {FILE_PATH}, ERROR = {ERR_EXCEP}", + "FILE_PATH", path.c_str(), "ERR_EXCEP", e.what()); } return std::make_pair(restoreTypes, storeTypes); @@ -239,7 +243,7 @@ void restoreDbusObj(HostPDRHandler* hostPDRHandler) continue; } - std::cout << "Restoring dbus of type : " << type << std::endl; + info("Restoring dbus of type : {DBUS_TYP}", "DBUS_TYP", type); // updateObjectPathMaps(); for (auto& [path, entites] : objs) { @@ -253,9 +257,8 @@ void restoreDbusObj(HostPDRHandler* hostPDRHandler) { if (!ibmDbusHandler.contains(name)) { - std::cerr - << "name is not in ibmDbusHandler, name = " << name - << std::endl; + error("name is not in ibmDbusHandler, name = {NAME}", + "NAME", name); continue; } ibmDbusHandler.at(name)(path, propertyValue); diff --git a/host-bmc/dbus/led_group.cpp b/host-bmc/dbus/led_group.cpp index c598973cd..cf85c2f88 100644 --- a/host-bmc/dbus/led_group.cpp +++ b/host-bmc/dbus/led_group.cpp @@ -2,6 +2,10 @@ #include "libpldm/state_set.h" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace dbus @@ -41,13 +45,14 @@ bool LEDGroup::asserted(bool value) hostEffecterParser->getPldmPDR(), entity.entity_type, entity.entity_instance_num, entity.entity_container_id, PLDM_STATE_SET_IDENTIFY_STATE, false); - std::cerr << "Setting the led on : [ " << objectPath << "] ,[ " - << entity.entity_type << " , " - << entity.entity_instance_num << " , " - << entity.entity_container_id << " ] , effecter ID : [ " - << effecterId << " ] , current value : [ " - << std::boolalpha << asserted() << " ] new value : [ " - << value << " ] " << std::endl; + auto curVal = asserted() ? "true" : "false"; + error( + "Setting the led on : [ {OBJ_PATH} ], [{ENTITY_TYP}, {ENTITY_NUM}, {ENTITY_ID}] effecter ID : [ {EFFECTER_ID} ] , current value : [ {CUR_VAL} ], new value : [ {NEW_VAL} ]", + "OBJ_PATH", objectPath, "ENTITY_TYP", + static_cast(entity.entity_type), "ENTITY_NUM", + static_cast(entity.entity_instance_num), "ENTITY_ID", + static_cast(entity.entity_container_id), + "EFFECTER_ID", effecterId, "CUR_VAL", curVal, "NEW_VAL", value); hostEffecterParser->sendSetStateEffecterStates( mctpEid, effecterId, 1, stateField, std::bind(std::mem_fn(&pldm::dbus::LEDGroup::updateAsserted), diff --git a/host-bmc/dbus/linkreset.cpp b/host-bmc/dbus/linkreset.cpp index 95da1d8eb..3047fffb7 100644 --- a/host-bmc/dbus/linkreset.cpp +++ b/host-bmc/dbus/linkreset.cpp @@ -4,11 +4,14 @@ #include "libpldm/state_set.h" #include "libpldm/states.h" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace dbus { - bool Link::linkReset(bool value) { std::vector stateField; @@ -27,7 +30,7 @@ bool Link::linkReset(bool value) if (value && hostEffecterParser) { - std::cerr << "Got a link reset request on : " << path << std::endl; + error("Got a link reset request on : {PATH}", "PATH", path.c_str()); uint16_t effecterID = getEffecterID(); if (effecterID == 0) @@ -35,13 +38,15 @@ bool Link::linkReset(bool value) return false; } - std::cerr - << "[link reset] : Sending a effecter call to host with effecter id: " - << effecterID << std::endl; + error( + "[link reset] : Sending a effecter call to host with effecter id: {EFFECTER_ID}", + "EFFECTER_ID", effecterID); hostEffecterParser->sendSetStateEffecterStates( mctpEid, effecterID, 1, stateField, nullptr, value); - std::cerr << "Link reset on path : " << path - << " is successful setting it back to false" << std::endl; + error( + "Link reset on path : {PATH} is successful setting it back to false", + "PATH", path.c_str()); + return sdbusplus::com::ibm::Control::Host::server::PCIeLink::linkReset( false); } @@ -60,9 +65,9 @@ uint16_t Link::getEffecterID() if (stateEffecterPDRs.empty()) { - std::cerr - << "PCIe LinkReset: The state set PDR can not be found, entityType = " - << entityType << std::endl; + error( + "PCIe LinkReset: The state set PDR can not be found, entityType = {ENTITY_TYP}", + "ENTITY_TYP", entityType); return effecterID; } @@ -71,8 +76,8 @@ uint16_t Link::getEffecterID() entityInstance = pldm::responder::utils::getLinkResetInstanceNumber(path); #endif - std::cerr << "CustomDBus: BusID of the link is: " << entityInstance - << std::endl; + error("CustomDBus: BusID of the link is: {ENTITY_INST}", "ENTITY_INST", + entityInstance); for (auto& rep : stateEffecterPDRs) { auto pdr = reinterpret_cast(rep.data()); diff --git a/host-bmc/dbus/pcie_topology.cpp b/host-bmc/dbus/pcie_topology.cpp index 9e1fa45dd..a7fc4e456 100644 --- a/host-bmc/dbus/pcie_topology.cpp +++ b/host-bmc/dbus/pcie_topology.cpp @@ -5,11 +5,14 @@ #include "host-bmc/dbus/custom_dbus.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace dbus { - bool PCIETopology::pcIeTopologyRefresh() const { return sdbusplus::com::ibm::PLDM::server::PCIeTopology:: @@ -157,9 +160,9 @@ uint16_t PCIETopology::getEffecterID() hostEffecterParser->getPldmPDR()); if (stateEffecterPDRs.empty()) { - std::cerr - << "PCIe Topology: The state set PDR can not be found, entityType = " - << entityType << std::endl; + error( + "PCIe Topology: The state set PDR can not be found, entityType = {ENTITY_TYPE}", + "ENTITY_TYPE", entityType); return effecterID; } for (auto& rep : stateEffecterPDRs) diff --git a/host-bmc/dbus/serialize.cpp b/host-bmc/dbus/serialize.cpp index 514584ff7..1a9ed777d 100644 --- a/host-bmc/dbus/serialize.cpp +++ b/host-bmc/dbus/serialize.cpp @@ -8,11 +8,14 @@ #include #include #include +#include #include #include #include +PHOSPHOR_LOG2_USING; + // Register class version with Cereal CEREAL_CLASS_VERSION(pldm::serialize::Serialize, 1) @@ -91,8 +94,8 @@ bool Serialize::deserialize() { if (!fs::exists(filePath)) { - std::cerr << "File does not exist, FILE_PATH = " << filePath - << std::endl; + error("File does not exist, FILE_PATH = {FILE_PATH}", "FILE_PATH", + filePath.c_str()); return false; } @@ -107,8 +110,8 @@ bool Serialize::deserialize() } catch (const cereal::Exception& e) { - std::cerr << "Failed to restore groups, ERROR = " << e.what() - << std::endl; + error("Failed to restore groups, ERROR = {ERR_EXCEP}", "ERR_EXCEP", + e.what()); fs::remove(filePath); } @@ -140,8 +143,9 @@ void Serialize::reSerialize(const std::vector types) { if (savedObjs.contains(type)) { - std::cerr << "Removing objects of type : " << (unsigned)type - << " from the persistent cache\n"; + info( + "Removing objects of type : {OBJ_TYP} from the persistent cache", + "OBJ_TYP", (unsigned)type); savedObjs.erase(savedObjs.find(type)); } } diff --git a/host-bmc/dbus/serialize.hpp b/host-bmc/dbus/serialize.hpp index c5340ee35..0a1a2e63b 100644 --- a/host-bmc/dbus/serialize.hpp +++ b/host-bmc/dbus/serialize.hpp @@ -1,12 +1,10 @@ #pragma once -#include "config.h" - -#include "libpldm/pdr.h" - #include "license_entry.hpp" #include "type.hpp" +#include + #include #include diff --git a/host-bmc/dbus_to_event_handler.cpp b/host-bmc/dbus_to_event_handler.cpp index 4851a2711..223078ec3 100644 --- a/host-bmc/dbus_to_event_handler.cpp +++ b/host-bmc/dbus_to_event_handler.cpp @@ -4,6 +4,10 @@ #include "libpldmresponder/pdr.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace pldm::dbus_api; @@ -40,8 +44,8 @@ void DbusToPLDMEvent::sendEventMsg(uint8_t eventType, if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_platform_event_message_req, rc = " << rc - << std::endl; + error("Failed to encode_platform_event_message_req, rc = {RC}", "RC", + rc); return; } @@ -49,8 +53,7 @@ void DbusToPLDMEvent::sendEventMsg(uint8_t eventType, [](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr - << "Failed to receive response for platform event message \n"; + error("Failed to receive response for platform event message"); return; } uint8_t completionCode{}; @@ -59,10 +62,9 @@ void DbusToPLDMEvent::sendEventMsg(uint8_t eventType, &completionCode, &status); if (rc || completionCode) { - std::cerr << "Failed to decode_platform_event_message_resp: " - << "rc=" << rc - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_platform_event_message_resp: rc = {RC}, cc = {CC}", + "RC", rc, "CC", static_cast(completionCode)); } }; @@ -71,7 +73,7 @@ void DbusToPLDMEvent::sendEventMsg(uint8_t eventType, std::move(requestMsg), std::move(platformEventMessageResponseHandler)); if (rc) { - std::cerr << "Failed to send the platform event message \n"; + error("Failed to send the platform event message"); } } diff --git a/host-bmc/dbus_to_host_effecters.cpp b/host-bmc/dbus_to_host_effecters.cpp index cb3016edd..6b6187412 100644 --- a/host-bmc/dbus_to_host_effecters.cpp +++ b/host-bmc/dbus_to_host_effecters.cpp @@ -4,12 +4,15 @@ #include "libpldm/platform.h" #include "libpldm/pldm.h" +#include #include #include #include #include +PHOSPHOR_LOG2_USING; + using namespace pldm::utils; namespace pldm @@ -38,15 +41,16 @@ void HostEffecterParser::parseEffecterJson(const std::string& jsonPath) fs::path jsonDir(jsonPath); if (!fs::exists(jsonDir) || fs::is_empty(jsonDir)) { - std::cerr << "Host Effecter json path does not exist, DIR=" << jsonPath - << "\n"; + error("Host Effecter json path does not exist, DIR = {JSON_PATH}", + "JSON_PATH", jsonPath.c_str()); return; } fs::path jsonFilePath = jsonDir / hostEffecterJson; if (!fs::exists(jsonFilePath)) { - std::cerr << "json does not exist, PATH=" << jsonFilePath << "\n"; + error("json does not exist, PATH = {JSON_PATH}", "JSON_PATH", + jsonFilePath.c_str()); throw InternalFailure(); } @@ -54,7 +58,8 @@ void HostEffecterParser::parseEffecterJson(const std::string& jsonPath) auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing json file failed, FILE=" << jsonFilePath << "\n"; + error("Parsing json file failed, FILE = {JSON_PATH}", "JSON_PATH", + jsonFilePath.c_str()); throw InternalFailure(); } const Json empty{}; @@ -96,11 +101,10 @@ void HostEffecterParser::parseEffecterJson(const std::string& jsonPath) auto states = state.value("state_values", emptyStates); if (dbusInfo.propertyValues.size() != states.size()) { - std::cerr << "Number of states do not match with" - << " number of D-Bus property values in the json. " - << "Object path " << dbusInfo.dbusMap.objectPath - << " and property " << dbusInfo.dbusMap.propertyName - << " will not be monitored \n"; + error( + "Number of states do not match with number of D-Bus property values in the json. Object path {JSON_OBJ_PATH} and property {DBUS_PROP} will not be monitored", + "JSON_OBJ_PATH", dbusInfo.dbusMap.objectPath.c_str(), + "DBUS_PROP", dbusInfo.dbusMap.propertyName); continue; } for (const auto& s : states) @@ -147,7 +151,7 @@ void HostEffecterParser::processHostEffecterChangeNotification( localOrRemote); if (effecterId == PLDM_INVALID_EFFECTER_ID) { - std::cerr << "Effecter id not found in pdr repo \n"; + error("Effecter id not found in pdr repo"); return; } } @@ -164,21 +168,19 @@ void HostEffecterParser::processHostEffecterChangeNotification( "ProgressStages.SystemInitComplete") && (currHostState != "xyz.openbmc_project.State.Boot.Progress." "ProgressStages.OSRunning") && - (currHostState != "xyz.openbmc_project.State.Boot.Progress." - "ProgressStages.OSStart") && (currHostState != "xyz.openbmc_project.State.Boot.Progress." "ProgressStages.SystemSetup")) { - std::cout << "Host is not up. Current host state: " - << currHostState.c_str() << "\n"; + info("Host is not up. Current host state: {CURR_HOST_STATE}", + "CURR_HOST_STATE", currHostState.c_str()); return; } } catch (const sdbusplus::exception::exception& e) { - std::cerr << "Error in getting current host state. Will still " - "continue to set the host effecter " - << e.what() << std::endl; + error( + "Error in getting current host state. Will still continue to set the host effecter {ERR_EXCEP}", + "ERR_EXCEP", e.what()); } uint8_t newState{}; try @@ -188,8 +190,7 @@ void HostEffecterParser::processHostEffecterChangeNotification( } catch (const std::out_of_range& e) { - std::cerr << "new state not found in json" - << "\n"; + error("new state not found in json"); return; } @@ -213,13 +214,12 @@ void HostEffecterParser::processHostEffecterChangeNotification( } catch (const std::runtime_error& e) { - std::cerr << "Could not set host state effecter \n"; + error("Could not set host state effecter"); return; } if (rc != PLDM_SUCCESS) { - std::cerr << "Could not set the host state effecter, rc= " << rc - << " \n"; + error("Could not set the host state effecter, rc= {RC}", "RC", rc); } } @@ -264,9 +264,9 @@ int HostEffecterParser::sendSetStateEffecterStates( if (rc != PLDM_SUCCESS) { - std::cerr - << "Message encode SetStateEffecterStates failure. PLDM error code = " - << std::hex << std::showbase << rc << "\n"; + error( + "Message encode SetStateEffecterStates failure. PLDM error code = {RC}", + "RC", lg2::hex, rc); requester->markFree(mctpEid, instanceId); return rc; } @@ -275,8 +275,8 @@ int HostEffecterParser::sendSetStateEffecterStates( [=](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for " - << "setStateEffecterStates command \n"; + error( + "Failed to receive response for setStateEffecterStates command"); return; } uint8_t completionCode{}; @@ -284,19 +284,19 @@ int HostEffecterParser::sendSetStateEffecterStates( &completionCode); if (rc) { - std::cerr - << "Failed to decode setStateEffecterStates response, effecter Id : " - << effecterId << " , rc " << rc << "\n"; + error( + "Failed to decode setStateEffecterStates response, effecter Id : {EFFECTER_ID}, rc = {RC}", + "EFFECTER_ID", effecterId, "RC", rc); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SetHostEffecterFailed", pldm::PelSeverity::ERROR); } if (completionCode) { - std::cerr << "Failed to set a Host effecter, effecter Id : " - << effecterId - << " , cc=" << static_cast(completionCode) - << "\n"; + error( + "Failed to set a Host effecter, effecter Id : {EFFECTER_ID}, cc = {CC}", + "EFFECTER_ID", effecterId, "CC", + static_cast(completionCode)); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SetHostEffecterFailed", pldm::PelSeverity::ERROR); @@ -315,7 +315,7 @@ int HostEffecterParser::sendSetStateEffecterStates( std::move(requestMsg), std::move(setStateEffecterStatesRespHandler)); if (rc) { - std::cerr << "Failed to send request to set an effecter on Host \n"; + error("Failed to send request to set an effecter on Host"); } return rc; } diff --git a/host-bmc/dbus_to_host_effecters.hpp b/host-bmc/dbus_to_host_effecters.hpp index 0710f0591..8dae0003c 100644 --- a/host-bmc/dbus_to_host_effecters.hpp +++ b/host-bmc/dbus_to_host_effecters.hpp @@ -5,16 +5,18 @@ #include "pldmd/dbus_impl_requester.hpp" #include "requester/handler.hpp" +#include + #include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace host_effecters { - using DbusChgHostEffecterProps = std::map; @@ -91,8 +93,9 @@ class HostEffecterParser } catch (const std::exception& e) { - std::cerr << "The json file does not exist or malformed, ERROR=" - << e.what() << "\n"; + error( + "The json file does not exist or malformed, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } diff --git a/host-bmc/host_associations_parser.cpp b/host-bmc/host_associations_parser.cpp index c0f2ceb9f..1b5c60846 100644 --- a/host-bmc/host_associations_parser.cpp +++ b/host-bmc/host_associations_parser.cpp @@ -1,10 +1,13 @@ #include "host_associations_parser.hpp" +#include #include #include #include +PHOSPHOR_LOG2_USING; + using namespace pldm::utils; namespace pldm @@ -21,8 +24,8 @@ void HostAssociationsParser::parseHostAssociations(const std::string& jsonPath) fs::path jsonDir(jsonPath); if (!fs::exists(jsonDir) || fs::is_empty(jsonDir)) { - std::cerr << "Host Associations json path does not exist, DIR=" - << jsonPath << "\n"; + error("Host Associations json path does not exist, DIR = {JSON_PATH}", + "JSON_PATH", jsonPath.c_str()); return; } @@ -30,7 +33,8 @@ void HostAssociationsParser::parseHostAssociations(const std::string& jsonPath) if (!fs::exists(jsonFilePath)) { - std::cerr << "json does not exist, PATH=" << jsonFilePath << "\n"; + error("json does not exist, PATH = {JSON_PATH}", "JSON_PATH", + jsonFilePath.c_str()); throw InternalFailure(); } @@ -38,7 +42,8 @@ void HostAssociationsParser::parseHostAssociations(const std::string& jsonPath) auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing json file failed, FILE=" << jsonFilePath << "\n"; + error("Parsing json file failed, FILE = {JSON_PATH}", "JSON_PATH", + jsonFilePath.c_str()); throw InternalFailure(); } const Json empty{}; diff --git a/host-bmc/host_associations_parser.hpp b/host-bmc/host_associations_parser.hpp index fd53e9e25..26893f30e 100644 --- a/host-bmc/host_associations_parser.hpp +++ b/host-bmc/host_associations_parser.hpp @@ -3,16 +3,18 @@ #include "common/types.hpp" #include "common/utils.hpp" +#include + #include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace host_associations { - /** @class HostAssociationsParser * * @brief This class parses the Host Effecter json file and monitors for the @@ -40,8 +42,9 @@ class HostAssociationsParser } catch (const std::exception& e) { - std::cerr << "The json file does not exist or malformed, ERROR=" - << e.what() << "\n"; + error( + "The json file does not exist or malformed, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } diff --git a/host-bmc/host_pdr_handler.cpp b/host-bmc/host_pdr_handler.cpp index f55fbebd5..5ad2c8d7d 100644 --- a/host-bmc/host_pdr_handler.cpp +++ b/host-bmc/host_pdr_handler.cpp @@ -1,10 +1,10 @@ -#include "config.h" - #include "host_pdr_handler.hpp" #include "libpldm/fru.h" #include "libpldm/pldm.h" #include "libpldm/state_set.h" + +#include #ifdef OEM_IBM #include "libpldm/fru_oem_ibm.h" #include "libpldm/pdr_oem_ibm.h" @@ -25,6 +25,8 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace pldm::dbus_api; @@ -120,7 +122,7 @@ HostPDRHandler::HostPDRHandler( auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing Host FRU json file failed" << std::endl; + error("Parsing Host FRU json file failed"); } else { @@ -138,8 +140,8 @@ HostPDRHandler::HostPDRHandler( } catch (const std::exception& e) { - std::cerr << "Parsing Host FRU json file failed, exception = " - << e.what() << std::endl; + error("Parsing Host FRU json file failed, exception = {ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -258,9 +260,9 @@ HostPDRHandler::HostPDRHandler( } catch (const std::exception& e) { - std::cerr - << "Unable to set the slot power state to Off " - << "ERROR=" << e.what() << "\n"; + error( + "Unable to set the slot power state to Off, ERROR = {ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } } @@ -358,7 +360,7 @@ void HostPDRHandler::getHostPDR(uint32_t nextRecordHandle) if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_get_pdr_req, rc = " << rc << std::endl; + error("Failed to encode_get_pdr_req, rc = {RC}", "RC", rc); return; } @@ -368,7 +370,7 @@ void HostPDRHandler::getHostPDR(uint32_t nextRecordHandle) std::move(std::bind_front(&HostPDRHandler::processHostPDRs, this))); if (rc) { - std::cerr << "Failed to send the GetPDR request to Host \n"; + error("Failed to send the GetPDR request to Host"); } } std::string HostPDRHandler::updateLedGroupPath(const std::string& path) @@ -406,16 +408,19 @@ int HostPDRHandler::handleStateSensorEvent( auto ledGroupPath = updateLedGroupPath(entity.first); if (!ledGroupPath.empty()) { - std::cout - << "led state event for [ " << ledGroupPath << " ] , [ " - << node_entity.entity_type << " ," - << node_entity.entity_instance_num << " ," - << node_entity.entity_container_id - << " ] , current value : [ " << std::boolalpha - << CustomDBus::getCustomDBus().getAsserted(ledGroupPath) - << " ] new value : [ " - << bool(state == PLDM_STATE_SET_IDENTIFY_STATE_ASSERTED) - << " ]\n"; + auto currVal = + CustomDBus::getCustomDBus().getAsserted(ledGroupPath) + ? "true" + : "false"; + auto newVal = + bool(state == PLDM_STATE_SET_IDENTIFY_STATE_ASSERTED); + info( + "led state event for [ {LED_GRP_PATH} ], [ {ENTITY_TYP}, {ENTITY_NUM}, {ENTITY_ID}] , current value : [ {CURR_VAL} ] new value : [ {NEW_VAL} ]", + "LED_GRP_PATH", ledGroupPath, "ENTITY_TYP", + (unsigned)node_entity.entity_type, "ENTITY_NUM", + (unsigned)node_entity.entity_instance_num, "ENTITY_ID", + (unsigned)node_entity.entity_container_id, "CURR_VAL", + currVal, "NEW_VAL", (unsigned)newVal); CustomDBus::getCustomDBus().setAsserted( ledGroupPath, node_entity, state == PLDM_STATE_SET_IDENTIFY_STATE_ASSERTED, @@ -431,8 +436,8 @@ int HostPDRHandler::handleStateSensorEvent( stateSetId[0] == PLDM_STATE_SET_HEALTH_STATE && strstr(entity.first.c_str(), "core")) { - std::cerr << "Guard event on CORE : [" << entity.first - << "] \n"; + error("Guard event on CORE : [{ENTITY_FIRST}]", "ENTITY_FIRST", + entity.first.c_str()); } CustomDBus::getCustomDBus().setOperationalStatus( entity.first, state == PLDM_OPERATIONAL_NORMAL, @@ -443,8 +448,7 @@ int HostPDRHandler::handleStateSensorEvent( else if (stateSetId[0] == PLDM_STATE_SET_VERSION) { // There is a version changed on any of the dbus objects - std::cout - << "Got a signal from Host about a possible change in Version\n"; + info("Got a signal from Host about a possible change in Version"); createDbusObjects(); return PLDM_SUCCESS; } @@ -453,8 +457,7 @@ int HostPDRHandler::handleStateSensorEvent( auto rc = stateSensorHandler.eventAction(entry, state); if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to fetch and update D-bus property, rc = " << rc - << std::endl; + error("Failed to fetch and update D-bus property, rc = {RC}", "RC", rc); return rc; } @@ -528,8 +531,7 @@ void HostPDRHandler::mergeEntityAssociations( pldm_find_entity_ref_in_tree(entityTree, entities[0], &node); if (node == nullptr) { - std::cerr - << "\ncould not find referrence of the entity in the tree \n"; + error("could not find referrence of the entity in the tree"); } else { @@ -571,9 +573,9 @@ void HostPDRHandler::mergeEntityAssociations( void HostPDRHandler::sendPDRRepositoryChgEvent(std::vector&& pdrTypes, uint8_t eventDataFormat) { - std::cerr - << "Sending the repo change event after merging the PDRs, MCTP_ID:" - << (unsigned)mctp_eid << std::endl; + error( + "Sending the repo change event after merging the PDRs, MCTP_ID: {MCTP_ID}", + "MCTP_ID", (unsigned)mctp_eid); assert(eventDataFormat == FORMAT_IS_PDR_HANDLES); // Extract from the PDR repo record handles of PDRs we want the host @@ -637,9 +639,8 @@ void HostPDRHandler::sendPDRRepositoryChgEvent(std::vector&& pdrTypes, &firstEntry, eventData, &actualSize, maxSize); if (rc != PLDM_SUCCESS) { - std::cerr - << "Failed to encode_pldm_pdr_repository_chg_event_data, rc = " - << rc << std::endl; + error("Failed to encode_pldm_pdr_repository_chg_event_data, rc = {RC}", + "RC", rc); return; } auto instanceId = requester.getInstanceId(mctp_eid); @@ -654,8 +655,8 @@ void HostPDRHandler::sendPDRRepositoryChgEvent(std::vector&& pdrTypes, if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_platform_event_message_req, rc = " << rc - << std::endl; + error("Failed to encode_platform_event_message_req, rc = {RC}", "RC", + rc); return; } @@ -663,9 +664,8 @@ void HostPDRHandler::sendPDRRepositoryChgEvent(std::vector&& pdrTypes, [](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for the PDR repository " - "changed event" - << "\n"; + error( + "Failed to receive response for the PDR repository changed event"); return; } @@ -676,10 +676,9 @@ void HostPDRHandler::sendPDRRepositoryChgEvent(std::vector&& pdrTypes, &completionCode, &status); if (rc || completionCode) { - std::cerr << "Failed to decode_platform_event_message_resp: " - << "rc=" << rc - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_platform_event_message_resp: {RC}, cc = {CC}", + "RC", rc, "CC", static_cast(completionCode)); } }; @@ -688,8 +687,7 @@ void HostPDRHandler::sendPDRRepositoryChgEvent(std::vector&& pdrTypes, std::move(requestMsg), std::move(platformEventMessageResponseHandler)); if (rc) { - std::cerr << "Failed to send the PDR repository changed event request" - << "\n"; + error("Failed to send the PDR repository changed event request"); } } @@ -736,8 +734,7 @@ void HostPDRHandler::processHostPDRs(mctp_eid_t /*eid*/, uint8_t transferCRC{}; if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for the GetPDR" - " command \n"; + error("Failed to receive response for the GetPDR command"); return; } @@ -750,7 +747,7 @@ void HostPDRHandler::processHostPDRs(mctp_eid_t /*eid*/, memcpy(responsePDRMsg.data(), response, respMsgLen + sizeof(pldm_msg_hdr)); if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to decode_get_pdr_resp, rc = " << rc << std::endl; + error("Failed to decode_get_pdr_resp, rc = {RC}", "RC", rc); return; } else @@ -762,11 +759,10 @@ void HostPDRHandler::processHostPDRs(mctp_eid_t /*eid*/, respCount, &transferCRC); if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Failed to decode_get_pdr_resp: " - << "rc= " - << ", NextRecordhandle :" << rc << nextRecordHandle - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_get_pdr_resp: rc = {RC}, NextRecordhandle : {NXT_RECORD_HNDL}, cc = {CC}", + "RC", rc, "NXT_RECORD_HNDL", nextRecordHandle, "CC", + static_cast(completionCode)); return; } else @@ -805,12 +801,10 @@ void HostPDRHandler::processHostPDRs(mctp_eid_t /*eid*/, terminusHandle = tlpdr->terminus_handle; tid = tlpdr->tid; - std::cerr - << "Got a terminus Locator PDR with TID:" - << (unsigned)tid - << " and Terminus handle:" << terminusHandle - << " with Valid bit as:" << (unsigned)tlpdr->validity - << std::endl; + error( + "Got a terminus Locator PDR with TID: {TID} and Terminus handle: {TERMINUS_HNDL} with Valid bit as: {VALID_BIT}", + "TID", (unsigned)tid, "TERMINUS_HNDL", terminusHandle, + "VALID_BIT", (unsigned)tlpdr->validity); auto terminus_locator_type = tlpdr->terminus_locator_type; if (terminus_locator_type == PLDM_TERMINUS_LOCATOR_TYPE_MCTP_EID) @@ -951,11 +945,11 @@ void HostPDRHandler::processHostPDRs(mctp_eid_t /*eid*/, { pldm_pdr_record* firstRecord = repo->first; pldm_pdr_record* lastRecord = repo->last; - std::cerr << "First Record in the repo after PDR exchange is: " - << firstRecord->record_handle << std::endl; - std::cerr << "Last Record in the repo after PDR exchange is:" - << lastRecord->record_handle << std::endl; - + error( + "First Record in the repo after PDR exchange is: {FIRST_REC_HNDL}", + "FIRST_REC_HNDL", firstRecord->record_handle); + error("Last Record in the repo after PDR exchange is: {LAST_REC_HNDL}", + "LAST_REC_HNDL", lastRecord->record_handle); pldm::hostbmc::utils::updateEntityAssociation( entityAssociations, entityTree, objPathMap, oemPlatformHandler); @@ -972,7 +966,7 @@ void HostPDRHandler::processHostPDRs(mctp_eid_t /*eid*/, this->createDbusObjects(); if (isHostUp()) { - std::cout << "Host is UP & Completed the PDR Exchange with host\n"; + info("Host is UP & Completed the PDR Exchange with host"); this->setHostSensorState(); } @@ -1049,8 +1043,8 @@ void HostPDRHandler::setHostFirmwareCondition() PLDM_BASE, request); if (rc != PLDM_SUCCESS) { - std::cerr << "GetPLDMVersion encode failure. PLDM error code = " - << std::hex << std::showbase << rc << "\n"; + error("GetPLDMVersion encode failure. PLDM error code = {RC}", "RC", + lg2::hex, rc); requester.markFree(mctp_eid, instanceId); return; } @@ -1060,13 +1054,12 @@ void HostPDRHandler::setHostFirmwareCondition() size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for " - << "getPLDMVersion command, Host seems to be off \n"; + error( + "Failed to receive response for getPLDMVersion command, Host seems to be off"); return; } - std::cout << "Getting the response. PLDM RC = " << std::hex - << std::showbase - << static_cast(response->payload[0]) << "\n"; + error("Getting the response. PLDM RC = {RC}", "RC", lg2::hex, + (uint16_t)response->payload[0]); this->responseReceived = true; }; rc = handler->registerRequest(mctp_eid, instanceId, PLDM_BASE, @@ -1074,7 +1067,7 @@ void HostPDRHandler::setHostFirmwareCondition() std::move(getPLDMVersionHandler)); if (rc) { - std::cerr << "Failed to discover Host state. Assuming Host as off \n"; + error("Failed to discover Host state. Assuming Host as off"); } } @@ -1093,8 +1086,8 @@ void HostPDRHandler::_setHostSensorState() { if (isHostOff) { - std::cerr - << "set host state sensor begin : Host is off, stopped sending sensor state commands\n"; + error( + "set host state sensor begin : Host is off, stopped sending sensor state commands"); return; } if (sensorIndex != stateSensorPDRs.end()) @@ -1106,7 +1099,7 @@ void HostPDRHandler::_setHostSensorState() if (!pdr) { - std::cerr << "Failed to get State sensor PDR" << std::endl; + error("Failed to get State sensor PDR"); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SetHostSensorState.GetStateSensorPDRFail", pldm::PelSeverity::ERROR); @@ -1139,9 +1132,9 @@ void HostPDRHandler::_setHostSensorState() if (rc != PLDM_SUCCESS) { requester.markFree(mctpEid, instanceId); - std::cerr << "Failed to " - "encode_get_state_sensor_readings_req, rc = " - << rc << " SensorId=" << sensorId << std::endl; + error( + "Failed to encode_get_state_sensor_readings_req, rc = {RC}, SensorId = {SENSOR_ID}", + "RC", rc, "SENSOR_ID", sensorId); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SetHostSensorState.EncodeStateSensorFail", pldm::PelSeverity::ERROR); @@ -1153,14 +1146,13 @@ void HostPDRHandler::_setHostSensorState() size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr - << "Failed to receive response for " - "getStateSensorReading command for sensor id=" - << sensorId << std::endl; + error( + "Failed to receive response for getStateSensorReading command for sensor id = {SENSOR_ID}", + "SENSOR_ID", sensorId); if (this->isHostOff) { - std::cerr - << "set host state sensor : Host is off, stopped sending sensor state commands\n"; + error( + "set host state sensor : Host is off, stopped sending sensor state commands"); return; } if (sensorIndex == stateSensorPDRs.end()) @@ -1181,12 +1173,10 @@ void HostPDRHandler::_setHostSensorState() if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr - << "Failed to " - "decode_get_state_sensor_readings_resp, rc = " - << rc - << " cc=" << static_cast(completionCode) - << " SensorId=" << sensorId << std::endl; + error( + "Failed to decode_get_state_sensor_readings_resp, rc = {RC} cc = {CC} SensorId = {SENSOR_ID}", + "RC", rc, "CC", (unsigned)completionCode, + "SENSOR_ID", sensorId); if (sensorIndex == stateSensorPDRs.end()) { return; @@ -1233,17 +1223,16 @@ void HostPDRHandler::_setHostSensorState() } catch (const std::out_of_range& e) { - std::cerr << "No mapping for the events" - << std::endl; + error("No mapping for the events"); continue; } } if (sensorOffset > compositeSensorStates.size()) { - std::cerr - << " Error Invalid data, Invalid sensor offset," - << " SensorId=" << sensorId << std::endl; + error( + "Error Invalid data, Invalid sensor offset, SensorId = {SENSOR_ID}", + "SENSOR_ID", sensorId); return; } @@ -1252,9 +1241,9 @@ void HostPDRHandler::_setHostSensorState() if (possibleStates.find(eventState) == possibleStates.end()) { - std::cerr - << " Error invalid_data, Invalid event state," - << " SensorId=" << sensorId << std::endl; + error( + "Error invalid_data, Invalid event state, SensorId = {SENSOR_ID}", + "SENSOR_ID", sensorId); return; } const auto& [containerId, entityType, @@ -1282,9 +1271,9 @@ void HostPDRHandler::_setHostSensorState() if (rc != PLDM_SUCCESS) { - std::cerr << " Failed to send request to get State sensor " - "reading on Host," - << " SensorId=" << sensorId << std::endl; + error( + " Failed to send request to get State sensor reading on Host, SensorId={SENSOR_ID}", + "SENSOR_ID", sensorId); } } } @@ -1304,8 +1293,8 @@ void HostPDRHandler::getFRURecordTableMetadataByHost() if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_get_fru_record_table_metadata_req, rc = " - << rc << std::endl; + error("Failed to encode_get_fru_record_table_metadata_req, rc = {RC}", + "RC", rc); return; } @@ -1314,8 +1303,8 @@ void HostPDRHandler::getFRURecordTableMetadataByHost() size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for the Get FRU Record " - "Table Metadata\n"; + error( + "Failed to receive response for the Get FRU Record Table Metadata"); return; } @@ -1333,9 +1322,9 @@ void HostPDRHandler::getFRURecordTableMetadataByHost() if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Faile to decode get fru record table metadata resp, " - "Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + error( + "Failed to decode get fru record table metadata resp, Message Error: rc = {RC}, cc = {CC}", + "RC", rc, "CC", (int)cc); return; } @@ -1349,8 +1338,7 @@ void HostPDRHandler::getFRURecordTableMetadataByHost() std::move(getFruRecordTableMetadataResponseHandler)); if (rc != PLDM_SUCCESS) { - std::cerr - << "Failed to send the the Set State Effecter States request\n"; + error("Failed to send the the Set State Effecter States request"); } return; @@ -1377,8 +1365,7 @@ void HostPDRHandler::getFRURecordTableByHost(uint16_t& total_table_records) if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_get_fru_record_table_req, rc = " << rc - << std::endl; + error("Failed to encode_get_fru_record_table_req, rc = {RC}", "RC", rc); return; } @@ -1387,8 +1374,7 @@ void HostPDRHandler::getFRURecordTableByHost(uint16_t& total_table_records) mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for the Get FRU Record " - "Table\n"; + error("Failed to receive response for the Get FRU Record Table"); return; } @@ -1405,9 +1391,9 @@ void HostPDRHandler::getFRURecordTableByHost(uint16_t& total_table_records) if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr - << "Failed to decode get fru record table resp, Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + error( + "Failed to decode get fru record table resp, Message Error: rc = {RC}, cc = {CC}", + "RC", rc, "CC", (int)cc); return; } @@ -1418,7 +1404,7 @@ void HostPDRHandler::getFRURecordTableByHost(uint16_t& total_table_records) { fruRecordData.clear(); - std::cerr << "failed to parse fru recrod data format.\n"; + error("failed to parse fru recrod data format."); return; } @@ -1430,8 +1416,7 @@ void HostPDRHandler::getFRURecordTableByHost(uint16_t& total_table_records) std::move(requestMsg), std::move(getFruRecordTableResponseHandler)); if (rc != PLDM_SUCCESS) { - std::cerr - << "Failed to send the the Set State Effecter States request\n"; + error("Failed to send the the Set State Effecter States request"); } } @@ -1465,8 +1450,8 @@ void HostPDRHandler::getPresentStateBySensorReadigs( if (rc != PLDM_SUCCESS) { requester.markFree(mctpEid, instanceId); - std::cerr << "Failed to encode_get_state_sensor_readings_req, rc = " - << rc << std::endl; + error("Failed to encode_get_state_sensor_readings_req, rc = {RC}", "RC", + rc); return; } @@ -1476,23 +1461,22 @@ void HostPDRHandler::getPresentStateBySensorReadigs( size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr - << "Failed to receive response for get_state_sensor_readings command, sensor id : " - << sensorId << std::endl; + error( + "Failed to receive response for get_state_sensor_readings command, sensor id : {SENSOR_ID}", + "SENSOR_ID", sensorId); // even when for some reason , if we fail to get a response // to one sensor, try all the dbus objects if (this->isHostOff) { - std::cerr - << "Host is off, stopped sending sensor states command\n"; + error("Host is off, stopped sending sensor states command"); return; } ++sensorMapIndex; if (sensorMapIndex == sensorMap.end()) { - // std::cerr << "sensor map completed\n"; + // error("sensor map completed"); ++objMapIndex; sensorMapIndex = sensorMap.begin(); } @@ -1506,13 +1490,12 @@ void HostPDRHandler::getPresentStateBySensorReadigs( std::array stateField{}; auto responsePtr = reinterpret_cast(response); auto rc = decode_get_state_sensor_readings_resp( - responsePtr, respMsgLen - sizeof(pldm_msg_hdr), &cc, &sensorCnt, - stateField.data()); + responsePtr, respMsgLen, &cc, &sensorCnt, stateField.data()); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Faile to decode get state sensor readings resp, " - "Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + error( + "Failed to decode get state sensor readings resp, Message Error: rc = {RC}, cc = {CC}", + "RC", rc, "CC", (int)cc); ++sensorMapIndex; if (sensorMapIndex == sensorMap.end()) { @@ -1560,7 +1543,7 @@ void HostPDRHandler::getPresentStateBySensorReadigs( ++sensorMapIndex; if (sensorMapIndex == sensorMap.end()) { - // std::cerr << "sensor map completed\n"; + // error("sensor map completed"); ++objMapIndex; sensorMapIndex = sensorMap.begin(); } @@ -1573,7 +1556,7 @@ void HostPDRHandler::getPresentStateBySensorReadigs( std::move(getStateSensorReadingsResponseHandler)); if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to get the State Sensor Readings request\n"; + error("Failed to get the State Sensor Readings request"); } return; @@ -1639,11 +1622,12 @@ void HostPDRHandler::setLocationCode( if (tlv.fruFieldType == PLDM_FRU_FIELD_TYPE_VERSION && node.entity_type == PLDM_ENTITY_SYSTEM_CHASSIS) { - std::cout << "Refreshing the mex firmware version : " - << std::string(reinterpret_cast( - tlv.fruFieldValue.data()), - tlv.fruFieldLen) - << std::endl; + auto mex_vers = + std::string(reinterpret_cast( + tlv.fruFieldValue.data()), + tlv.fruFieldLen); + info("Refreshing the mex firmware version : {MEX_VERS}", + "MEX_VERS", mex_vers); CustomDBus::getCustomDBus().setSoftwareVersion( entity.first, std::string(reinterpret_cast( @@ -1767,7 +1751,7 @@ void HostPDRHandler::setAvailabilityState(const std::string& path) void HostPDRHandler::createDbusObjects() { - std::cerr << "Refreshing dbus hosted by pldm Started \n"; + error("Refreshing dbus hosted by pldm Started"); objMapIndex = objPathMap.begin(); @@ -1856,7 +1840,7 @@ void HostPDRHandler::createDbusObjects() // update xyz.openbmc_project.State.Decorator.OperationalStatus setOperationStatus(); - std::cerr << "Refreshing dbus hosted by pldm Completed \n"; + error("Refreshing dbus hosted by pldm Completed"); } void HostPDRHandler::deleteDbusObjects(const std::vector types) @@ -1874,15 +1858,15 @@ void HostPDRHandler::deleteDbusObjects(const std::vector types) continue; } - std::cerr << "Deleting the dbus objects of type : " << (unsigned)type - << std::endl; + error("Deleting the dbus objects of type : {OBJ_TYP} ", "OBJ_TYP", + (unsigned)type); for (const auto& [path, entites] : savedObjs.at(type)) { if (type != (PLDM_ENTITY_PROC | 0x8000)) // other than CPU core object { - std::cout << "Erasing Dbus Path from ObjectMap " << path - << std::endl; + info("Erasing Dbus Path from ObjectMap {DBUS_PATH}", + "DBUS_PATH", path.c_str()); objPathMap.erase(path); // Delete the Mex Led Dbus Object paths auto ledGroupPath = updateLedGroupPath(path); @@ -1949,11 +1933,11 @@ void HostPDRHandler::setRecordPresent(uint32_t recordHandle) recordEntity.entity_instance_num && dbusEntity.entity_container_id == recordEntity.entity_container_id) { - std::cerr << "Removing Host FRU " - << "[ " << path << " ] with entityid [ " - << recordEntity.entity_type << "," - << recordEntity.entity_instance_num << "," - << recordEntity.entity_container_id << "]" << std::endl; + error( + "Removing Host FRU [ {PATH} ] with entityid [ {ENTITY_TYP}, {ENTITY_NUM}, {ENTITY_ID} ]", + "ENTITY_TYP", (unsigned)recordEntity.entity_type, "ENTITY_NUM", + (unsigned)recordEntity.entity_instance_num, "ENTITY_ID", + (unsigned)recordEntity.entity_container_id); // if the record has the same entity id, mark that dbus object as // not present CustomDBus::getCustomDBus().updateItemPresentStatus(path, false); @@ -1968,7 +1952,8 @@ void HostPDRHandler::deletePDRFromRepo(PDRRecordHandles&& recordHandles) { for (auto& recordHandle : recordHandles) { - std::cerr << "Record handle deleted: " << recordHandle << std::endl; + error("Record handle deleted: {REC_HANDLE}", "REC_HANDLE", + recordHandle); this->setRecordPresent(recordHandle); pldm_delete_by_record_handle(repo, recordHandle, true); } diff --git a/host-bmc/test/dbus_to_host_effecter_test.cpp b/host-bmc/test/dbus_to_host_effecter_test.cpp index 76025eb90..526e3a4ae 100644 --- a/host-bmc/test/dbus_to_host_effecter_test.cpp +++ b/host-bmc/test/dbus_to_host_effecter_test.cpp @@ -21,14 +21,14 @@ class MockHostEffecterParser : public HostEffecterParser HostEffecterParser(nullptr, fd, repo, dbusHandler, jsonPath, nullptr) {} - MOCK_METHOD(void, setHostStateEffecter, + MOCK_METHOD(int, setHostStateEffecter, (size_t, std::vector&, uint16_t), - (const override)); + (override)); MOCK_METHOD(void, createHostEffecterMatch, (const std::string&, const std::string&, size_t, size_t, uint16_t), - (const override)); + (override)); const std::vector& gethostEffecterInfo() { diff --git a/host-bmc/test/meson.build b/host-bmc/test/meson.build index 565e04010..da3e54390 100644 --- a/host-bmc/test/meson.build +++ b/host-bmc/test/meson.build @@ -52,6 +52,7 @@ foreach t : tests libpldmutils, nlohmann_json, phosphor_dbus_interfaces, + phosphor_logging_dep, sdbusplus, sdeventplus]), workdir: meson.current_source_dir()) diff --git a/host-bmc/utils.cpp b/host-bmc/utils.cpp index 81aeba2e5..171cf70e2 100644 --- a/host-bmc/utils.cpp +++ b/host-bmc/utils.cpp @@ -5,8 +5,12 @@ #include "common/utils.hpp" #include "utils.hpp" +#include + #include +PHOSPHOR_LOG2_USING; + namespace fs = std::filesystem; namespace pldm { @@ -14,7 +18,6 @@ namespace hostbmc { namespace utils { - Entities getParentEntites(const EntityAssociations& entityAssoc) { Entities parents{}; @@ -195,11 +198,11 @@ void updateEntityAssociation( } catch (const std::exception& e) { - std::cerr - << "Parent entity not found in the entityMaps, type = " - << parent.entity_type - << ", num = " << parent.entity_instance_num - << ", e = " << e.what() << std::endl; + error( + "Parent entity not found in the entityMaps, type = {ENTITY_TYP}, num = {ENTITY_NUM}, e = {ERR_EXCEP}", + "ENTITY_TYP", static_cast(parent.entity_type), + "ENTITY_NUM", static_cast(parent.entity_instance_num), + "ERR_EXCEP", e.what()); found = false; break; } @@ -272,8 +275,9 @@ void setCoreCount(const EntityAssociations& Associations) } catch (const std::exception& e) { - std::cerr << "failed to set the core count property " - << " ERROR=" << e.what() << "\n"; + error( + "failed to set the core count property ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } } diff --git a/libpldmresponder/base.cpp b/libpldmresponder/base.cpp index b18e8ed3d..f82c37828 100644 --- a/libpldmresponder/base.cpp +++ b/libpldmresponder/base.cpp @@ -1,16 +1,20 @@ -#include "config.h" - -#include "libpldm/base.h" - -#include "libpldm/bios.h" -#include "libpldm/fru.h" -#include "libpldm/platform.h" -#include "libpldm/pldm.h" - #include "base.hpp" + #include "common/utils.hpp" #include "libpldmresponder/pdr.hpp" +#include +#include +#include +#include +#include + +#ifdef OEM_IBM +#include +#include +#endif +#include + #include #include #include @@ -23,6 +27,8 @@ #include "libpldm/host.h" #endif +PHOSPHOR_LOG2_USING; + namespace pldm { using Type = uint8_t; @@ -193,8 +199,8 @@ void Handler::processSetEventReceiver( if (rc != PLDM_SUCCESS) { requester.markFree(eid, instanceId); - std::cerr << "Failed to encode_set_event_receiver_req, rc = " - << std::hex << std::showbase << rc << std::endl; + error("Failed to encode_set_event_receiver_req, rc = {RC}", "RC", + lg2::hex, rc); return; } @@ -202,8 +208,7 @@ void Handler::processSetEventReceiver( [](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for " - "setEventReceiver command \n"; + error("Failed to receive response for setEventReceiver command"); return; } @@ -212,9 +217,9 @@ void Handler::processSetEventReceiver( &completionCode); if (rc || completionCode) { - std::cerr << "Failed to decode setEventReceiver command response," - << " rc=" << rc << "cc=" << (unsigned)completionCode - << "\n"; + error( + "Failed to decode setEventReceiver command response, rc = {RC}, cc = {CC}", + "RC", rc, "CC", (unsigned)completionCode); } }; rc = handler->registerRequest( @@ -223,8 +228,7 @@ void Handler::processSetEventReceiver( if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to send the setEventReceiver request" - << "\n"; + error("Failed to send the setEventReceiver request"); } if (oemPlatformHandler) diff --git a/libpldmresponder/base.hpp b/libpldmresponder/base.hpp index 35491df2d..2c3c7d375 100644 --- a/libpldmresponder/base.hpp +++ b/libpldmresponder/base.hpp @@ -1,13 +1,10 @@ #pragma once -#include "config.h" - -#include "libpldm/base.h" - #include "libpldmresponder/platform.hpp" #include "pldmd/handler.hpp" #include "requester/handler.hpp" +#include #include #include diff --git a/libpldmresponder/bios.cpp b/libpldmresponder/bios.cpp index dee51928f..30dd27fd9 100644 --- a/libpldmresponder/bios.cpp +++ b/libpldmresponder/bios.cpp @@ -4,6 +4,8 @@ #include +#include + #include #include #include @@ -13,6 +15,8 @@ #include #include +PHOSPHOR_LOG2_USING; + using namespace pldm::utils; namespace pldm @@ -122,9 +126,9 @@ Response Handler::getDateTime(const pldm_msg* request, size_t /*payloadLength*/) } catch (const sdbusplus::exception_t& e) { - std::cerr << "Error getting time, PATH=" << bmcTimePath - << " TIME INTERACE=" << timeInterface << "\n"; - + error( + "Error getting time, PATH={BMC_TIME_PATH} TIME INTERACE={TIME_INTF}", + "BMC_TIME_PATH", bmcTimePath, "TIME_INTF", timeInterface); return CmdHandler::ccOnlyResponse(request, PLDM_ERROR); } @@ -176,10 +180,10 @@ Response Handler::setDateTime(const pldm_msg* request, size_t payloadLength) } catch (const std::exception& e) { - std::cerr << "Error getting the time sync property, PATH=" - << timeSyncPath << "INTERFACE=" << timeSyncInterface - << "PROPERTY=" << timeSyncProperty << "ERROR=" << e.what() - << "\n"; + error( + "Error getting the time sync property, PATH={TIME_SYNC_PATH} INTERFACE={SYNC_INTERFACE} PROPERTY={SYNC_PROP} ERROR={ERR_EXCEP}", + "TIME_SYNC_PATH", timeSyncPath, "SYNC_INTERFACE", timeSyncInterface, + "SYNC_PROP", timeSyncProperty, "ERR_EXCEP", e.what()); } constexpr auto setTimeInterface = "xyz.openbmc_project.Time.EpochTime"; @@ -206,10 +210,10 @@ Response Handler::setDateTime(const pldm_msg* request, size_t payloadLength) } catch (const std::exception& e) { - std::cerr << "Error Setting time,PATH=" << setTimePath - << "TIME INTERFACE=" << setTimeInterface - << "ERROR=" << e.what() << "\n"; - + error( + "Error Setting time,PATH={SET_TIME_PATH} TIME INTERFACE={TIME_INTERFACE} ERROR={ERR_EXCEP}", + "SET_TIME_PATH", setTimePath, "TIME_INTERFACE", setTimeInterface, + "ERR_EXCEP", e.what()); return ccOnlyResponse(request, PLDM_ERROR); } diff --git a/libpldmresponder/bios.hpp b/libpldmresponder/bios.hpp index 3ec3a5799..7c4c25b9f 100644 --- a/libpldmresponder/bios.hpp +++ b/libpldmresponder/bios.hpp @@ -1,16 +1,13 @@ #pragma once -#include "config.h" - -#include "libpldm/bios.h" -#include "libpldm/bios_table.h" - #include "bios_config.hpp" #include "bios_table.hpp" #include "pldmd/dbus_impl_requester.hpp" #include "pldmd/handler.hpp" #include "requester/handler.hpp" +#include +#include #include #include diff --git a/libpldmresponder/bios_attribute.cpp b/libpldmresponder/bios_attribute.cpp index aa6ff9f51..0923ab59d 100644 --- a/libpldmresponder/bios_attribute.cpp +++ b/libpldmresponder/bios_attribute.cpp @@ -1,5 +1,3 @@ -#include "config.h" - #include "bios_attribute.hpp" #include "bios_config.hpp" diff --git a/libpldmresponder/bios_config.cpp b/libpldmresponder/bios_config.cpp index 27957e0ba..d01b78a57 100644 --- a/libpldmresponder/bios_config.cpp +++ b/libpldmresponder/bios_config.cpp @@ -6,6 +6,7 @@ #include "bios_table.hpp" #include "common/bios_utils.hpp" +#include #include #include @@ -18,6 +19,8 @@ using namespace pldm::dbus_api; using namespace pldm::utils; +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -167,13 +170,17 @@ int BIOSConfig::checkAttributeTable(const Table& table) case PLDM_BIOS_ENUMERATION: case PLDM_BIOS_ENUMERATION_READ_ONLY: { - auto pvNum = - pldm_bios_table_attr_entry_enum_decode_pv_num(entry); + uint8_t pvNum; + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_num_check(entry, + &pvNum); std::vector pvHandls(pvNum); - pldm_bios_table_attr_entry_enum_decode_pv_hdls( + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check( entry, pvHandls.data(), pvHandls.size()); - auto defNum = - pldm_bios_table_attr_entry_enum_decode_def_num(entry); + uint8_t defNum; + pldm_bios_table_attr_entry_enum_decode_def_num_check(entry, + &defNum); std::vector defIndices(defNum); pldm_bios_table_attr_entry_enum_decode_def_indices( entry, defIndices.data(), defIndices.size()); @@ -262,8 +269,10 @@ int BIOSConfig::checkAttributeValueTable(const Table& table) auto strLength = pldm_bios_table_string_entry_decode_string_length(stringEntry); std::vector buffer(strLength + 1 /* sizeof '\0' */); - pldm_bios_table_string_entry_decode_string(stringEntry, buffer.data(), - buffer.size()); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_string_entry_decode_string_check( + stringEntry, buffer.data(), buffer.size()); + attributeName = std::string(buffer.data(), buffer.data() + strLength); if (!biosAttributes.empty()) @@ -290,7 +299,9 @@ int BIOSConfig::checkAttributeValueTable(const Table& table) pldm_bios_table_string_entry_decode_string_length( stringEntry); std::vector buffer(strLength + 1 /* sizeof '\0' */); - pldm_bios_table_string_entry_decode_string( + // Preconditions are upheld therefore no error check + // necessary + pldm_bios_table_string_entry_decode_string_check( stringEntry, buffer.data(), buffer.size()); return std::string(buffer.data(), @@ -300,10 +311,13 @@ int BIOSConfig::checkAttributeValueTable(const Table& table) attributeType = "xyz.openbmc_project.BIOSConfig.Manager." "AttributeType.Enumeration"; - auto pvNum = - pldm_bios_table_attr_entry_enum_decode_pv_num(attrEntry); + uint8_t pvNum; + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_num_check(attrEntry, + &pvNum); std::vector pvHandls(pvNum); - pldm_bios_table_attr_entry_enum_decode_pv_hdls( + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check( attrEntry, pvHandls.data(), pvHandls.size()); // get possible_value @@ -328,8 +342,10 @@ int BIOSConfig::checkAttributeValueTable(const Table& table) currentValue = getValue(pvHandls[handles[i]], *stringTable); } - auto defNum = - pldm_bios_table_attr_entry_enum_decode_def_num(attrEntry); + uint8_t defNum; + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_def_num_check(attrEntry, + &defNum); std::vector defIndices(defNum); pldm_bios_table_attr_entry_enum_decode_def_indices( attrEntry, defIndices.data(), defIndices.size()); @@ -386,9 +402,10 @@ int BIOSConfig::checkAttributeValueTable(const Table& table) attrEntry); auto max = pldm_bios_table_attr_entry_string_decode_max_length( attrEntry); - auto def = - pldm_bios_table_attr_entry_string_decode_def_string_length( - attrEntry); + uint16_t def; + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_string_decode_def_string_length_check( + attrEntry, &def); std::vector defString(def + 1); pldm_bios_table_attr_entry_string_decode_def_string( attrEntry, defString.data(), defString.size()); @@ -468,12 +485,14 @@ void BIOSConfig::updateBaseBIOSTableProperty() } #endif method.append(biosConfigInterface, biosConfigPropertyName, value); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "failed to update BaseBIOSTable property, ERROR=" - << e.what() << "\n"; + error("failed to update BaseBIOSTable property, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -511,7 +530,9 @@ void BIOSConfig::buildAndStoreAttrTables(const Table& stringTable) "org.freedesktop.DBus.Properties", "Get"); method.append(biosInterface, "BaseBIOSTable"); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); std::variant varBiosTable{}; reply.read(varBiosTable); biosTable = std::get(varBiosTable); @@ -521,8 +542,8 @@ void BIOSConfig::buildAndStoreAttrTables(const Table& stringTable) // bios-settings-manager in sync catch (const std::exception& e) { - std::cerr << "Failed to read BaseBIOSTable property, ERROR=" << e.what() - << "\n"; + error("Failed to read BaseBIOSTable property, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } Table attrTable, attrValueTable; @@ -547,8 +568,8 @@ void BIOSConfig::buildAndStoreAttrTables(const Table& stringTable) } catch (const std::exception& e) { - std::cerr << "Construct Table Entry Error, AttributeName = " - << attr->name << std::endl; + error("Construct Table Entry Error, AttributeName = {ATTR_NAME}", + "ATTR_NAME", attr->name); } } @@ -630,16 +651,16 @@ void BIOSConfig::load(const fs::path& filePath, ParseHandler handler) } catch (const std::exception& e) { - std::cerr - << "Failed to parse JSON config file(entry handler) : " - << filePath.c_str() << ", " << e.what() << std::endl; + error( + "Failed to parse JSON config file(entry handler) : {FILE_PATH}, {ERR_EXCEP}", + "FILE_PATH", filePath.c_str(), "ERR_EXCEP", e.what()); } } } catch (const std::exception& e) { - std::cerr << "Failed to parse JSON config file : " - << filePath.c_str() << std::endl; + error("Failed to parse JSON config file : {FILE_PATH}", "FILE_PATH", + filePath.c_str()); } } } @@ -650,8 +671,9 @@ std::string BIOSConfig::decodeStringFromStringEntry( auto strLength = pldm_bios_table_string_entry_decode_string_length(stringEntry); std::vector buffer(strLength + 1 /* sizeof '\0' */); - pldm_bios_table_string_entry_decode_string(stringEntry, buffer.data(), - buffer.size()); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_string_entry_decode_string_check(stringEntry, buffer.data(), + buffer.size()); return std::string(buffer.data(), buffer.data() + strLength); } @@ -662,10 +684,19 @@ std::string { auto attrEntry = pldm_bios_table_attr_find_by_handle( attrTable->data(), attrTable->size(), handle); - auto pvNum = pldm_bios_table_attr_entry_enum_decode_pv_num(attrEntry); + uint8_t pvNum; + int rc = pldm_bios_table_attr_entry_enum_decode_pv_num_check(attrEntry, + &pvNum); + if (rc != PLDM_SUCCESS) + { + throw std::runtime_error( + "Failed to decode BIOS table possible values for attribute entry"); + } + std::vector pvHandls(pvNum); - pldm_bios_table_attr_entry_enum_decode_pv_hdls(attrEntry, pvHandls.data(), - pvHandls.size()); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check( + attrEntry, pvHandls.data(), pvHandls.size()); std::string displayString = std::to_string(pvHandls[index]); @@ -704,10 +735,12 @@ void BIOSConfig::traceBIOSUpdate( for (uint8_t handle : handles) { - std::cout << "BIOS:" << attrName << ", updated to value: " - << displayStringHandle(attrHandle, handle, attrTable, - stringTable) - << ", by BMC: " << std::boolalpha << isBMC << "\n"; + info( + "BIOS:{ATTR_NAME}, updated to value: {VAL}, by BMC: {CHK_BMC}", + "ATTR_NAME", attrName, "VAL", + displayStringHandle(attrHandle, handle, attrTable, + stringTable), + "CHK_BMC", isBMC ? "true" : "false"); } break; } @@ -716,8 +749,10 @@ void BIOSConfig::traceBIOSUpdate( { auto value = table::attribute_value::decodeIntegerEntry(attrValueEntry); - std::cout << "BIOS:" << attrName << ", updated to value: " << value - << ", by BMC:" << std::boolalpha << isBMC << std::endl; + info( + "BIOS: {ATTR_NAME}, updated to value: {NEW_VAL}, by BMC: {BMC_CHK}", + "ATTR_NAME", attrName, "NEW_VAL", value, "BMC_CHK", + isBMC ? "true" : "false"); break; } case PLDM_BIOS_STRING: @@ -725,8 +760,10 @@ void BIOSConfig::traceBIOSUpdate( { auto value = table::attribute_value::decodeStringEntry(attrValueEntry); - std::cout << "BIOS:" << attrName << " updated to value: " << value - << ", by BMC:" << std::boolalpha << isBMC << std::endl; + info( + "BIOS:{ATTR_NAME} updated to value: {NEW_VAL}, by BMC:{BMC_CHK}", + "ATTR_NAME", attrName, "NEW_VAL", value, "BMC_CHK", + isBMC ? "true" : "false"); break; } default: @@ -757,8 +794,8 @@ int BIOSConfig::checkAttrValueToUpdate( } if (value[0] >= pvHdls.size()) { - std::cerr << "Enum: Illgeal index, Index = " << (int)value[0] - << std::endl; + error("Enum: Illgeal index, Index = {ATTR_VAL}", "ATTR_VAL", + (int)value[0]); return PLDM_ERROR_INVALID_DATA; } return PLDM_SUCCESS; @@ -773,8 +810,8 @@ int BIOSConfig::checkAttrValueToUpdate( if (value < lower || value > upper) { - std::cerr << "Integer: out of bound, value = " << value - << std::endl; + error("Integer: out of bound, value = {ATTR_VAL}", "ATTR_VAL", + value); return PLDM_ERROR_INVALID_DATA; } return PLDM_SUCCESS; @@ -788,15 +825,16 @@ int BIOSConfig::checkAttrValueToUpdate( if (value.size() < stringConf.minLength || value.size() > stringConf.maxLength) { - std::cerr << "String: Length error, string = " << value - << " length = " << value.size() << std::endl; + error( + "String: Length error, string = {ATTR_VAL} length {ATTR_VAL_LEN}", + "ATTR_VAL", value, "ATTR_VAL_LEN", value.size()); return PLDM_ERROR_INVALID_LENGTH; } return PLDM_SUCCESS; } default: - std::cerr << "ReadOnly or Unspported type, type = " << attrType - << std::endl; + error("ReadOnly or Unspported type, type = {ATTR_TYP}", "ATTR_TYP", + attrType); return PLDM_ERROR; }; } @@ -861,7 +899,7 @@ int BIOSConfig::setAttrValue(const void* entry, size_t size, bool isBMC, } catch (const std::exception& e) { - std::cerr << "Set attribute value error: " << e.what() << std::endl; + error("Set attribute value error: {ERR_EXCEP}", "ERR_EXCEP", e.what()); return PLDM_ERROR; } @@ -882,7 +920,7 @@ void BIOSConfig::removeTables() } catch (const std::exception& e) { - std::cerr << "Remove the tables error: " << e.what() << std::endl; + error("Remove the tables error: {ERR_EXCEP}", "ERR_EXCEP", e.what()); } } @@ -903,7 +941,7 @@ void BIOSConfig::processBiosAttrChangeNotification( auto stringTable = getBIOSTable(PLDM_BIOS_STRING_TABLE); if (!stringTable.has_value()) { - std::cerr << "BIOS string table unavailable\n"; + error("BIOS string table unavailable"); return; } BIOSStringTable biosStringTable(*stringTable); @@ -914,23 +952,24 @@ void BIOSConfig::processBiosAttrChangeNotification( } catch (const std::invalid_argument& e) { - std::cerr << "Could not find handle for BIOS string, ATTRIBUTE=" - << attrName.c_str() << "\n"; + error("Could not find handle for BIOS string, ATTRIBUTE={ATTR_NAME}", + "ATTR_NAME", attrName.c_str()); return; } auto attrTable = getBIOSTable(PLDM_BIOS_ATTR_TABLE); if (!attrTable.has_value()) { - std::cerr << "Attribute table not present\n"; + error("Attribute table not present"); return; } const struct pldm_bios_attr_table_entry* tableEntry = table::attribute::findByStringHandle(*attrTable, attrNameHdl); if (tableEntry == nullptr) { - std::cerr << "Attribute not found in attribute table, name= " - << attrName.c_str() << "name handle=" << attrNameHdl << "\n"; + error( + "Attribute not found in attribute table, name= {ATTR_NAME} name handle={ATTR_HNDL}", + "ATTR_NAME", attrName.c_str(), "ATTR_HNDL", attrNameHdl); return; } @@ -941,7 +980,7 @@ void BIOSConfig::processBiosAttrChangeNotification( if (!attrValueSrcTable.has_value()) { - std::cerr << "Attribute value table not present\n"; + error("Attribute value table not present"); return; } @@ -950,9 +989,9 @@ void BIOSConfig::processBiosAttrChangeNotification( newValue, attrHdl, attrType, newPropVal); if (rc != PLDM_SUCCESS) { - std::cerr << "Could not update the attribute value table for attribute " - "handle=" - << attrHdl << " and type=" << (uint32_t)attrType << "\n"; + error( + "Could not update the attribute value table for attribute handle={ATTR_HNDL} and type={ATTR_TYP}", + "ATTR_HNDL", attrHdl, "ATTR_TYP", (uint32_t)attrType); return; } auto destTable = table::attribute_value::updateTable( @@ -965,8 +1004,8 @@ void BIOSConfig::processBiosAttrChangeNotification( rc = setAttrValue(newValue.data(), newValue.size(), true, false); if (rc != PLDM_SUCCESS) { - std::cerr << "could not setAttrValue on base bios table and dbus, rc = " - << rc << "\n"; + error("could not setAttrValue on base bios table and dbus, rc = {RC}", + "RC", rc); } } @@ -1010,8 +1049,8 @@ void BIOSConfig::constructPendingAttribute( if (iter == biosAttributes.end()) { - std::cerr << "Wrong attribute name, attributeName = " - << attributeName << std::endl; + error("Wrong attribute name, attributeName = {ATTR_NAME}", + "ATTR_NAME", attributeName); continue; } @@ -1027,8 +1066,8 @@ void BIOSConfig::constructPendingAttribute( type != BIOSConfigManager::AttributeType::String && type != BIOSConfigManager::AttributeType::Integer) { - std::cerr << "Attribute type not supported, attributeType = " - << attributeType << std::endl; + error("Attribute type not supported, attributeType = {ATTR_TYP}", + "ATTR_TYP", attributeType); continue; } diff --git a/libpldmresponder/bios_config.hpp b/libpldmresponder/bios_config.hpp index 124eb3818..1fc9cdd98 100644 --- a/libpldmresponder/bios_config.hpp +++ b/libpldmresponder/bios_config.hpp @@ -8,6 +8,7 @@ #include "requester/handler.hpp" #include +#include #include #include @@ -17,6 +18,8 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -223,8 +226,8 @@ class BIOSConfig } catch (const std::exception& e) { - std::cerr << "Constructs Attribute Error, " << e.what() - << std::endl; + error("Constructs Attribute Error, {ERR_EXCEP}", "ERR_EXCEP", + e.what()); } } diff --git a/libpldmresponder/bios_enum_attribute.cpp b/libpldmresponder/bios_enum_attribute.cpp index 7ef3bb973..e208ddad5 100644 --- a/libpldmresponder/bios_enum_attribute.cpp +++ b/libpldmresponder/bios_enum_attribute.cpp @@ -1,20 +1,21 @@ -#include "config.h" - #include "bios_enum_attribute.hpp" #include "common/utils.hpp" +#include + #include using namespace pldm::utils; +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { namespace bios { - BIOSEnumAttribute::BIOSEnumAttribute(const Json& entry, DBusHandler* const dbusHandler) : BIOSAttribute(entry, dbusHandler) @@ -114,8 +115,8 @@ void BIOSEnumAttribute::buildValMap(const Json& dbusVals) } else { - std::cerr << "Unknown D-Bus property type, TYPE=" - << dBusMap->propertyType << "\n"; + error("Unknown D-Bus property type, TYPE={DBUS_PROP_TYP}", + "DBUS_PROP_TYP", dBusMap->propertyType); throw std::invalid_argument("Unknown D-BUS property type"); } valMap.emplace(value, possibleValues[pos]); @@ -222,9 +223,10 @@ void BIOSEnumAttribute::constructEntry( } catch (const std::invalid_argument& ex) { - std::cerr << "Enum Value " << currValue - << " is not one of the possible values. Error: " - << ex.what() << " for Attribute " << name << '\n'; + error( + "Enum Value {ENUM_VAL} is not one of the possible values. Error:{ERR_EXCEP} for Attribute {ATTR_NAME}", + "ENUM_VAL", currValue, "ERR_EXCEP", ex.what(), "ATTR_NAME", + name); currValueIndices[0] = getValueIndex(defaultValue, possibleValues); } @@ -250,8 +252,8 @@ int BIOSEnumAttribute::updateAttrVal(Table& newValue, uint16_t attrHdl, auto iter = valMap.find(newPropVal); if (iter == valMap.end()) { - std::cerr << "Could not find index for new BIOS enum, value=" - << std::get(newPropVal) << "\n"; + error("Could not find index for new BIOS enum, value={ENUM_VAL}", + "ENUM_VAL", std::get(newPropVal)); return PLDM_ERROR; } auto currentValue = iter->second; diff --git a/libpldmresponder/bios_integer_attribute.cpp b/libpldmresponder/bios_integer_attribute.cpp index 6d00b6fd2..6240753ca 100644 --- a/libpldmresponder/bios_integer_attribute.cpp +++ b/libpldmresponder/bios_integer_attribute.cpp @@ -2,6 +2,10 @@ #include "common/utils.hpp" +#include + +PHOSPHOR_LOG2_USING; + using namespace pldm::utils; namespace pldm @@ -10,7 +14,6 @@ namespace responder { namespace bios { - BIOSIntegerAttribute::BIOSIntegerAttribute(const Json& entry, DBusHandler* const dbusHandler) : BIOSAttribute(entry, dbusHandler) @@ -33,13 +36,12 @@ BIOSIntegerAttribute::BIOSIntegerAttribute(const Json& entry, auto rc = pldm_bios_table_attr_entry_integer_info_check(&info, &errmsg); if (rc != PLDM_SUCCESS) { - std::cerr << "Wrong filed for integer attribute, ATTRIBUTE_NAME=" - << attr.c_str() << " ERRMSG=" << errmsg - << " LOWER_BOUND=" << integerInfo.lowerBound - << " UPPER_BOUND=" << integerInfo.upperBound - << " DEFAULT_VALUE=" << integerInfo.defaultValue - << " SCALAR_INCREMENT=" << integerInfo.scalarIncrement - << "\n"; + error( + "Wrong field for integer attribute, ATTRIBUTE_NAME={ATTR_NAME} ERRMSG= {ERR_MSG} LOWER_BOUND={LOW_BOUND} UPPER_BOUND={UPPER_BOUND} DEFAULT_VALUE={DEF_VAL} SCALAR_INCREMENT={SCALAR_INCREMENT}", + "ATTR_NAME", attr.c_str(), "ERR_MSG", errmsg, "LOW_BOUND", + integerInfo.lowerBound, "UPPER_BOUND", integerInfo.upperBound, + "DEF_VAL", integerInfo.defaultValue, "SCALAR_INCREMENT", + integerInfo.scalarIncrement); throw std::invalid_argument("Wrong field for integer attribute"); } } @@ -95,8 +97,8 @@ void BIOSIntegerAttribute::setAttrValueOnDbus( static_cast(currentValue)); } - std::cerr << "Unsupported property type on dbus: " << dBusMap->propertyType - << std::endl; + error("Unsupported property type on dbus: {DBUS_PROP_TYP}", "DBUS_PROP_TYP", + dBusMap->propertyType); throw std::invalid_argument("dbus type error"); } @@ -137,9 +139,10 @@ void BIOSIntegerAttribute::constructEntry( if (currentValue < (int64_t)integerInfo.lowerBound || currentValue > (int64_t)integerInfo.upperBound) { - std::cerr << "Setting to default value " << integerInfo.defaultValue - << " For Attribute " << name - << " Received value: " << currentValue << std::endl; + error( + "Setting to default value {DEF_VAL} For Attribute {ATTR_NAME} Received value: {CURR_VAL}", + "DEF_VAL", integerInfo.defaultValue, "ATTR_NAME", name, "CURR_VAL", + currentValue); currentValue = integerInfo.defaultValue; } @@ -184,8 +187,8 @@ uint64_t BIOSIntegerAttribute::getAttrValue(const PropertyValue& propertyValue) } else { - std::cerr << "Unsupported property type for getAttrValue: " - << dBusMap->propertyType << std::endl; + error("Unsupported property type for getAttrValue: {DBUS_PROP_TYP}", + "DBUS_PROP_TYP", dBusMap->propertyType); throw std::invalid_argument("dbus type error"); } return value; @@ -208,8 +211,8 @@ uint64_t BIOSIntegerAttribute::getAttrValue() } catch (const std::exception& e) { - std::cerr << "Get Integer Attribute Value Error: AttributeName = " - << name << std::endl; + error("Get Integer Attribute Value Error: AttributeName = {ATTR_NAME}", + "ATTR_NAME", name); return integerInfo.defaultValue; } } diff --git a/libpldmresponder/bios_string_attribute.cpp b/libpldmresponder/bios_string_attribute.cpp index c22ebaca9..bd69fdbb8 100644 --- a/libpldmresponder/bios_string_attribute.cpp +++ b/libpldmresponder/bios_string_attribute.cpp @@ -2,19 +2,22 @@ #include "common/utils.hpp" +#include + #include #include #include using namespace pldm::utils; +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { namespace bios { - BIOSStringAttribute::BIOSStringAttribute(const Json& entry, DBusHandler* const dbusHandler) : BIOSAttribute(entry, dbusHandler) @@ -23,8 +26,9 @@ BIOSStringAttribute::BIOSStringAttribute(const Json& entry, auto iter = strTypeMap.find(strTypeTmp); if (iter == strTypeMap.end()) { - std::cerr << "Wrong string type, STRING_TYPE=" << strTypeTmp - << " ATTRIBUTE_NAME=" << name << "\n"; + error( + "Wrong string type, STRING_TYPE={STRING_TYPE} ATTRIBUTE_NAME={ATTR_NAME}", + "STRING_TYPE", strTypeTmp, "ATTR_NAME", name); throw std::invalid_argument("Wrong string type"); } stringInfo.stringType = static_cast(iter->second); @@ -48,12 +52,11 @@ BIOSStringAttribute::BIOSStringAttribute(const Json& entry, auto rc = pldm_bios_table_attr_entry_string_info_check(&info, &errmsg); if (rc != PLDM_SUCCESS) { - std::cerr << "Wrong field for string attribute, ATTRIBUTE_NAME=" << name - << " ERRMSG=" << errmsg - << " MINIMUM_STRING_LENGTH=" << stringInfo.minLength - << " MAXIMUM_STRING_LENGTH=" << stringInfo.maxLength - << " DEFAULT_STRING_LENGTH=" << stringInfo.defLength - << " DEFAULT_STRING=" << stringInfo.defString << "\n"; + error( + "Wrong field for string attribute, ATTRIBUTE_NAME={ATTR_NAME} ERRMSG={ERR_MSG} MINIMUM_STRING_LENGTH={MIN_LEN} MAXIMUM_STRING_LENGTH={MAX_LEN} DEFAULT_STRING_LENGTH={DEF_LEN} DEFAULT_STRING={DEF_STR}", + "ATTR_NAME", name, "ERR_MSG", errmsg, "MIN_LEN", + stringInfo.minLength, "MAX_LEN", stringInfo.maxLength, "DEF_LEN", + stringInfo.defLength, "DEF_STR", stringInfo.defString); throw std::invalid_argument("Wrong field for string attribute"); } } @@ -86,8 +89,8 @@ std::string BIOSStringAttribute::getAttrValue() } catch (const std::exception& e) { - std::cerr << "Get String Attribute Value Error: AttributeName = " - << name << std::endl; + error("Get String Attribute Value Error: AttributeName = {ATTR_NAME}", + "ATTR_NAME", name); return stringInfo.defString; } } @@ -129,8 +132,9 @@ void BIOSStringAttribute::constructEntry( if (currStr.size() < stringInfo.minLength || currStr.size() > stringInfo.maxLength) { - std::cerr << "Setting to default. Received string size " - << currStr.size() << " For Attribute " << name << std::endl; + error( + "Setting to default. Received string size {STR_SIZE} For Attribute {ATTR_NAME}", + "STR_SIZE", currStr.size(), "ATTR_NAME", name); currStr = stringInfo.defString; } @@ -150,8 +154,8 @@ int BIOSStringAttribute::updateAttrVal(Table& newValue, uint16_t attrHdl, } catch (const std::bad_variant_access& e) { - std::cerr << "invalid value passed for the property, error: " - << e.what() << "\n"; + error("invalid value passed for the property, error: {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } return PLDM_SUCCESS; diff --git a/libpldmresponder/bios_table.cpp b/libpldmresponder/bios_table.cpp index 34fe9ca13..41276f6c2 100644 --- a/libpldmresponder/bios_table.cpp +++ b/libpldmresponder/bios_table.cpp @@ -103,8 +103,9 @@ std::string decodeString(const pldm_bios_string_table_entry* entry) { auto strLength = pldm_bios_table_string_entry_decode_string_length(entry); std::vector buffer(strLength + 1 /* sizeof '\0' */); - pldm_bios_table_string_entry_decode_string(entry, buffer.data(), - buffer.size()); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_string_entry_decode_string_check(entry, buffer.data(), + buffer.size()); return std::string(buffer.data(), buffer.data() + strLength); } const pldm_bios_string_table_entry* constructEntry(Table& table, @@ -113,8 +114,9 @@ const pldm_bios_string_table_entry* constructEntry(Table& table, auto tableSize = table.size(); auto entryLength = pldm_bios_table_string_entry_encode_length(str.length()); table.resize(tableSize + entryLength); - pldm_bios_table_string_entry_encode(table.data() + tableSize, entryLength, - str.c_str(), str.length()); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_string_entry_encode_check( + table.data() + tableSize, entryLength, str.c_str(), str.length()); return reinterpret_cast(table.data() + tableSize); } @@ -155,8 +157,13 @@ const pldm_bios_attr_table_entry* auto tableSize = table.size(); table.resize(tableSize + entryLength, 0); - pldm_bios_table_attr_entry_string_encode(table.data() + tableSize, - entryLength, info); + int rc = pldm_bios_table_attr_entry_string_encode_check( + table.data() + tableSize, entryLength, info); + if (rc != PLDM_SUCCESS) + { + throw std::runtime_error("Failed to encode BIOS table string entry"); + } + return reinterpret_cast(table.data() + tableSize); } @@ -179,8 +186,14 @@ StringField decodeStringEntry(const pldm_bios_attr_table_entry* entry) auto strType = pldm_bios_table_attr_entry_string_decode_string_type(entry); auto minLength = pldm_bios_table_attr_entry_string_decode_min_length(entry); auto maxLength = pldm_bios_table_attr_entry_string_decode_max_length(entry); - auto defLength = - pldm_bios_table_attr_entry_string_decode_def_string_length(entry); + uint16_t defLength; + int rc = pldm_bios_table_attr_entry_string_decode_def_string_length_check( + entry, &defLength); + if (rc != PLDM_SUCCESS) + { + throw std::runtime_error( + "Failed to decode BIOS table string definition length"); + } std::vector buffer(defLength + 1); pldm_bios_table_attr_entry_string_decode_def_string(entry, buffer.data(), @@ -207,8 +220,9 @@ const pldm_bios_attr_table_entry* auto tableSize = table.size(); table.resize(tableSize + entryLength, 0); - pldm_bios_table_attr_entry_enum_encode(table.data() + tableSize, - entryLength, info); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_encode_check(table.data() + tableSize, + entryLength, info); return reinterpret_cast(table.data() + tableSize); @@ -216,10 +230,20 @@ const pldm_bios_attr_table_entry* EnumField decodeEnumEntry(const pldm_bios_attr_table_entry* entry) { - uint8_t pvNum = pldm_bios_table_attr_entry_enum_decode_pv_num(entry); + uint8_t pvNum; + int rc = pldm_bios_table_attr_entry_enum_decode_pv_num_check(entry, &pvNum); + if (rc != PLDM_SUCCESS) + { + throw std::runtime_error( + "Failed to decode the number of possible values for BIOS table enum entry"); + } std::vector pvHdls(pvNum, 0); - pldm_bios_table_attr_entry_enum_decode_pv_hdls(entry, pvHdls.data(), pvNum); - auto defNum = pldm_bios_table_attr_entry_enum_decode_def_num(entry); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check(entry, pvHdls.data(), + pvNum); + // Preconditions are upheld therefore no error check necessary + uint8_t defNum; + pldm_bios_table_attr_entry_enum_decode_def_num_check(entry, &defNum); std::vector defIndices(defNum, 0); pldm_bios_table_attr_entry_enum_decode_def_indices(entry, defIndices.data(), defIndices.size()); diff --git a/libpldmresponder/event_parser.cpp b/libpldmresponder/event_parser.cpp index 6d6ab0aa7..829af2a61 100644 --- a/libpldmresponder/event_parser.cpp +++ b/libpldmresponder/event_parser.cpp @@ -1,5 +1,6 @@ #include "event_parser.hpp" +#include #include #include @@ -7,9 +8,10 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm::responder::events { - namespace fs = std::filesystem; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; @@ -27,8 +29,8 @@ StateSensorHandler::StateSensorHandler(const std::string& dirPath) fs::path dir(dirPath); if (!fs::exists(dir) || fs::is_empty(dir)) { - std::cerr << "Event config directory does not exist or empty, DIR=" - << dirPath << "\n"; + error("Event config directory does not exist or empty, DIR={DIR_PATH}", + "DIR_PATH", dirPath.c_str()); return; } @@ -39,8 +41,8 @@ StateSensorHandler::StateSensorHandler(const std::string& dirPath) auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing Event state sensor JSON file failed, FILE=" - << file.path(); + error("Parsing Event state sensor JSON file failed, FILE={FILE}", + "FILE", file.path().c_str()); continue; } @@ -75,11 +77,11 @@ StateSensorHandler::StateSensorHandler(const std::string& dirPath) (supportedDbusPropertyTypes.find(dbusInfo.propertyType) == supportedDbusPropertyTypes.end())) { - std::cerr << "Invalid dbus config," - << " OBJPATH=" << dbusInfo.objectPath << " INTERFACE=" - << dbusInfo.interface << " PROPERTY_NAME=" - << dbusInfo.propertyName - << " PROPERTY_TYPE=" << dbusInfo.propertyType << "\n"; + error( + "Invalid dbus config, OBJPATH= {OBJ_PATH} INTERFACE={INTF} PROPERTY_NAME={PROP_NAME} PROPERTY_TYPE={PROP_TYP}", + "OBJ_PATH", dbusInfo.objectPath.c_str(), "INTF", + dbusInfo.interface, "PROP_NAME", dbusInfo.propertyName, + "PROP_TYP", dbusInfo.propertyType); continue; } @@ -88,10 +90,10 @@ StateSensorHandler::StateSensorHandler(const std::string& dirPath) if ((eventStates.size() == 0) || (propertyValues.size() == 0) || (eventStates.size() != propertyValues.size())) { - std::cerr << "Invalid event state JSON config," - << " EVENT_STATE_SIZE=" << eventStates.size() - << " PROPERTY_VALUE_SIZE=" << propertyValues.size() - << "\n"; + error( + "Invalid event state JSON config, EVENT_STATE_SIZE={EVENT_STATE_SIZE} PROPERTY_VALUE_SIZE={PROP_VAL_SIZE}", + "EVENT_STATE_SIZE", eventStates.size(), "PROP_VAL_SIZE", + propertyValues.size()); continue; } @@ -145,8 +147,8 @@ int StateSensorHandler::eventAction(StateSensorEntry entry, } catch (const std::out_of_range& e) { - std::cerr << "Invalid event state" << static_cast(state) - << '\n'; + error("Invalid event state {EVENT_STATE}", "EVENT_STATE", + static_cast(state)); return PLDM_ERROR_INVALID_DATA; } @@ -156,10 +158,11 @@ int StateSensorHandler::eventAction(StateSensorEntry entry, } catch (const std::exception& e) { - std::cerr << "Error setting property, ERROR=" << e.what() - << " PROPERTY=" << dbusMapping.propertyName - << " INTERFACE=" << dbusMapping.interface << " PATH=" - << dbusMapping.objectPath << "\n"; + error( + "Error setting property, ERROR={ERR_EXCEP} PROPERTY={DBUS_PROP} INTERFACE={INTF} PATH = {OBJ_PATH}", + "ERR_EXCEP", e.what(), "DBUS_PROP", dbusMapping.propertyName, + "INTF", dbusMapping.interface, "OBJ_PATH", + dbusMapping.objectPath.c_str()); return PLDM_ERROR; } } diff --git a/libpldmresponder/fru.cpp b/libpldmresponder/fru.cpp index 9e074d4bf..7c22af4a6 100644 --- a/libpldmresponder/fru.cpp +++ b/libpldmresponder/fru.cpp @@ -1,24 +1,26 @@ #include "fru.hpp" -#include "libpldm/entity.h" -#include "libpldm/utils.h" - #include "common/utils.hpp" #include "pdr.hpp" -#ifdef OEM_IBM -#include "libpldm/pdr_oem_ibm.h" +#ifdef OEM_IBM #include "oem/ibm/libpldmresponder/utils.hpp" + +#include #endif -#include +#include +#include #include +#include #include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -163,8 +165,8 @@ void FruImpl::buildFRUTable() } catch (const std::exception& e) { - std::cerr << "Look up of inventory objects failed and PLDM FRU table " - "creation failed\n"; + info( + "Look up of inventory objects failed and PLDM FRU table creation failed"); return; } @@ -210,9 +212,9 @@ void FruImpl::buildFRUTable() } catch (const std::exception& e) { - std::cout << "Config JSONs missing for the item " - "interface type, interface = " - << interface.first << "\n"; + error( + "Config JSONs missing for the item interface type, interface = {INTF}", + "INTF", interface.first); break; } } @@ -239,7 +241,9 @@ std::string FruImpl::populatefwVersion() pldm::utils::dbusProperties, "Get"); method.append("xyz.openbmc_project.Association", "endpoints"); std::variant> paths; - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(paths); auto fwRunningVersion = std::get>(paths)[0]; constexpr auto versionIntf = "xyz.openbmc_project.Software.Version"; @@ -249,9 +253,8 @@ std::string FruImpl::populatefwVersion() } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call " - "Asociation, ERROR= " - << e.what() << "\n"; + error("failed to make a d-bus call Asociation, ERROR= {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return {}; } return currentBmcVersion; @@ -401,11 +404,12 @@ void FruImpl::removeIndividualFRU(const std::string& fruObjPath) objectPathToRSIMap.erase(fruObjPath); objToEntityNode.erase(fruObjPath); // sm00 - std::cerr << "Removing Individual FRU " - << "[ " << fruObjPath << " ] " - << "with entityid [ " << removeEntity.entity_type << "," - << removeEntity.entity_instance_num << "," - << removeEntity.entity_container_id << " ]\n"; + error( + "Removing Individual FRU [ {FRU_OBJ_PATH} ] with entityid [ {ENTITY_TYP}, {ENTITY_NUM}, {ENTITY_ID} ]", + "FRU_OBJ_PATH", fruObjPath, "ENTITY_TYP", + static_cast(removeEntity.entity_type), "ENTITY_NUM", + static_cast(removeEntity.entity_instance_num), "ENTITY_ID", + static_cast(removeEntity.entity_container_id)); associatedEntityMap.erase(fruObjPath); // sm00 deleteFruRecord(rsi); @@ -556,14 +560,15 @@ void FruImpl::buildIndividualFRU(const std::string& fruInterface, PLDM_ENTITY_ASSOCIAION_PHYSICAL, false, true, last_container_id); pldm_entity node_entity = pldm_entity_extract(node); objToEntityNode[fruObjectPath] = node_entity; - std::cerr << " Building Individual FRU " - << "[ " << fruObjectPath << " ] " - << "with entityid [ " << node_entity.entity_type << "," - << node_entity.entity_instance_num << "," - << node_entity.entity_container_id << " ] " - << "Parent :[ " << parent.entity_type << "," - << parent.entity_instance_num << "," - << parent.entity_container_id << " ]\n"; + error( + "Building Individual FRU [{FRU_OBJ_PATH}] with entityid [ {ENTITY_TYP}, {ENTITY_NUM}, {ENTITY_ID} ] Parent :[ {P_ENTITY_TYP}, {P_ENTITY_NUM}, {P_ENTITY_ID} ]", + "FRU_OBJ_PATH", fruObjectPath, "ENTITY_TYP", + static_cast(node_entity.entity_type), "ENTITY_NUM", + static_cast(node_entity.entity_instance_num), "ENTITY_ID", + static_cast(node_entity.entity_container_id), + "P_ENTITY_TYP", static_cast(parent.entity_type), + "P_ENTITY_NUM", static_cast(parent.entity_instance_num), + "P_ENTITY_ID", static_cast(parent.entity_container_id)); auto recordInfos = parser.getRecordInfo(fruInterface); // sm00 @@ -597,9 +602,9 @@ void FruImpl::buildIndividualFRU(const std::string& fruInterface, } catch (const std::exception& e) { - std::cout << "Config JSONs missing for the item " - << " in concurrent add path " - << "interface type, interface = " << fruInterface << "\n"; + error( + "Config JSONs missing for the item in concurrent add path interface type, interface = {FRU_INTF}", + "FRU_INTF", fruInterface); } #ifdef OEM_IBM auto lastLocalRecord = pldm_pdr_find_last_local_record(pdrRepo); @@ -712,22 +717,24 @@ void FruImpl::reGenerateStatePDR(const std::string& fruObjectPath, } catch (const InternalFailure& e) { - std::cerr - << "PDR config directory does not exist or empty, TYPE= " - << (unsigned)pdrType << "PATH= " << dirEntry - << " ERROR=" << e.what() << "\n"; + error( + "PDR config directory does not exist or empty, TYPE= {PDR_TYP} PATH= {DIR_PATH} ERROR={ERR_EXCEP}", + "PDR_TYP", (unsigned)pdrType, "DIR_PATH", + dirEntry.path().string(), "ERR_EXCEP", e.what()); // log an error here } catch (const Json::exception& e) { - std::cerr << "Failed parsing PDR JSON file, TYPE= " - << (unsigned)pdrType << " ERROR=" << e.what() << "\n"; + error( + "Failed parsing PDR JSON file, TYPE= {PDR_TYP} ERROR={ERR_EXCEP}", + "PDR_TYP", (unsigned)pdrType, "ERR_EXCEP", e.what()); // log error } catch (const std::exception& e) { - std::cerr << "Failed parsing PDR JSON file, TYPE= " - << (unsigned)pdrType << " ERROR=" << e.what() << "\n"; + error( + "Failed parsing PDR JSON file, TYPE= {PDR_TYP} ERROR={ERR_EXCEP}", + "PDR_TYP", (unsigned)pdrType, "ERR_EXCEP", e.what()); // log appropriate error } } @@ -844,7 +851,9 @@ void FruImpl::subscribeFruPresence( method.append(inventoryObjPath); method.append(0); method.append(std::vector({fruInterface})); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(fruObjPaths); for (const auto& fruObjPath : fruObjPaths) @@ -864,8 +873,9 @@ void FruImpl::subscribeFruPresence( } catch (const std::exception& e) { - std::cerr << "could not subscribe for concurrent maintenance of fru: " - << fruInterface << " error " << e.what() << "\n"; + error( + "could not subscribe for concurrent maintenance of fru: {FRU_INTF} error {ERR_EXCEP}", + "FRU_INTF", fruInterface, "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.CMsubscribeFailure", pldm::PelSeverity::ERROR); @@ -965,9 +975,8 @@ void FruImpl::sendPDRRepositoryChgEventbyPDRHandles( if (rc != PLDM_SUCCESS) { - std::cerr - << "Failed to encode_pldm_pdr_repository_chg_event_data, rc = " - << rc << std::endl; + error("Failed to encode_pldm_pdr_repository_chg_event_data, rc = {RC}", + "RC", static_cast(rc)); return; } auto instanceId = requester.getInstanceId(mctp_eid); @@ -982,17 +991,16 @@ void FruImpl::sendPDRRepositoryChgEventbyPDRHandles( if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_platform_event_message_req, rc = " << rc - << std::endl; + error("Failed to encode_platform_event_message_req, rc = {RC}", "RC", + static_cast(rc)); return; } auto platformEventMessageResponseHandler = [](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for the PDR repository " - "changed event" - << "\n"; + error( + "Failed to receive response for the PDR repository changed event"); return; } uint8_t completionCode{}; @@ -1002,10 +1010,10 @@ void FruImpl::sendPDRRepositoryChgEventbyPDRHandles( &completionCode, &status); if (rc || completionCode) { - std::cerr << "Failed to decode_platform_event_message_resp: " - << "rc=" << rc - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_platform_event_message_resp: rc={RC}, cc={CC}", + "RC", static_cast(rc), "CC", + static_cast(completionCode)); } }; rc = handler->registerRequest( @@ -1013,9 +1021,8 @@ void FruImpl::sendPDRRepositoryChgEventbyPDRHandles( std::move(requestMsg), std::move(platformEventMessageResponseHandler)); if (rc) { - std::cerr << "Failed to send the PDR repository changed event request " - "after CM" - << "\n"; + error( + "Failed to send the PDR repository changed event request after CM"); } } @@ -1054,10 +1061,10 @@ std::vector FruImpl::setStatePDRParams( auto statesSize = set.value("size", 0); if (!statesSize) { - std::cerr << "Malformed PDR JSON return " - "pdrEntry;- no state set " - "info, TYPE=" - << PLDM_STATE_EFFECTER_PDR << "\n"; + error( + "Malformed PDR JSON return pdrEntry;- no state set info, TYPE={INFO_TYP}", + "INFO_TYP", + static_cast(PLDM_STATE_EFFECTER_PDR)); throw InternalFailure(); } pdrSize += sizeof(state_effecter_possible_states) - @@ -1073,7 +1080,7 @@ std::vector FruImpl::setStatePDRParams( reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get state effecter PDR.\n"; + error("Failed to get state effecter PDR."); continue; } pdr->hdr.record_handle = 0; @@ -1181,9 +1188,9 @@ std::vector FruImpl::setStatePDRParams( } catch (const std::exception& e) { - std::cerr - << "D-Bus object path does not exist, effecter ID: " - << pdr->effecter_id << "\n"; + error( + "D-Bus object path does not exist, effecter ID: {EFFECTER_ID}", + "EFFECTER_ID", static_cast(pdr->effecter_id)); } dbusMappings.emplace_back(std::move(dbusMapping)); dbusValMaps.emplace_back(std::move(dbusIdToValMap)); @@ -1221,10 +1228,10 @@ std::vector FruImpl::setStatePDRParams( auto statesSize = set.value("size", 0); if (!statesSize) { - std::cerr << "Malformed PDR JSON return " - "pdrEntry;- no state set " - "info, TYPE=" - << PLDM_STATE_SENSOR_PDR << "\n"; + error( + "Malformed PDR JSON return pdrEntry;- no state set info, TYPE={INFO_TYP}", + "INFO_TYP", + static_cast(PLDM_STATE_SENSOR_PDR)); throw InternalFailure(); } pdrSize += sizeof(state_sensor_possible_states) - @@ -1240,7 +1247,7 @@ std::vector FruImpl::setStatePDRParams( reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get state sensor PDR.\n"; + error("Failed to get state sensor PDR."); continue; } pdr->hdr.record_handle = 0; @@ -1360,8 +1367,9 @@ std::vector FruImpl::setStatePDRParams( } catch (const std::exception& e) { - std::cerr << "D-Bus object path does not exist, sensor ID: " - << pdr->sensor_id << "\n"; + error( + "D-Bus object path does not exist, sensor ID: {SENSOR_ID}", + "SENSOR_ID", static_cast(pdr->sensor_id)); } dbusMappings.emplace_back(std::move(dbusMapping)); dbusValMaps.emplace_back(std::move(dbusIdToValMap)); diff --git a/libpldmresponder/fru.hpp b/libpldmresponder/fru.hpp index 7d1a7f97c..6ff6d828b 100644 --- a/libpldmresponder/fru.hpp +++ b/libpldmresponder/fru.hpp @@ -1,10 +1,5 @@ #pragma once -#include "config.h" - -#include "libpldm/fru.h" -#include "libpldm/pdr.h" - #include "common/utils.hpp" #include "fru_parser.hpp" #include "host-bmc/dbus_to_event_handler.hpp" @@ -14,6 +9,9 @@ #include "pldmd/handler.hpp" #include "requester/handler.hpp" +#include +#include + #include #include diff --git a/libpldmresponder/fru_parser.cpp b/libpldmresponder/fru_parser.cpp index 6326bee46..a440c0078 100644 --- a/libpldmresponder/fru_parser.cpp +++ b/libpldmresponder/fru_parser.cpp @@ -1,23 +1,23 @@ #include "fru_parser.hpp" #include +#include #include #include #include #include +PHOSPHOR_LOG2_USING; + using namespace pldm::responder::dbus; namespace pldm { - namespace responder { - namespace fru_parser { - using Json = nlohmann::json; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; @@ -50,8 +50,9 @@ void FruParser::setupDefaultDBusLookup(const fs::path& masterJsonPath) auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing FRU Dbus Lookup Map config file failed, FILE=" - << masterJsonPath; + error( + "Parsing FRU Dbus Lookup Map config file failed, FILE={JSON_PATH}", + "JSON_PATH", masterJsonPath.c_str()); std::abort(); } std::map defIntfToEntityType; @@ -66,7 +67,7 @@ void FruParser::setupDefaultDBusLookup(const fs::path& masterJsonPath) } catch (const std::exception& e) { - std::cerr << "FRU DBus lookup map format error\n"; + error("FRU DBus lookup map format error"); throw InternalFailure(); } } @@ -118,7 +119,8 @@ void FruParser::setupFruRecordMap(const std::string& dirPath) auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing FRU config file failed, FILE=" << file.path(); + error("Parsing FRU config file failed, FILE={FILE}", "FILE", + file.path().c_str()); throw InternalFailure(); } diff --git a/libpldmresponder/meson.build b/libpldmresponder/meson.build index 70d9ba15d..be6206695 100644 --- a/libpldmresponder/meson.build +++ b/libpldmresponder/meson.build @@ -1,5 +1,6 @@ libpldmresponder_deps = [ phosphor_dbus_interfaces, + phosphor_logging_dep, nlohmann_json, sdbusplus, sdeventplus, diff --git a/libpldmresponder/pdr.hpp b/libpldmresponder/pdr.hpp index f9ebf52ce..d0ec8f1aa 100644 --- a/libpldmresponder/pdr.hpp +++ b/libpldmresponder/pdr.hpp @@ -3,7 +3,6 @@ #include "common/utils.hpp" #include "libpldmresponder/pdr_utils.hpp" -#include #include namespace pldm diff --git a/libpldmresponder/pdr_numeric_effecter.hpp b/libpldmresponder/pdr_numeric_effecter.hpp index e210bf8a6..39430ec86 100644 --- a/libpldmresponder/pdr_numeric_effecter.hpp +++ b/libpldmresponder/pdr_numeric_effecter.hpp @@ -4,15 +4,16 @@ #include "libpldmresponder/pdr_utils.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace responder { - namespace pdr_numeric_effecter { - using Json = nlohmann::json; static const Json empty{}; @@ -41,7 +42,7 @@ void generateNumericEffecterPDR(const DBusInterface& dBusIntf, const Json& json, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get numeric effecter PDR.\n"; + error("Failed to get numeric effecter PDR."); continue; } pdr->hdr.record_handle = 0; @@ -218,9 +219,10 @@ void generateNumericEffecterPDR(const DBusInterface& dBusIntf, const Json& json, } catch (const std::exception& e) { - std::cerr << "D-Bus object path " << objectPath - << " does not exist, numeric effecter ID: " - << pdr->effecter_id << " error : " << e.what() << "\n"; + error( + "D-Bus object path {OBJ_PATH} does not exist, numeric effecter ID: {EFFECTER_ID} error : {ERR_EXCEP}", + "OBJ_PATH", objectPath.c_str(), "EFFECTER_ID", + static_cast(pdr->effecter_id), "ERR_EXCEP", e.what()); } dbusMappings.emplace_back(std::move(dbusMapping)); diff --git a/libpldmresponder/pdr_state_effecter.hpp b/libpldmresponder/pdr_state_effecter.hpp index f37b2a115..5ed3f2163 100644 --- a/libpldmresponder/pdr_state_effecter.hpp +++ b/libpldmresponder/pdr_state_effecter.hpp @@ -1,21 +1,20 @@ #pragma once -#include "libpldm/platform.h" - #include "pdr.hpp" #include "pdr_utils.hpp" -#include +#include + +#include + +PHOSPHOR_LOG2_USING; namespace pldm { - namespace responder { - namespace pdr_state_effecter { - using Json = nlohmann::json; static const Json empty{}; @@ -44,10 +43,9 @@ void generateStateEffecterPDR(const DBusInterface& dBusIntf, const Json& json, auto statesSize = set.value("size", 0); if (!statesSize) { - std::cerr << "Malformed PDR JSON return " - "pdrEntry;- no state set " - "info, TYPE=" - << PLDM_STATE_EFFECTER_PDR << "\n"; + error( + "Malformed PDR JSON return pdrEntry;- no state set info, TYPE={PDR_TYP}", + "PDR_TYP", static_cast(PLDM_STATE_EFFECTER_PDR)); throw InternalFailure(); } pdrSize += sizeof(state_effecter_possible_states) - @@ -62,7 +60,7 @@ void generateStateEffecterPDR(const DBusInterface& dBusIntf, const Json& json, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get state effecter PDR.\n"; + error("Failed to get state effecter PDR."); continue; } pdr->hdr.record_handle = 0; @@ -161,10 +159,11 @@ void generateStateEffecterPDR(const DBusInterface& dBusIntf, const Json& json, } catch (const std::exception& e) { - std::cerr << "D-Bus object " << objectPath - << " does not exist, state effecter ID: " - << pdr->effecter_id << " error : " << e.what() - << "\n"; + error( + "D-Bus object path {OBJ_PATH} does not exist, numeric effecter ID: {EFFECTER_ID} error : {ERR_EXCEP}", + "OBJ_PATH", objectPath.c_str(), "EFFECTER_ID", + static_cast(pdr->effecter_id), "ERR_EXCEP", + e.what()); } dbusMappings.emplace_back(std::move(dbusMapping)); diff --git a/libpldmresponder/pdr_state_sensor.hpp b/libpldmresponder/pdr_state_sensor.hpp index f6c91810f..0665cd526 100644 --- a/libpldmresponder/pdr_state_sensor.hpp +++ b/libpldmresponder/pdr_state_sensor.hpp @@ -7,16 +7,16 @@ #ifdef OEM_IBM #include "libpldm/pdr_oem_ibm.h" #endif +#include + +PHOSPHOR_LOG2_USING; namespace pldm { - namespace responder { - namespace pdr_state_sensor { - using Json = nlohmann::json; static const Json empty{}; @@ -45,10 +45,9 @@ void generateStateSensorPDR(const DBusInterface& dBusIntf, const Json& json, auto statesSize = set.value("size", 0); if (!statesSize) { - std::cerr << "Malformed PDR JSON return " - "pdrEntry;- no state set " - "info, TYPE=" - << PLDM_STATE_SENSOR_PDR << "\n"; + error( + "Malformed PDR JSON return pdrEntry;- no state set info, TYPE={PDR_TYP}", + "PDR_TYP", static_cast(PLDM_STATE_SENSOR_PDR)); throw InternalFailure(); } pdrSize += sizeof(state_sensor_possible_states) - @@ -63,7 +62,7 @@ void generateStateSensorPDR(const DBusInterface& dBusIntf, const Json& json, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get state sensor PDR.\n"; + error("Failed to get state sensor PDR."); continue; } pdr->hdr.record_handle = 0; @@ -127,10 +126,10 @@ void generateStateSensorPDR(const DBusInterface& dBusIntf, const Json& json, { // parent node not found in the entity association tree, // this should not be possible - std::cerr - << "Parent Entity of type " - << parent_entity.entity_type - << " not found in the BMC Entity Association tree\n"; + error( + "Parent Entity of type {P_ENTITY_TYP} not found in the BMC Entity Association tree", + "P_ENTITY_TYP", + static_cast(parent_entity.entity_type)); return; } pldm_entity_association_tree_add( @@ -218,9 +217,11 @@ void generateStateSensorPDR(const DBusInterface& dBusIntf, const Json& json, } catch (const std::exception& e) { - std::cerr << "D-Bus object path " << objectPath - << " does not exist, sensor ID: " << pdr->sensor_id - << " error : " << e.what() << "\n"; + error( + "D-Bus object path {OBJ_PATH} does not exist, sensor ID: {SENSOR_ID} error : {ERR_EXCEP}", + "OBJ_PATH", objectPath.c_str(), "SENSOR_ID", + static_cast(pdr->sensor_id), "ERR_EXCEP", + e.what()); } dbusMappings.emplace_back(std::move(dbusMapping)); diff --git a/libpldmresponder/pdr_utils.cpp b/libpldmresponder/pdr_utils.cpp index 84fd6e20c..79b6b1407 100644 --- a/libpldmresponder/pdr_utils.cpp +++ b/libpldmresponder/pdr_utils.cpp @@ -3,22 +3,23 @@ #include "pdr.hpp" -#include +#include + +#include #include #include +PHOSPHOR_LOG2_USING; + using namespace pldm::pdr; namespace pldm { - namespace responder { - namespace pdr_utils { - pldm_pdr* Repo::getPdr() const { return repo; @@ -83,10 +84,9 @@ StatestoDbusVal populateMapping(const std::string& type, const Json& dBusValues, StatestoDbusVal valueMap; if (dBusValues.size() != pv.size()) { - std::cerr - << "dBusValues size is not equal to pv size, dBusValues Size: " - << dBusValues.size() << ", pv Size: " << pv.size() << "\n"; - + error( + "dBusValues size is not equal to pv size, dBusValues Size: {DBUS_VAL_SIZE}, pv Size: {PV_SIZE}", + "DBUS_VAL_SIZE", dBusValues.size(), "PV_SIZE", pv.size()); return {}; } @@ -134,8 +134,8 @@ StatestoDbusVal populateMapping(const std::string& type, const Json& dBusValues, } else { - std::cerr << "Unknown D-Bus property type, TYPE=" << type.c_str() - << "\n"; + error("Unknown D-Bus property type, TYPE={TYP}", "TYP", + type.c_str()); return {}; } @@ -277,8 +277,8 @@ std::vector fetchBitMap(const std::vector>& pdrs) tempStream << std::setfill('0') << std::setw(2) << std::hex << byte << " "; } - std::cout << "Panel:BitMap received: " << tempStream.str() - << std::endl; + error("Panel:BitMap received: {RECV_STREAM}", "RECV_STREAM", + tempStream.str()); if (compEffCount) { statesPtr += sizeof(state_effecter_possible_states) + diff --git a/libpldmresponder/pdr_utils.hpp b/libpldmresponder/pdr_utils.hpp index cdaa50113..5f6a0e278 100644 --- a/libpldmresponder/pdr_utils.hpp +++ b/libpldmresponder/pdr_utils.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -16,6 +17,8 @@ #include #include +PHOSPHOR_LOG2_USING; + using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; @@ -98,7 +101,7 @@ inline Json readJson(const std::string& path) std::ifstream jsonFile(path); if (!jsonFile.is_open()) { - std::cerr << "Error opening PDR JSON file, PATH=" << path << "\n"; + error("Error opening PDR JSON file, PATH={PDR_JSON}", "PDR_JSON", path); return {}; } diff --git a/libpldmresponder/platform.cpp b/libpldmresponder/platform.cpp index 7dfd1eb62..f201173e1 100644 --- a/libpldmresponder/platform.cpp +++ b/libpldmresponder/platform.cpp @@ -17,12 +17,17 @@ #include "platform_state_effecter.hpp" #include "platform_state_sensor.hpp" -#include +#include +#include + +#include using namespace pldm::utils; using namespace pldm::responder::pdr; using namespace pldm::responder::pdr_utils; +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -68,7 +73,7 @@ void Handler::generate(const pldm::utils::DBusHandler& dBusIntf, { for (const auto& directory : dir) { - std::cerr << "checking if : " << directory << "exists" << std::endl; + info("checking if : {DIR} exists", "DIR", directory.c_str()); if (!fs::exists(directory)) { return; @@ -139,23 +144,25 @@ void Handler::generate(const pldm::utils::DBusHandler& dBusIntf, } catch (const InternalFailure& e) { - std::cerr - << "PDR config directory does not exist or empty, TYPE= " - << pdrType << "PATH= " << dirEntry << " ERROR=" << e.what() - << "\n"; + error( + "PDR config directory does not exist or empty, TYPE= {PDR_TYP} PATH= {DIR_PATH} ERROR={ERR_EXCEP}", + "PDR_TYP", pdrType, "DIR_PATH", dirEntry.path().string(), + "ERR_EXCEP", e.what()); } catch (const Json::exception& e) { - std::cerr << "Failed parsing PDR JSON file, TYPE= " << pdrType - << " ERROR=" << e.what() << "\n"; + error( + "Failed parsing PDR JSON file, TYPE= {PDR_TYP} ERROR={ERR_EXCEP}", + "PDR_TYP", pdrType, "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.Generate.PDRJsonFileParseFail", pldm::PelSeverity::ERROR); } catch (const std::exception& e) { - std::cerr << "Failed parsing PDR JSON file, TYPE= " << pdrType - << " ERROR=" << e.what() << "\n"; + error( + "Failed parsing PDR JSON file, TYPE= {PDR_TYP} ERROR={ERR_EXCEP}", + "PDR_TYP", pdrType, "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.Generate.PDRJsonFileParseFail", pldm::PelSeverity::ERROR); @@ -316,8 +323,8 @@ Response Handler::getPDR(const pldm_msg* request, size_t payloadLength) } catch (const std::exception& e) { - std::cerr << "Error accessing PDR, HANDLE=" << recordHandle - << " ERROR=" << e.what() << "\n"; + error("Error accessing PDR, HANDLE={REC_HNDL} ERROR={ERR_EXCEP}", + "REC_HNDL", recordHandle, "ERR_EXCEP", e.what()); return CmdHandler::ccOnlyResponse(request, PLDM_ERROR); } return response; @@ -559,8 +566,7 @@ int Handler::pldmPDRRepositoryChgEvent(const pldm_msg* request, uint8_t /*formatVersion*/, uint8_t tid, size_t eventDataOffset) { - std::cerr << "Got a repo change event from TID: " << (unsigned)tid - << std::endl; + error("Got a repo change event from TID: {TID}", "TID", (unsigned)tid); uint8_t eventDataFormat{}; uint8_t eventDataOperation{}; uint8_t numberOfChangeRecords{}; @@ -603,8 +609,8 @@ int Handler::pldmPDRRepositoryChgEvent(const pldm_msg* request, return rc; } - std::cout << "pldmPDRRepositoryChgEvent eventDataOperation : " - << (unsigned)eventDataOperation << std::endl; + error("pldmPDRRepositoryChgEvent eventDataOperation : {EVENT_OP}", + "EVENT_OP", (unsigned)eventDataOperation); if (eventDataOperation == PLDM_RECORDS_ADDED || eventDataOperation == PLDM_RECORDS_DELETED) @@ -691,7 +697,8 @@ int Handler::getPDRRecordHandles(const ChangeEntry* changeEntryData, } for (const auto& i : pdrRecordHandles) { - std::cerr << "Record handles sent down to BMC: " << i << std::endl; + error("Record handles sent down to BMC: {PDR_REC_HNDL}", "PDR_REC_HNDL", + static_cast(i)); } return PLDM_SUCCESS; } @@ -870,7 +877,7 @@ bool isOemNumericEffecter(Handler& handler, uint16_t effecterId, if (numericEffecterPDRs.empty()) { - std::cerr << "Failed to get record by PDR type\n"; + error("Failed to get record by PDR type"); return false; } @@ -928,7 +935,7 @@ bool isOemStateSensor(Handler& handler, uint16_t sensorId, getRepoByType(handler.getRepo(), stateSensorPDRs, PLDM_STATE_SENSOR_PDR); if (stateSensorPDRs.empty()) { - std::cerr << "Failed to get record by PDR type\n"; + error("Failed to get record by PDR type"); return false; } @@ -955,10 +962,10 @@ bool isOemStateSensor(Handler& handler, uint16_t sensorId, if (sensorRearmCount > tmpCompSensorCnt) { - std::cerr << "The requester sent wrong sensorRearm" - << " count for the sensor, SENSOR_ID=" << sensorId - << "SENSOR_REARM_COUNT=" << (uint16_t)sensorRearmCount - << "\n"; + error( + "The requester sent wrong sensorRearm count for the sensor, SENSOR_ID={SENSOR_ID} SENSOR_REARM_COUNT={SENSOR_REARM_COUNT}", + "SENSOR_ID", sensorId, "SENSOR_REARM_COUNT", + (uint16_t)sensorRearmCount); break; } @@ -995,7 +1002,7 @@ bool isOemStateEffecter(Handler& handler, uint16_t effecterId, PLDM_STATE_EFFECTER_PDR); if (stateEffecterPDRs.empty()) { - std::cerr << "Failed to get record by PDR type\n"; + error("Failed to get record by PDR type"); return false; } @@ -1021,9 +1028,10 @@ bool isOemStateEffecter(Handler& handler, uint16_t effecterId, if (compEffecterCnt > pdr->composite_effecter_count) { - std::cerr << "The requester sent wrong composite effecter" - << " count for the effecter, EFFECTER_ID=" << effecterId - << "COMP_EFF_CNT=" << (uint16_t)compEffecterCnt << "\n"; + error( + "The requester sent wrong composite effecter count for the effecter, EFFECTER_ID={EFFECTER_ID} COMP_EFF_CNT={COMP_EFF_CNT}", + "EFFECTER_ID", effecterId, "COMP_EFF_CNT", + (uint16_t)compEffecterCnt); return false; } diff --git a/libpldmresponder/platform.hpp b/libpldmresponder/platform.hpp index 4695a33ae..eb1ca5b06 100644 --- a/libpldmresponder/platform.hpp +++ b/libpldmresponder/platform.hpp @@ -1,11 +1,5 @@ #pragma once -#include "config.h" - -#include "libpldm/pdr.h" -#include "libpldm/platform.h" -#include "libpldm/states.h" - #include "common/utils.hpp" #include "event_parser.hpp" #include "fru.hpp" @@ -16,17 +10,23 @@ #include "oem_handler.hpp" #include "pldmd/handler.hpp" +#include +#include +#include #include +#include + #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { namespace platform { - using generatePDR = std::functionpossible_states); if (compEffecterCnt > pdr->composite_effecter_count) { - std::cerr << "The requester sent wrong composite effecter" - << " count for the effecter, EFFECTER_ID=" - << (unsigned)effecterId - << "COMP_EFF_CNT=" << (unsigned)compEffecterCnt - << "\n"; + error( + "The requester sent wrong composite effecter count for the effecter, EFFECTER_ID={EFFECTER_ID} COMP_EFF_CNT={COMP_EFF_CNT}", + "EFFECTER_ID", (unsigned)effecterId, "COMP_EFF_CNT", + (unsigned)compEffecterCnt); return PLDM_ERROR_INVALID_DATA; } break; @@ -387,13 +386,12 @@ class Handler : public CmdHandler if (states->possible_states_size < bitfieldIndex || !(states->states[bitfieldIndex].byte & (1 << bit))) { - std::cerr - << "Invalid state set value, EFFECTER_ID=" - << (unsigned)effecterId << " VALUE=" - << (unsigned)stateField[currState].effecter_state - << " COMPOSITE_EFFECTER_ID=" << (unsigned)currState - << " DBUS_PATH=" << dbusMappings[currState].objectPath - << "\n"; + error( + "Invalid state set value, EFFECTER_ID={EFFECTER_ID} VALUE={VAL} COMPOSITE_EFFECTER_ID={COMP_EFF_ID} DBUS_PATH={DBUS_OBJ_PATH}", + "EFFECTER_ID", (unsigned)effecterId, "VAL", + (unsigned)stateField[currState].effecter_state, + "COMP_EFF_ID", (unsigned)currState, "DBUS_OBJ_PATH", + dbusMappings[currState].objectPath.c_str()); rc = PLDM_PLATFORM_SET_EFFECTER_UNSUPPORTED_SENSORSTATE; break; } @@ -412,12 +410,12 @@ class Handler : public CmdHandler } catch (const std::exception& e) { - std::cerr - << "Error setting property, ERROR=" << e.what() - << " PROPERTY=" << dbusMapping.propertyName - << " INTERFACE=" - << dbusMapping.interface << " PATH=" - << dbusMapping.objectPath << "\n"; + error( + "Error setting property, ERROR={ERR_EXCEP} PROPERTY={DBUS_PROP_NAME} INTERFACE={INTF} PATH={DBUS_OBJ_PATH}", + "ERR_EXCEP", e.what(), "DBUS_PROP_NAME", + dbusMapping.propertyName, "INTF", + dbusMapping.interface, "DBUS_OBJ_PATH", + dbusMapping.objectPath.c_str()); return PLDM_ERROR; } } @@ -432,8 +430,9 @@ class Handler : public CmdHandler } catch (const std::out_of_range& e) { - std::cerr << "the effecterId does not exist. effecter id: " - << (unsigned)effecterId << e.what() << '\n'; + error( + "the effecterId does not exist. effecter id: {EFFECTER_ID}, {ERR_EXCEP}", + "EFFECTER_ID", (unsigned)effecterId, "ERR_EXCEP", e.what()); } return rc; diff --git a/libpldmresponder/platform_numeric_effecter.hpp b/libpldmresponder/platform_numeric_effecter.hpp index 9cf97e644..0770ee5b9 100644 --- a/libpldmresponder/platform_numeric_effecter.hpp +++ b/libpldmresponder/platform_numeric_effecter.hpp @@ -1,28 +1,28 @@ #pragma once -#include "config.h" - -#include "libpldm/platform.h" -#include "libpldm/states.h" - #include "common/utils.hpp" #include "libpldmresponder/pdr.hpp" #include "pdr_utils.hpp" #include "pldmd/handler.hpp" +#include +#include #include #include +#include + #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { namespace platform_numeric_effecter { - /** @brief Function to get the effecter value by PDR factor coefficient, etc. * @param[in] pdr - The structure of pldm_numeric_effecter_value_pdr. * @param[in] effecterValue - effecter value. @@ -223,7 +223,7 @@ std::pair> } else { - std::cerr << "Wrong field effecterDataSize...\n"; + error("Wrong field effecterDataSize..."); return {PLDM_ERROR, {}}; } } @@ -262,7 +262,7 @@ int setNumericEffecterValueHandler(const DBusInterface& dBusIntf, PLDM_NUMERIC_EFFECTER_PDR); if (numericEffecterPDRs.empty()) { - std::cerr << "The Numeric Effecter PDR repo is empty." << std::endl; + error("The Numeric Effecter PDR repo is empty."); return PLDM_ERROR; } @@ -290,7 +290,7 @@ int setNumericEffecterValueHandler(const DBusInterface& dBusIntf, if (effecterValueLength != effecterValueArrayLength) { - std::cerr << "effecter data size is incorrect.\n"; + error("effecter data size is incorrect."); return PLDM_ERROR_INVALID_DATA; } @@ -315,16 +315,18 @@ int setNumericEffecterValueHandler(const DBusInterface& dBusIntf, } catch (const std::exception& e) { - std::cerr << "Error setting property, ERROR=" << e.what() - << " PROPERTY=" << dbusMapping.propertyName - << " INTERFACE=" << dbusMapping.interface << " PATH=" - << dbusMapping.objectPath << "\n"; + error( + "Error setting property, ERROR={ERR_EXCEP} PROPERTY={DBUS_PROP} INTERFACE={DBUS_INTF}, PATH={DBUS_OBJ_PATH}", + "ERR_EXCEP", e.what(), "DBUS_PROP", dbusMapping.propertyName, + "DBUS_INTF", dbusMapping.interface, "DBUS_OBJ_PATH", + dbusMapping.objectPath); return PLDM_ERROR; } } catch (const std::out_of_range& e) { - std::cerr << "Unknown effecter ID : " << effecterId << e.what() << '\n'; + error("Unknown effecter ID : {EFFECTER_ID} , {ERR_EXCEP}", + "EFFECTER_ID", effecterId, "ERR_EXCEP", e.what()); return PLDM_ERROR; } diff --git a/libpldmresponder/platform_state_effecter.hpp b/libpldmresponder/platform_state_effecter.hpp index f4e1224f9..b45378dcd 100644 --- a/libpldmresponder/platform_state_effecter.hpp +++ b/libpldmresponder/platform_state_effecter.hpp @@ -1,18 +1,20 @@ #pragma once -#include "config.h" - -#include "libpldm/platform.h" -#include "libpldm/states.h" - #include "common/utils.hpp" #include "libpldmresponder/pdr.hpp" #include "pdr_utils.hpp" #include "pldmd/handler.hpp" +#include +#include + +#include + #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -53,7 +55,7 @@ int setStateEffecterStatesHandler( PLDM_STATE_EFFECTER_PDR); if (stateEffecterPDRs.empty()) { - std::cerr << "Failed to get record by PDR type\n"; + error("Failed to get record by PDR type"); return PLDM_PLATFORM_INVALID_EFFECTER_ID; } @@ -73,9 +75,9 @@ int setStateEffecterStatesHandler( pdr->possible_states); if (compEffecterCnt > pdr->composite_effecter_count) { - std::cerr << "The requester sent wrong composite effecter" - << " count for the effecter, EFFECTER_ID=" << effecterId - << "COMP_EFF_CNT=" << compEffecterCnt << "\n"; + error( + "The requester sent wrong composite effecter count for the effecter, EFFECTER_ID={EFFECTER_ID} COMP_EFF_CNT={COMP_EFF_CNT}", + "EFFECTER_ID", effecterId, "COMP_EFF_CNT", compEffecterCnt); return PLDM_ERROR_INVALID_DATA; } break; @@ -101,12 +103,11 @@ int setStateEffecterStatesHandler( if (states->possible_states_size < bitfieldIndex || !(states->states[bitfieldIndex].byte & (1 << bit))) { - std::cerr << "Invalid state set value, EFFECTER_ID=" - << effecterId - << " VALUE=" << stateField[currState].effecter_state - << " COMPOSITE_EFFECTER_ID=" << currState - << " DBUS_PATH=" << dbusMappings[currState].objectPath - << "\n"; + error( + "Invalid state set value, EFFECTER_ID={EFFECTER_ID} VALUE={VALUE} COMPOSITE_EFFECTER_ID={COMP_EFFECTER_ID} DBUS_PATH={DBUS_PATH}", + "EFFECTER_ID", effecterId, "VALUE", + stateField[currState].effecter_state, "COMP_EFFECTER_ID", + currState, "DBUS_PATH", dbusMappings[currState].objectPath); rc = PLDM_PLATFORM_SET_EFFECTER_UNSUPPORTED_SENSORSTATE; break; } @@ -124,11 +125,12 @@ int setStateEffecterStatesHandler( } catch (const std::exception& e) { - std::cerr - << "Error setting property, ERROR=" << e.what() - << " PROPERTY=" << dbusMapping.propertyName - << " INTERFACE=" << dbusMapping.interface << " PATH=" - << dbusMapping.objectPath << "\n"; + error( + "Error setting property, ERROR={ERR_EXCEP} PROPERTY={DBUS_PROP} INTERFACE={INTF} PATH={DBUS_OBJ_PATH}", + "ERR_EXCEP", e.what(), "DBUS_PROP", + dbusMapping.propertyName, "DBUS_INTF", + dbusMapping.interface, "DBUS_OBJ_PATH", + dbusMapping.objectPath); return PLDM_ERROR; } } @@ -143,7 +145,8 @@ int setStateEffecterStatesHandler( } catch (const std::out_of_range& e) { - std::cerr << "Unknown effecter ID : " << effecterId << e.what() << '\n'; + error("Unknown effecter ID : {EFFECTER_ID}, {ERR_EXCEP}", "EFFECTER_ID", + effecterId, "ERR_EXCEP", e.what()); return PLDM_ERROR; } diff --git a/libpldmresponder/platform_state_sensor.hpp b/libpldmresponder/platform_state_sensor.hpp index 6ddb7ffd5..b32ca7cbf 100644 --- a/libpldmresponder/platform_state_sensor.hpp +++ b/libpldmresponder/platform_state_sensor.hpp @@ -1,18 +1,19 @@ #pragma once - -#include "config.h" - -#include "libpldm/platform.h" -#include "libpldm/states.h" - #include "common/utils.hpp" #include "libpldmresponder/pdr.hpp" #include "pdr_utils.hpp" #include "pldmd/handler.hpp" +#include +#include + +#include + #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -66,9 +67,9 @@ uint8_t getStateSensorEventState( } catch (const std::exception& e) { - std::cerr << "Get StateSensor EventState from dbus Error, interface : " - << dbusMapping.objectPath.c_str() - << " ,exception : " << e.what() << '\n'; + error( + "Get StateSensor EventState from dbus Error, interface : {INTF} ,exception : {ERR_EXCEP}", + "INTF", dbusMapping.objectPath.c_str(), "ERR_EXCEP", e.what()); } return PLDM_SENSOR_UNKNOWN; @@ -108,7 +109,7 @@ int getStateSensorReadingsHandler( getRepoByType(handler.getRepo(), stateSensorPDRs, PLDM_STATE_SENSOR_PDR); if (stateSensorPDRs.empty()) { - std::cerr << "Failed to get record by PDR type\n"; + error("Failed to get record by PDR type"); return PLDM_PLATFORM_INVALID_SENSOR_ID; } @@ -128,9 +129,9 @@ int getStateSensorReadingsHandler( compSensorCnt = pdr->composite_sensor_count; if (sensorRearmCnt > compSensorCnt) { - std::cerr << "The requester sent wrong sensorRearm" - << " count for the sensor, SENSOR_ID=" << sensorId - << "SENSOR_REARM_COUNT=" << sensorRearmCnt << "\n"; + error( + "The requester sent wrong sensorRearm count for the sensor, SENSOR_ID={SENSOR_ID} SENSOR_REARM_COUNT={SENSOR_REARM_CNT}", + "SENSOR_ID", sensorId, "SENSOR_REARM_CNT", sensorRearmCnt); return PLDM_PLATFORM_REARM_UNAVAILABLE_IN_PRESENT_STATE; } @@ -198,8 +199,9 @@ int getStateSensorReadingsHandler( } catch (const std::out_of_range& e) { - std::cerr << "the sensorId does not exist. sensor id: " << sensorId - << e.what() << '\n'; + error( + "the sensorId does not exist. sensor id: {SENSOR_ID}, {ERR_EXCEP}", + "SENSOR_ID", sensorId, "ERR_EXCEP", e.what()); rc = PLDM_ERROR; } diff --git a/libpldmresponder/test/libpldmresponder_platform_test.cpp b/libpldmresponder/test/libpldmresponder_platform_test.cpp index 030b64b25..d49f193ec 100644 --- a/libpldmresponder/test/libpldmresponder_platform_test.cpp +++ b/libpldmresponder/test/libpldmresponder_platform_test.cpp @@ -198,13 +198,10 @@ TEST(getPDR, testFindPDR) // current is not what we want pldm_pdr_hdr* hdr = reinterpret_cast(resp->record_data); - std::cerr << "PDR next record handle " << handle << "\n"; - std::cerr << "PDR type " << hdr->type << "\n"; if (hdr->type == PLDM_STATE_EFFECTER_PDR) { pldm_state_effecter_pdr* pdr = reinterpret_cast(resp->record_data); - std::cerr << "PDR entity type " << pdr->entity_type << "\n"; if (pdr->entity_type == 100) { found = true; diff --git a/libpldmresponder/test/meson.build b/libpldmresponder/test/meson.build index 9c7a78272..f4b57a173 100644 --- a/libpldmresponder/test/meson.build +++ b/libpldmresponder/test/meson.build @@ -37,6 +37,7 @@ foreach t : tests libpldm_dep, libpldmresponder_dep, libpldmutils, + phosphor_logging_dep, gtest, gmock, nlohmann_json, diff --git a/meson.build b/meson.build index 5b50fe1b4..c74b25106 100644 --- a/meson.build +++ b/meson.build @@ -36,6 +36,7 @@ conf_data.set_quoted('EVENTS_JSONS_DIR', join_paths(package_datadir, 'events')) conf_data.set('HEARTBEAT_TIMEOUT', get_option('heartbeat-timeout-seconds')) conf_data.set('TERMINUS_ID', get_option('terminus-id')) conf_data.set('TERMINUS_HANDLE',get_option('terminus-handle')) +conf_data.set('DBUS_TIMEOUT', get_option('dbus-timeout-value')) conf_data.set_quoted('PERSISTENT_FILE', '/var/lib/pldm/persist') conf_data.set_quoted('DBUS_JSON_FILE', '/usr/share/pldm/dbus-config.json') add_project_arguments('-DLIBPLDMRESPONDER', language : ['c','cpp']) @@ -60,16 +61,19 @@ conf_data.set('RESPONSE_TIME_OUT',get_option('response-time-out')) conf_data.set('FLIGHT_RECORDER_MAX_ENTRIES',get_option('flightrecorder-max-entries')) conf_data.set_quoted('HOST_EID_PATH', join_paths(package_datadir, 'host_eid')) conf_data.set('MAXIMUM_TRANSFER_SIZE', get_option('maximum-transfer-size')) -configure_file(output: 'config.h', +config = configure_file(output: 'config.h', configuration: conf_data ) +add_project_arguments('-include', '@0@'.format(config), language: 'cpp') + cpp = meson.get_compiler('cpp') phosphor_dbus_interfaces = dependency('phosphor-dbus-interfaces') sdbusplus = dependency('sdbusplus') sdeventplus = dependency('sdeventplus') stdplus = dependency('stdplus') +phosphor_logging_dep = dependency('phosphor-logging') if cpp.has_header('nlohmann/json.hpp') nlohmann_json = declare_dependency() @@ -142,6 +146,7 @@ libpldmutils = library( dependencies: [ libpldm_dep, phosphor_dbus_interfaces, + phosphor_logging_dep, nlohmann_json, sdbusplus, ], @@ -176,6 +181,7 @@ deps = [ libpldmutils, nlohmann_json, phosphor_dbus_interfaces, + phosphor_logging_dep, sdbusplus, sdeventplus, stdplus, diff --git a/meson_options.txt b/meson_options.txt index 5e7fb7263..3296ff366 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -15,6 +15,13 @@ option('number-of-request-retries', type: 'integer', min: 2, max: 30, descriptio option('instance-id-expiration-interval', type: 'integer', min: 5, max: 6, description: 'Instance ID expiration interval in seconds', value: 5) # Default response-time-out set to 2 seconds to facilitate a minimum retry of the request of 2. option('response-time-out', type: 'integer', min: 300, max: 4800, description: 'The amount of time a requester has to wait for a response message in milliseconds', value: 2000) +# As per PLDM spec DSP0240 version 1.1.0, in Timing Specification for PLDM messages (Table 6), +# the instance ID for a given response will expire and become reusable if a response has not been +# received within a maximum of 6 seconds after a request is sent. By setting the dbus timeout +# value to 5 seconds we ensure that PLDM does not wait for a response from a dbus call even after +# the instance ID has expired. If the option is set to 5 seconds, any dbus call originated from +# PLDM daemon will timeout after 5 seconds. +option('dbus-timeout-value', type: 'integer', min: 3, max: 10, description: 'The amount of time pldm waits to get a response for a dbus message before timing out', value: 5) option('heartbeat-timeout-seconds', type: 'integer', description: ' The amount of time host waits for BMC to respond to pings from host, as part of host-bmc surveillance', value: 120) diff --git a/oem/ibm/configurations/bios/enum_attrs.json b/oem/ibm/configurations/bios/enum_attrs.json index 54459f3b9..e7e7632c4 100644 --- a/oem/ibm/configurations/bios/enum_attrs.json +++ b/oem/ibm/configurations/bios/enum_attrs.json @@ -196,14 +196,14 @@ { "attribute_name": "pvm_os_boot_type", "possible_values": ["A_Mode", "B_Mode", "C_Mode", "D_Mode"], - "default_values": ["D_Mode"], + "default_values": ["A_Mode"], "helpText": "Select the IBMi partition boot mode for next system boot. A_Mode: Boot from disk using copy A, B_Mode: Boot from disk using copy B, C_Mode: Reserved for IBM lab use only, D_Mode: Boot from media/drives.", "displayName": "IBMi Partition Boot Mode" }, { "attribute_name": "pvm_os_boot_type_current", "possible_values": ["A_Mode", "B_Mode", "C_Mode", "D_Mode"], - "default_values": ["D_Mode"], + "default_values": ["A_Mode"], "helpText": "Specifies the current IBMi partition boot mode for next system boot. Do not set this attribute directly; set pvm_os_boot_type instead.", "displayName": "IBMi Partition Boot Mode (current)", "readOnly": true diff --git a/oem/ibm/configurations/bios/string_attrs.json b/oem/ibm/configurations/bios/string_attrs.json index 25a691561..ea038741d 100644 --- a/oem/ibm/configurations/bios/string_attrs.json +++ b/oem/ibm/configurations/bios/string_attrs.json @@ -70,7 +70,7 @@ "attribute_name": "vmi_if0_ipv6_gateway", "string_type": "ASCII", "minimum_string_length": 2, - "maximum_string_length": 39, + "maximum_string_length": 45, "default_string_length": 2, "default_string": "::", "helpText": "vmi_if0_ipv6_gateway", @@ -80,7 +80,7 @@ "attribute_name": "vmi_if1_ipv6_gateway", "string_type": "ASCII", "minimum_string_length": 2, - "maximum_string_length": 39, + "maximum_string_length": 45, "default_string_length": 2, "default_string": "::", "helpText": "vmi_if1_ipv6_gateway", @@ -90,7 +90,7 @@ "attribute_name": "vmi_if0_ipv6_ipaddr", "string_type": "ASCII", "minimum_string_length": 2, - "maximum_string_length": 39, + "maximum_string_length": 45, "default_string_length": 2, "default_string": "::", "helpText": "vmi_if0_ipv6_ipaddr", @@ -100,7 +100,7 @@ "attribute_name": "vmi_if1_ipv6_ipaddr", "string_type": "ASCII", "minimum_string_length": 2, - "maximum_string_length": 39, + "maximum_string_length": 45, "default_string_length": 2, "default_string": "::", "helpText": "vmi_if1_ipv6_ipaddr", diff --git a/oem/ibm/configurations/fru/Motherboard_UTIL.json b/oem/ibm/configurations/fru/Motherboard_UTIL.json new file mode 100644 index 000000000..8d4c72e1f --- /dev/null +++ b/oem/ibm/configurations/fru/Motherboard_UTIL.json @@ -0,0 +1,33 @@ +{ + "record_details": { + "fru_record_type": 254, + "fru_encoding_type": 1, + "dbus_interface_name": "xyz.openbmc_project.Inventory.Item.Board.Motherboard" + }, + "fru_fields": [ + { + "fru_field_type": 2, + "dbus": { + "interface": "com.ibm.ipzvpd.UTIL", + "property_name": "RT", + "property_type": "bytearray" + } + }, + { + "fru_field_type": 18, + "dbus": { + "interface": "com.ibm.ipzvpd.UTIL", + "property_name": "F5", + "property_type": "bytearray" + } + }, + { + "fru_field_type": 19, + "dbus": { + "interface": "com.ibm.ipzvpd.UTIL", + "property_name": "F6", + "property_type": "bytearray" + } + } + ] +} diff --git a/oem/ibm/configurations/pdr/ibm,rainier-1s4u/11.json b/oem/ibm/configurations/pdr/ibm,rainier-1s4u/11.json index 6df10a92e..44dfbdb99 100644 --- a/oem/ibm/configurations/pdr/ibm,rainier-1s4u/11.json +++ b/oem/ibm/configurations/pdr/ibm,rainier-1s4u/11.json @@ -614,6 +614,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme0_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme1_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme2", "effecters": [ @@ -690,6 +728,82 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme6_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme7_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme8_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme9_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme2", "effecters": [ @@ -766,6 +880,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme14_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "effecters": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme15_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/pcieslot6", "effecters": [ @@ -1643,6 +1795,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme2", "effecters": [ @@ -1719,6 +1909,82 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme2", "effecters": [ @@ -1795,6 +2061,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "effecters": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "interface": "xyz.openbmc_project.State.Decorator.OperationalStatus", + "property_name": "Functional", + "property_type": "bool", + "property_values": [true, false] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/pcieslot6", "effecters": [ @@ -2295,6 +2599,52 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme2", "effecters": [ @@ -2387,6 +2737,98 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme2", "effecters": [ @@ -2478,6 +2920,52 @@ } } ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "effecters": [ + { + "set": { + "id": 257, + "size": 1, + "states": [0, 1, 4] + }, + "dbus": { + "path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "interface": "xyz.openbmc_project.State.Decorator.PowerState", + "property_name": "PowerState", + "property_type": "string", + "property_values": [ + "xyz.openbmc_project.State.Decorator.PowerState.State.Unknown", + "xyz.openbmc_project.State.Decorator.PowerState.State.On", + "xyz.openbmc_project.State.Decorator.PowerState.State.Off" + ] + } + } + ] } ] } diff --git a/oem/ibm/configurations/pdr/ibm,rainier-1s4u/4.json b/oem/ibm/configurations/pdr/ibm,rainier-1s4u/4.json index be5b3b28e..9c1d09c85 100644 --- a/oem/ibm/configurations/pdr/ibm,rainier-1s4u/4.json +++ b/oem/ibm/configurations/pdr/ibm,rainier-1s4u/4.json @@ -639,6 +639,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme0_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme1_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme2", "sensors": [ @@ -715,6 +753,82 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme6_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme7_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme8_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme9_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme2", "sensors": [ @@ -791,6 +905,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme14_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "sensors": [ + { + "set": { + "id": 17, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme15_identify", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/pcieslot6", "sensors": [ @@ -1676,6 +1828,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme0", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme0_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme1", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme1_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme2", "sensors": [ @@ -1752,6 +1942,82 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme6", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme6_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane0/nvme7", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme7_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme0", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme8_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme1", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme9_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme2", "sensors": [ @@ -1828,6 +2094,44 @@ } ] }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme6", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme14_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, + { + "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/disk_backplane1/nvme7", + "sensors": [ + { + "set": { + "id": 10, + "size": 1, + "states": [1, 2] + }, + "dbus": { + "path": "/xyz/openbmc_project/led/groups/nvme15_fault", + "interface": "xyz.openbmc_project.Led.Group", + "property_name": "Asserted", + "property_type": "bool", + "property_values": [false, true] + } + } + ] + }, { "entity_path": "/xyz/openbmc_project/inventory/system/chassis/motherboard/pcieslot6", "sensors": [ diff --git a/oem/ibm/host-bmc/host_lamp_test.cpp b/oem/ibm/host-bmc/host_lamp_test.cpp index 3ce567ef8..ab63e8157 100644 --- a/oem/ibm/host-bmc/host_lamp_test.cpp +++ b/oem/ibm/host-bmc/host_lamp_test.cpp @@ -9,13 +9,16 @@ #include "common/types.hpp" #include "common/utils.hpp" +#include + #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace led { - bool HostLampTest::asserted() const { return sdbusplus::xyz::openbmc_project::Led::server::Group::asserted(); @@ -91,9 +94,9 @@ uint16_t HostLampTest::getEffecterID() if (stateEffecterPDRs.empty()) { - std::cerr - << "Lamp Test: The state set PDR can not be found, entityType = " - << entityType << std::endl; + error( + "Lamp Test: The state set PDR can not be found, entityType = {ENTITY_TYP}", + "ENTITY_TYP", entityType); return effecterID; } @@ -123,8 +126,8 @@ void HostLampTest::setHostStateEffecter(uint16_t effecterID, uint8_t& rc) if (rc != PLDM_SUCCESS) { requester.markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_set_state_effecter_states_req, rc = " - << rc << std::endl; + error("Failed to encode_set_state_effecter_states_req, rc = {RC}", "RC", + static_cast(rc)); return; } @@ -132,8 +135,8 @@ void HostLampTest::setHostStateEffecter(uint16_t effecterID, uint8_t& rc) [&rc](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for the Set State " - "Effecter States\n"; + error( + "Failed to receive response for the Set State Effecter States"); return; } @@ -144,10 +147,9 @@ void HostLampTest::setHostStateEffecter(uint16_t effecterID, uint8_t& rc) if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Failed to decode_set_state_effecter_states_resp: " - << "rc=" << rc - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_set_state_effecter_states_resp: rc={RC}, cc={CC}", + "RC", rc, "CC", static_cast(completionCode)); } }; @@ -157,8 +159,7 @@ void HostLampTest::setHostStateEffecter(uint16_t effecterID, uint8_t& rc) std::move(setStateEffecterStatesResponseHandler)); if (rc != PLDM_SUCCESS) { - std::cerr - << "Failed to send the the Set State Effecter States request\n"; + error("Failed to send the the Set State Effecter States request"); } return; diff --git a/oem/ibm/libpldmresponder/collect_slot_vpd.cpp b/oem/ibm/libpldmresponder/collect_slot_vpd.cpp index 9fe7f7439..75efba222 100644 --- a/oem/ibm/libpldmresponder/collect_slot_vpd.cpp +++ b/oem/ibm/libpldmresponder/collect_slot_vpd.cpp @@ -3,20 +3,26 @@ #include "oem_ibm_handler.hpp" #include "xyz/openbmc_project/Common/error.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace responder { using namespace oem_ibm_platform; void SlotHandler::timeOutHandler() { - std::cerr - << "Timer expired waiting for Event from Inventory on following pldm_entity: [ " - << current_on_going_slot_entity.entity_type << "," - << current_on_going_slot_entity.entity_instance_num << "," - << current_on_going_slot_entity.entity_container_id << "]" << std::endl; - + error( + "Timer expired waiting for Event from Inventory on following pldm_entity: [ {ENTITY_TYP}, {ENTITY_NUM}, {ENTITY_ID} ]", + "ENTITY_TYP", + static_cast(current_on_going_slot_entity.entity_type), + "ENTITY_NUM", + static_cast(current_on_going_slot_entity.entity_instance_num), + "ENTITY_ID", + static_cast( + current_on_going_slot_entity.entity_container_id)); // Disable the timer timer.setEnabled(false); @@ -37,7 +43,8 @@ void SlotHandler::enableSlot(uint16_t effecterId, uint8_t stateFileValue) { - std::cerr << "CM: slot enable effecter id: " << effecterId << std::endl; + error("CM: slot enable effecter id: {EFFECTER_ID}", "EFFECTER_ID", + effecterId); const pldm_entity entity = getEntityIDfromEffecterID(effecterId); for (const auto& [key, value] : fruAssociationMap) @@ -60,8 +67,8 @@ void SlotHandler::processSlotOperations(const std::string& slotObjectPath, const pldm_entity& entity, uint8_t stateFiledValue) { - std::cerr << "CM: processing the slot operations, SlotObject: " - << slotObjectPath << std::endl; + error("CM: processing the slot operations, SlotObject: {SLOT_OBJ}", + "SLOT_OBJ", slotObjectPath); std::string adapterObjPath; try @@ -74,8 +81,9 @@ void SlotHandler::processSlotOperations(const std::string& slotObjectPath, return; } - std::cerr << "CM: Found an adapter under the slot, adapter object:" - << adapterObjPath << std::endl; + error( + "CM: Found an adapter under the slot, adapter object:{ADAPTER_OBJ_PATH}", + "ADAPTER_OBJ_PATH", adapterObjPath); // create a presence match for the adpter present property createPresenceMatch(adapterObjPath, entity, stateFiledValue); @@ -102,7 +110,9 @@ void SlotHandler::callVPDManager(const std::string& adapterObjPath, VPDInterface, "CollectFRUVPD"); method.append( static_cast(adapterObjPath)); - bus.call_noreply(method); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } else if (stateFiledValue == uint8_t(REMOVE) || stateFiledValue == uint8_t(REPLACE)) @@ -111,14 +121,17 @@ void SlotHandler::callVPDManager(const std::string& adapterObjPath, VPDInterface, "deleteFRUVPD"); method.append( static_cast(adapterObjPath)); - bus.call_noreply(method); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call to VPD Manager , Operation =" - << (unsigned)stateFiledValue << ", ERROR=" << e.what() - << "\n"; + error( + "failed to make a d-bus call to VPD Manager , Operation = {STATE_FILED_VAL}, ERROR={ERR_EXCEP}", + "STATE_FILED_VAL", (unsigned)stateFiledValue, "ERR_EXCEP", + e.what()); } } @@ -201,9 +214,9 @@ void SlotHandler::processPropertyChangeFromVPD( sensorOpState = uint8_t(SLOT_STATE_DISABLED); } } - std::cerr - << "CM: processing the property change from VPD Present value and sensor opState:" - << presentValue << "and" << (unsigned)sensorOpState << std::endl; + error( + "CM: processing the property change from VPD Present value and sensor opState: {CURR_VAL} and {SENSOR_OP_STATE}", + "CURR_VAL", presentValue, "SENSOR_OP_STATE", (unsigned)sensorOpState); // set the sensor state based on the stateFieldValue this->sendStateSensorEvent(sensorId, PLDM_STATE_SENSOR_STATE, 0, sensorOpState, uint8_t(SLOT_STATE_UNKOWN)); @@ -261,9 +274,9 @@ uint8_t SlotHandler::fetchSlotSensorState(const std::string& slotObjectPath) } catch (const std::bad_optional_access& e) { - std::cerr - << "Failed to get the adapterObjectPath from slotObjectPath : " - << slotObjectPath << e.what() << '\n'; + error( + "Failed to get the adapterObjectPath from slotObjectPath : {SLOT_OBJ_PATH}, {ERR_EXCEP}", + "SLOT_OBJ_PATH", slotObjectPath, "ERR_EXCEP", e.what()); return uint8_t(SLOT_STATE_UNKOWN); } @@ -308,14 +321,17 @@ bool SlotHandler::fetchSensorStateFromDbus(const std::string& adapterObjectPath) adapterObjectPath.c_str(), FreedesktopInterface, GetMethod); method.append(ItemInterface, PresentProperty); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(presentProperty); return std::get(presentProperty); } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call to Inventory manager, ERROR=" - << e.what() << "\n"; + error( + "failed to make a d-bus call to Inventory manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } return false; diff --git a/oem/ibm/libpldmresponder/file_io.cpp b/oem/ibm/libpldmresponder/file_io.cpp index d04ac33f8..41e74c2ca 100644 --- a/oem/ibm/libpldmresponder/file_io.cpp +++ b/oem/ibm/libpldmresponder/file_io.cpp @@ -1,5 +1,3 @@ -#include "config.h" - #include "file_io.hpp" #include "libpldm/base.h" @@ -15,12 +13,16 @@ #include #include +#include + #include #include #include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace pldm::responder::utils; @@ -32,7 +34,6 @@ namespace fs = std::filesystem; namespace dma { - /** @struct AspeedXdmaOp * * Structure representing XDMA operation @@ -56,9 +57,9 @@ int DMA::transferHostDataToSocket(int fd, uint32_t length, uint64_t address) if (xdmaFd < 0) { rc = -errno; - std::cerr - << "transferHostDataToSocket : Failed to open the XDMA device, RC=" - << rc << "\n"; + error( + "transferHostDataToSocket : Failed to open the XDMA device, RC={RC}", + "RC", rc); return rc; } @@ -66,9 +67,9 @@ int DMA::transferHostDataToSocket(int fd, uint32_t length, uint64_t address) if (MAP_FAILED == vgaMemDump) { rc = -errno; - std::cerr - << "transferHostDataToSocket : Failed to mmap the XDMA device, RC=" - << rc << "\n"; + error( + "transferHostDataToSocket : Failed to mmap the XDMA device, RC={RC}", + "RC", rc); return rc; } auto mmapCleanup = [pageAlLength, &rc, xdmaFd, this](void* vgaMem) { @@ -84,9 +85,8 @@ int DMA::transferHostDataToSocket(int fd, uint32_t length, uint64_t address) } else { - std::cerr - << "transferHostDataToSocket : Received interrupt during dump DMA transfer. Skipping Unmap" - << std::endl; + error( + "transferHostDataToSocket : Received interrupt during dump DMA transfer. Skipping Unmap"); } }; std::unique_ptr vgaMemPtr(vgaMemDump, @@ -157,9 +157,7 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, } else { - std::cerr - << "Received interrupt during DMA transfer. Skipping Unmap" - << std::endl; + error("Received interrupt during DMA transfer. Skipping Unmap"); } }; @@ -170,9 +168,9 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, if (rc == -1) { rc = -errno; - std::cerr << "transferDataHost upstream : lseek failed, ERROR=" - << errno << ", UPSTREAM=" << upstream - << ", OFFSET=" << offset << "\n"; + error( + "transferDataHost upstream : lseek failed, ERROR={ERR}, UPSTREAM={UP_STRM}, OFFSET={KEY2}", + "ERR", errno, "UP_STRM", upstream, "OFFSET", offset); return rc; } @@ -185,17 +183,17 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, if (rc == -1) { rc = -errno; - std::cerr << "transferDataHost upstream : file read failed, ERROR=" - << errno << ", UPSTREAM=" << upstream - << ", LENGTH=" << length << ", OFFSET=" << offset << "\n"; + error( + "transferDataHost upstream : file read failed, ERROR={ERR}, UPSTREAM={UP_STRM}, LENGTH={LEN}, OFFSET={OFFSET}", + "ERR", errno, "UP_STRM", upstream, "LEN", length, "OFFSET", + offset); return rc; } if (rc != static_cast(length)) { - std::cerr - << " transferDataHost upstream : mismatch between number of characters to read and " - << "the length read, LENGTH=" << length << " COUNT=" << rc - << "\n"; + error( + "transferDataHost upstream : mismatch between number of characters to read and the length read, LENGTH={LEN} COUNT={RC}", + "LEN", length, "RC", rc); return -1; } responseByte = rc; @@ -212,10 +210,9 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, if (rc < 0) { rc = -errno; - std::cerr - << "transferDataHost : Failed to execute the DMA operation, RC=" - << rc << " UPSTREAM=" << upstream << " ADDRESS=" << address - << " LENGTH=" << length << "\n"; + error( + "transferDataHost : Failed to execute the DMA operation, RC={RC} UPSTREAM={UP_STRM} ADDRESS={ADDR} LENGTH={LEN}", + "RC", rc, "UP_STRM", upstream, "ADDR", address, "LEN", length); return rc; } @@ -225,10 +222,9 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, if (rc == -1) { rc = -errno; - std::cerr << "transferDataHost downstream : lseek failed, ERROR=" - << errno << ", UPSTREAM=" << upstream - << ", OFFSET=" << offset << " fd:" << fd << " rc:" << rc - << "\n "; + error( + "transferDataHost downstream : lseek failed, ERROR={ERR}, UPSTREAM={UP_STRM}, OFFSET={OFFSET}", + "ERR", errno, "UP_STRM", upstream, "OFFSET", offset); return rc; } @@ -236,10 +232,10 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, if (rc == -1) { rc = -errno; - std::cerr - << "transferDataHost downstream : file write failed, ERROR=" - << errno << ", UPSTREAM=" << upstream << ", LENGTH=" << length - << ", OFFSET=" << offset << "\n"; + error( + "transferDataHost downstream : file write failed, ERROR={ERR}, UPSTREAM={UP_STRM}, LENGTH={LEN}, OFFSET={OFFSET}", + "ERR", errno, "UP_STRM", upstream, "LEN", length, "OFFSET", + offset); return rc; } responseByte = rc; @@ -260,7 +256,6 @@ int32_t DMA::transferDataHost(int fd, uint32_t offset, uint32_t length, namespace oem_ibm { - Response Handler::readFileIntoMemory(const pldm_msg* request, size_t payloadLength) { @@ -292,8 +287,9 @@ Response Handler::readFileIntoMemory(const pldm_msg* request, } catch (const std::exception& e) { - std::cerr << "File handle does not exist in the file table, HANDLE=" - << fileHandle << "\n"; + error( + "File handle does not exist in the file table, HANDLE={FILE_HNDL}", + "FILE_HNDL", fileHandle); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_READ_FILE_INTO_MEMORY, PLDM_INVALID_FILE_HANDLE, 0, responsePtr); @@ -302,7 +298,8 @@ Response Handler::readFileIntoMemory(const pldm_msg* request, if (!fs::exists(value.fsPath)) { - std::cerr << "File does not exist, HANDLE=" << fileHandle << "\n"; + error("File does not exist, HANDLE={FILE_HNDL}", "FILE_HNDL", + fileHandle); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_READ_FILE_INTO_MEMORY, PLDM_INVALID_FILE_HANDLE, 0, responsePtr); @@ -312,8 +309,9 @@ Response Handler::readFileIntoMemory(const pldm_msg* request, auto fileSize = fs::file_size(value.fsPath); if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error( + "fileIO:Handler::readFileIntoMemory:Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE} FILE_HANDLE={FILE_HANDLE}", + "OFFSET", offset, "FILE_SIZE", fileSize, "FILE_HANDLE", fileHandle); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_READ_FILE_INTO_MEMORY, PLDM_DATA_OUT_OF_RANGE, 0, responsePtr); @@ -327,8 +325,8 @@ Response Handler::readFileIntoMemory(const pldm_msg* request, if ((length == 0) && (length % dma::minSize)) { - std::cerr << "Read length is not a multiple of DMA minSize, LENGTH=" - << length << "\n"; + error("Read length is not a multiple of DMA minSize, LENGTH={LEN}", + "LEN", length); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_READ_FILE_INTO_MEMORY, PLDM_ERROR_INVALID_LENGTH, 0, responsePtr); @@ -380,8 +378,8 @@ Response Handler::writeFileFromMemory(const pldm_msg* request, &length, &address); if ((length == 0) || (length % dma::minSize)) { - std::cerr << "Write length is not a multiple of DMA minSize, LENGTH=" - << length << "\n"; + error("Write length is not a multiple of DMA minSize, LENGTH={LEN}", + "LEN", length); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_WRITE_FILE_FROM_MEMORY, PLDM_ERROR_INVALID_LENGTH, 0, responsePtr); @@ -398,8 +396,9 @@ Response Handler::writeFileFromMemory(const pldm_msg* request, } catch (const std::exception& e) { - std::cerr << "File handle does not exist in the file table, HANDLE=" - << fileHandle << "\n"; + error( + "File handle does not exist in the file table, HANDLE={FILE_HNDL}", + "FILE_HNDL", fileHandle); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_WRITE_FILE_FROM_MEMORY, PLDM_INVALID_FILE_HANDLE, 0, responsePtr); @@ -408,7 +407,8 @@ Response Handler::writeFileFromMemory(const pldm_msg* request, if (!fs::exists(value.fsPath)) { - std::cerr << "File does not exist, HANDLE=" << fileHandle << "\n"; + error("File does not exist, HANDLE={FILE_HNDL}", "FILE_HNDL", + fileHandle); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_WRITE_FILE_FROM_MEMORY, PLDM_INVALID_FILE_HANDLE, 0, responsePtr); @@ -418,8 +418,9 @@ Response Handler::writeFileFromMemory(const pldm_msg* request, auto fileSize = fs::file_size(value.fsPath); if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error( + "fileIO:Handler::readFileFromMemory:Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE} FILE_HANDLE={FILE_HANDLE}", + "OFFSET", offset, "FILE_SIZE", fileSize, "FILE_HANDLE", fileHandle); encode_rw_file_memory_resp(request->hdr.instance_id, PLDM_WRITE_FILE_FROM_MEMORY, PLDM_DATA_OUT_OF_RANGE, 0, responsePtr); @@ -549,8 +550,10 @@ Response Handler::readFile(const pldm_msg* request, size_t payloadLength) } catch (const std::exception& e) { - std::cerr << "File handle does not exist in the file table, HANDLE=" - << fileHandle << "\n"; + error( + "File handle does not exist in the file table, HANDLE={FILE_HNDL}", + "FILE_HNDL", fileHandle); + encode_read_file_resp(request->hdr.instance_id, PLDM_INVALID_FILE_HANDLE, length, responsePtr); return response; @@ -558,7 +561,8 @@ Response Handler::readFile(const pldm_msg* request, size_t payloadLength) if (!fs::exists(value.fsPath)) { - std::cerr << "File does not exist, HANDLE=" << fileHandle << "\n"; + error("File does not exist, HANDLE={FILE_HNDL}", "FILE_HNDL", + fileHandle); encode_read_file_resp(request->hdr.instance_id, PLDM_INVALID_FILE_HANDLE, length, responsePtr); return response; @@ -567,8 +571,8 @@ Response Handler::readFile(const pldm_msg* request, size_t payloadLength) auto fileSize = fs::file_size(value.fsPath); if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error("Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE}", + "OFFSET", offset, "FILE_SIZE", fileSize); encode_read_file_resp(request->hdr.instance_id, PLDM_DATA_OUT_OF_RANGE, length, responsePtr); return response; @@ -630,8 +634,9 @@ Response Handler::writeFile(const pldm_msg* request, size_t payloadLength) } catch (const std::exception& e) { - std::cerr << "File handle does not exist in the file table, HANDLE=" - << fileHandle << "\n"; + error( + "File handle does not exist in the file table, HANDLE={FILE_HNDL}", + "FILE_HNDL", fileHandle); encode_write_file_resp(request->hdr.instance_id, PLDM_INVALID_FILE_HANDLE, 0, responsePtr); return response; @@ -639,7 +644,8 @@ Response Handler::writeFile(const pldm_msg* request, size_t payloadLength) if (!fs::exists(value.fsPath)) { - std::cerr << "File does not exist, HANDLE=" << fileHandle << "\n"; + error("File does not exist, HANDLE={FILE_HNDL}", "FILE_HNDL", + fileHandle); encode_write_file_resp(request->hdr.instance_id, PLDM_INVALID_FILE_HANDLE, 0, responsePtr); return response; @@ -648,8 +654,8 @@ Response Handler::writeFile(const pldm_msg* request, size_t payloadLength) auto fileSize = fs::file_size(value.fsPath); if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error("Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE}", + "OFFSET", offset, "FILE_SIZE", fileSize); encode_write_file_resp(request->hdr.instance_id, PLDM_DATA_OUT_OF_RANGE, 0, responsePtr); return response; @@ -702,8 +708,8 @@ Response rwFileByTypeIntoMemory(uint8_t cmd, const pldm_msg* request, } if ((length == 0) || (length % dma::minSize)) { - std::cerr << "Length is not a multiple of DMA minSize, LENGTH=" - << length << "\n"; + error("Length is not a multiple of DMA minSize, LENGTH={LEN}", "LEN", + length); encode_rw_file_by_type_memory_resp(request->hdr.instance_id, cmd, PLDM_ERROR_INVALID_LENGTH, 0, responsePtr); @@ -719,7 +725,7 @@ Response rwFileByTypeIntoMemory(uint8_t cmd, const pldm_msg* request, } catch (const InternalFailure& e) { - std::cerr << "unknown file type, TYPE=" << fileType << "\n"; + error("unknown file type, TYPE={LEN}", "LEN", fileType); encode_rw_file_by_type_memory_resp(request->hdr.instance_id, cmd, PLDM_INVALID_FILE_TYPE, 0, responsePtr); @@ -793,7 +799,7 @@ Response Handler::writeFileByType(const pldm_msg* request, size_t payloadLength) } catch (const InternalFailure& e) { - std::cerr << "unknown file type, TYPE=" << fileType << "\n"; + error("unknown file type, TYPE={FILE_TYP}", "FILE_TYP", fileType); encode_rw_file_by_type_resp(request->hdr.instance_id, PLDM_WRITE_FILE_BY_TYPE, PLDM_INVALID_FILE_TYPE, 0, responsePtr); @@ -842,7 +848,7 @@ Response Handler::readFileByType(const pldm_msg* request, size_t payloadLength) } catch (const InternalFailure& e) { - std::cerr << "unknown file type, TYPE=" << fileType << "\n"; + error("unknown file type, TYPE={FILE_TYP}", "FILE_TYP", fileType); encode_rw_file_by_type_resp(request->hdr.instance_id, PLDM_READ_FILE_BY_TYPE, PLDM_INVALID_FILE_TYPE, 0, responsePtr); @@ -962,7 +968,7 @@ Response Handler::newFileAvailable(const pldm_msg* request, } catch (const InternalFailure& e) { - std::cerr << "unknown file type, TYPE=" << fileType << "\n"; + error("unknown file type, TYPE={FILE_TYP}", "FILE_TYP", fileType); return CmdHandler::ccOnlyResponse(request, PLDM_INVALID_FILE_TYPE); } @@ -1006,7 +1012,7 @@ Response Handler::fileAckWithMetaData(const pldm_msg* request, } catch (const InternalFailure& e) { - std::cerr << "unknown file type, TYPE=" << fileType << "\n"; + error("unknown file type, TYPE={FILE_TYP}", "FILE_TYP", fileType); return CmdHandler::ccOnlyResponse(request, PLDM_INVALID_FILE_TYPE); } @@ -1052,7 +1058,7 @@ Response Handler::newFileAvailableWithMetaData(const pldm_msg* request, } catch (const InternalFailure& e) { - std::cerr << "unknown file type, TYPE=" << fileType << "\n"; + error("unknown file type, TYPE={FILE_TYP}", "FILE_TYP", fileType); return CmdHandler::ccOnlyResponse(request, PLDM_INVALID_FILE_TYPE); } diff --git a/oem/ibm/libpldmresponder/file_io.hpp b/oem/ibm/libpldmresponder/file_io.hpp index 465f6f296..535c7f5f5 100644 --- a/oem/ibm/libpldmresponder/file_io.hpp +++ b/oem/ibm/libpldmresponder/file_io.hpp @@ -1,11 +1,5 @@ #pragma once -#include "config.h" - -#include "libpldm/base.h" -#include "libpldm/file_io.h" -#include "libpldm/host.h" - #include "common/utils.hpp" #include "file_io_by_type.hpp" #include "oem/ibm/requester/dbus_to_file_handler.hpp" @@ -15,6 +9,9 @@ #include "requester/handler.hpp" #include +#include +#include +#include #include #include #include @@ -22,11 +19,15 @@ #include #include +#include #include #include #include #include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -338,9 +339,22 @@ Response transferAll(std::shared_ptr intf, int32_t file, uint8_t command = responseHdr.command; if (nullptr == intf) { - Response response(sizeof(pldm_msg_hdr) + command, 0); - auto responsePtr = reinterpret_cast(response.data()); - encode_rw_file_memory_resp(instance_id, command, PLDM_ERROR, 0, + flags = O_RDONLY; + } + else if (fs::exists(path)) + { + flags = O_RDWR; + } + else + { + flags = O_WRONLY; + } + int file = open(path.string().c_str(), flags); + if (file == -1) + { + error("File does not exist, path = {FILE_PATH}", "FILE_PATH", + path.string()); + encode_rw_file_memory_resp(instanceId, command, PLDM_ERROR, 0, responsePtr); if (responseHdr.respInterface != nullptr) { diff --git a/oem/ibm/libpldmresponder/file_io_by_type.cpp b/oem/ibm/libpldmresponder/file_io_by_type.cpp index 5b518f58e..31682e179 100644 --- a/oem/ibm/libpldmresponder/file_io_by_type.cpp +++ b/oem/ibm/libpldmresponder/file_io_by_type.cpp @@ -1,4 +1,4 @@ -#include "config.h" +#include "file_io_by_type.hpp" #include "libpldm/base.h" @@ -18,6 +18,9 @@ #include #include +#include +#include + #include #include #include @@ -25,6 +28,9 @@ #include #include #include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -80,7 +86,7 @@ void FileHandler::deleteAIOobjects( } } -int FileHandler::transferFileData(int32_t fd, bool upstream, uint32_t offset, +void FileHandler::transferFileData(int32_t fd, bool upstream, uint32_t offset, uint32_t& length, uint64_t address, ResponseHdr& responseHdr, sdeventplus::Event& event) @@ -94,7 +100,7 @@ int FileHandler::transferFileData(int32_t fd, bool upstream, uint32_t offset, dmaResponseToHost(responseHdr, PLDM_ERROR, 0); deleteAIOobjects(nullptr, responseHdr); close(fd); - return {}; + return; } xdmaInterface->setDMASourceFd(fd); uint32_t origLength = length; @@ -172,7 +178,7 @@ int FileHandler::transferFileData(int32_t fd, bool upstream, uint32_t offset, << "transferFileData : Failed to start the event timer.\n"; dmaResponseToHost(responseHdr, PLDM_ERROR, 0); deleteAIOobjects(xdmaInterface, responseHdr); - return {}; + return; } xdmaInterface->insertIOInstance(std::move(std::make_unique( @@ -185,10 +191,9 @@ int FileHandler::transferFileData(int32_t fd, bool upstream, uint32_t offset, dmaResponseToHost(responseHdr, PLDM_ERROR, 0); deleteAIOobjects(xdmaInterface, responseHdr); } - return {}; } -int FileHandler::transferFileDataToSocket(int32_t fd, uint32_t& length, +void FileHandler::transferFileDataToSocket(int32_t fd, uint32_t& length, uint64_t address, ResponseHdr& responseHdr, sdeventplus::Event& event) @@ -312,7 +317,7 @@ int FileHandler::transferFileDataToSocket(int32_t fd, uint32_t& length, return {}; } -int FileHandler::transferFileData(const fs::path& path, bool upstream, +void FileHandler::transferFileData(const fs::path& path, bool upstream, uint32_t offset, uint32_t& length, uint64_t address, ResponseHdr& responseHdr, sdeventplus::Event& event) @@ -323,7 +328,7 @@ int FileHandler::transferFileData(const fs::path& path, bool upstream, fileExists = fs::exists(path); if (!fileExists) { - std::cerr << "File does not exist. PATH=" << path.c_str() << "\n"; + error("File does not exist. PATH={PATH}", "PATH", path.c_str()); dmaResponseToHost(responseHdr, PLDM_INVALID_FILE_HANDLE, length); deleteAIOobjects(nullptr, responseHdr); return PLDM_INVALID_FILE_HANDLE; @@ -332,8 +337,10 @@ int FileHandler::transferFileData(const fs::path& path, bool upstream, size_t fileSize = fs::file_size(path); if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error( + "FileHandler::transferFileData: Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE} FILE_HANDLE={FILE_HANDLE}", + "OFFSET", offset, "FILE_SIZE", fileSize, "FILE_HANDLE", + fileHandle); dmaResponseToHost(responseHdr, PLDM_DATA_OUT_OF_RANGE, length); deleteAIOobjects(nullptr, responseHdr); return PLDM_DATA_OUT_OF_RANGE; @@ -360,7 +367,7 @@ int FileHandler::transferFileData(const fs::path& path, bool upstream, int file = open(path.string().c_str(), flags | O_NONBLOCK); if (file == -1) { - std::cerr << "File does not exist, PATH = " << path.string() << "\n"; + error("File does not exist, PATH = {PATH}", "PATH", path.string()); dmaResponseToHost(responseHdr, PLDM_ERROR, 0); deleteAIOobjects(nullptr, responseHdr); return PLDM_ERROR; @@ -515,16 +522,17 @@ int FileHandler::readFile(const std::string& filePath, uint32_t offset, { if (!fs::exists(filePath)) { - std::cerr << "File does not exist, HANDLE=" << fileHandle - << " PATH=" << filePath.c_str() << "\n"; + error("File does not exist, HANDLE={FILE_HNDLE} PATH={PATH}", + "FILE_HNDLE", fileHandle, "PATH", filePath.c_str()); return PLDM_INVALID_FILE_HANDLE; } size_t fileSize = fs::file_size(filePath); if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error( + "FileHandler::readFileData: Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE} FILE_HANDLE={FILE_HANDLE}", + "OFFSET", offset, "FILE_SIZE", fileSize, "FILE_HANDLE", fileHandle); return PLDM_DATA_OUT_OF_RANGE; } @@ -544,7 +552,8 @@ int FileHandler::readFile(const std::string& filePath, uint32_t offset, stream.read(filePos, length); return PLDM_SUCCESS; } - std::cerr << "Unable to read file, FILE=" << filePath.c_str() << "\n"; + error("Unable to read file, FILE={FILE_PATH}", "FILE_PATH", + filePath.c_str()); return PLDM_ERROR; } diff --git a/oem/ibm/libpldmresponder/file_io_type_cert.cpp b/oem/ibm/libpldmresponder/file_io_type_cert.cpp index 5c1fcdeff..db81419a7 100644 --- a/oem/ibm/libpldmresponder/file_io_type_cert.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_cert.cpp @@ -7,15 +7,18 @@ #include +#include + #include +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace utils; namespace responder { - constexpr auto certObjPath = "/xyz/openbmc_project/certs/ca/entry/"; constexpr auto certEntryIntf = "xyz.openbmc_project.Certs.Entry"; static constexpr auto certFilePath = "/var/lib/ibm/bmcweb/"; @@ -31,8 +34,9 @@ int CertHandler::writeFromMemory(uint32_t offset, uint32_t length, auto it = certMap.find(certType); if (it == certMap.end()) { - std::cerr << "CertHandler::writeFromMemory:file for type " << certType - << " doesn't exist\n"; + error( + "CertHandler::writeFromMemory:file for type {CERT_TYP} doesn't exist", + "CERT_TYP", certType); FileHandler::dmaResponseToHost(responseHdr, PLDM_ERROR, 0); FileHandler::deleteAIOobjects(nullptr, responseHdr); return PLDM_ERROR; @@ -95,9 +99,9 @@ int CertHandler::readIntoMemory(uint32_t offset, uint32_t& length, int CertHandler::read(uint32_t offset, uint32_t& length, Response& response, oem_platform::Handler* /*oemPlatformHandler*/) { - std::cout - << " CertHandler::read:Read file response for Sign CSR, file handle: " - << fileHandle << std::endl; + info( + "CertHandler::read:Read file response for Sign CSR, file handle: {FILE_HNDL}", + "FILE_HNDL", fileHandle); std::string filePath = certFilePath; filePath += "CSR_" + std::to_string(fileHandle); if (certType != PLDM_FILE_TYPE_CERT_SIGNING_REQUEST) @@ -119,8 +123,8 @@ int CertHandler::write(const char* buffer, uint32_t offset, uint32_t& length, auto it = certMap.find(certType); if (it == certMap.end()) { - std::cerr << "CertHandler::write:file for type " << certType - << " doesn't exist\n"; + error("CertHandler::write:file for type {CERT_TYP} doesn't exist", + "CERT_TYP", certType); return PLDM_ERROR; } @@ -128,15 +132,17 @@ int CertHandler::write(const char* buffer, uint32_t offset, uint32_t& length, int rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { - std::cerr << "CertHandler::write:lseek failed, ERROR=" << errno - << ", OFFSET=" << offset << "\n"; + error( + "CertHandler::write:lseek failed, ERROR={ERR_EXCEP}, OFFSET={OFFSET}", + "ERR_EXCEP", errno, "OFFSET", offset); return PLDM_ERROR; } rc = ::write(fd, buffer, length); if (rc == -1) { - std::cerr << "CertHandler::write:file write failed, ERROR=" << errno - << ", LENGTH=" << length << ", OFFSET=" << offset << "\n"; + error( + "CertHandler::write:file write failed, ERROR={ERR_EXCEP}, LENGTH={LEN}, OFFSET={OFFSET}", + "ERR_EXCEP", errno, "LEN", length, "OFFSET", offset); return PLDM_ERROR; } length = rc; @@ -175,10 +181,9 @@ int CertHandler::write(const char* buffer, uint32_t offset, uint32_t& length, } catch (const std::exception& e) { - std::cerr - << "CertHandler::write:failed to set Client certificate, " - "ERROR=" - << e.what() << "\n"; + error( + "CertHandler::write:failed to set Client certificate, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } PropertyValue valueStatus{ @@ -188,18 +193,17 @@ int CertHandler::write(const char* buffer, uint32_t offset, uint32_t& length, certEntryIntf, "Status", "string"}; try { - std::cout - << "CertHandler::write:Client cert write, status: complete. File handle: " - << fileHandle << std::endl; + info( + "CertHandler::write:Client cert write, status: complete. File handle: {FILE_HNDL}", + "FILE_HNDL", fileHandle); pldm::utils::DBusHandler().setDbusProperty(dbusMappingStatus, valueStatus); } catch (const std::exception& e) { - std::cerr - << "CertHandler::write:failed to set status property of certicate entry, " - "ERROR=" - << e.what() << "\n"; + error( + "CertHandler::write:failed to set status property of certicate entry, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } fs::remove(filePath); @@ -211,17 +215,16 @@ int CertHandler::write(const char* buffer, uint32_t offset, uint32_t& length, certEntryIntf, "Status", "string"}; try { - std::cout - << "CertHandler::write:Client cert write, status: Bad CSR. File handle: " - << fileHandle << std::endl; + info( + "CertHandler::write:Client cert write, status: Bad CSR. File handle: {FILE_HNDLE}", + "FILE_HNDLE", fileHandle); pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value); } catch (const std::exception& e) { - std::cerr - << "CertHandler::write:failed to set status property of certicate entry, " - "ERROR=" - << e.what() << "\n"; + error( + "CertHandler::write:failed to set status property of certicate entry, {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -244,9 +247,9 @@ int CertHandler::newFileAvailable(uint64_t length) } if (certType == PLDM_FILE_TYPE_SIGNED_CERT) { - std::cout - << "CertHandler::newFileAvailable:new file available client cert file, file handle: " - << fileHandle << std::endl; + info( + "CertHandler::newFileAvailable:new file available client cert file, file handle: {FILE_HNDLE}", + "FILE_HNDLE", fileHandle); fileFd = open( (filePath + "ClientCert_" + std::to_string(fileHandle)).c_str(), flags, S_IRUSR | S_IWUSR); @@ -258,9 +261,9 @@ int CertHandler::newFileAvailable(uint64_t length) } if (fileFd == -1) { - std::cerr - << "CertHandler::newFileAvailable:failed to open file for type " - << certType << " ERROR=" << errno << "\n"; + error( + "CertHandler::newFileAvailable:failed to open file for type {CERT_TYP} ERROR={ERR_EXCEP}", + "CERT_TYP", certType, "ERR_EXCEP", errno); return PLDM_ERROR; } certMap.emplace(certType, std::tuple(fileFd, length)); @@ -289,18 +292,18 @@ int CertHandler::newFileAvailableWithMetaData(uint64_t length, { if (certSigningStatus == PLDM_SUCCESS) { - std::cerr - << "CertHandler::newFileAvailableWithMetaData:new file available client cert file, file handle: " - << fileHandle << std::endl; + error( + "CertHandler::newFileAvailableWithMetaData:new file available client cert file, file handle: {FILE_HNDL}", + "FILE_HNDL", fileHandle); fileFd = open( (filePath + "ClientCert_" + std::to_string(fileHandle)).c_str(), flags, S_IRUSR | S_IWUSR); } else if (certSigningStatus == PLDM_INVALID_CERT_DATA) { - std::cerr - << "newFileAvailableWithMetaData:client cert file Invalid data, file handle: " - << fileHandle << std::endl; + error( + "newFileAvailableWithMetaData:client cert file Invalid data, file handle: {FILE_HNDL}", + "FILE_HNDL", fileHandle); DBusMapping dbusMapping{certObjPath + std::to_string(fileHandle), certEntryIntf, "Status", "string"}; std::string status = "xyz.openbmc_project.Certs.Entry.State.BadCSR"; @@ -311,10 +314,9 @@ int CertHandler::newFileAvailableWithMetaData(uint64_t length, } catch (const std::exception& e) { - std::cerr - << "newFileAvailableWithMetaData:Failed to set status property of certicate entry, " - "ERROR=" - << e.what() << "\n"; + error( + "newFileAvailableWithMetaData:Failed to set status property of certicate entry, ERROR= {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -326,9 +328,9 @@ int CertHandler::newFileAvailableWithMetaData(uint64_t length, } if (fileFd == -1) { - std::cerr - << "newFileAvailableWithMetaData:failed to open file for type " - << certType << " ERROR=" << errno << "\n"; + error( + "newFileAvailableWithMetaData:failed to open file for type {CERT_TYP} ERROR={ERR_EXCEP}", + "CERT_TYP", certType, "ERR_EXCEP", errno); return PLDM_ERROR; } certMap.emplace(certType, std::tuple(fileFd, length)); @@ -363,10 +365,9 @@ int CertHandler::fileAckWithMetaData(uint8_t fileStatus, } catch (const std::exception& e) { - std::cerr - << "CertHandler::fileAckWithMetaData:Failed to set status property of certicate entry, " - "ERROR=" - << e.what() << "\n"; + error( + "CertHandler::fileAckWithMetaData:Failed to set status property of certicate entry, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } diff --git a/oem/ibm/libpldmresponder/file_io_type_dump.cpp b/oem/ibm/libpldmresponder/file_io_type_dump.cpp index dc29b626b..630ba4ce7 100644 --- a/oem/ibm/libpldmresponder/file_io_type_dump.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_dump.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -19,6 +20,7 @@ #include #include +PHOSPHOR_LOG2_USING; using namespace pldm::responder::utils; using namespace pldm::utils; @@ -104,15 +106,17 @@ std::string DumpHandler::findDumpObjPath(uint32_t fileHandle) auto method = bus.new_method_call(DUMP_MANAGER_BUSNAME, DUMP_MANAGER_PATH, OBJECT_MANAGER_INTERFACE, "GetManagedObjects"); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(objects); } catch (const sdbusplus::exception_t& e) { - std::cerr - << "Failure with GetManagedObjects in findDumpObjPath call, ERROR=" - << e.what() << "\n"; + error( + "Failure with GetManagedObjects in findDumpObjPath call, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.findDumpObjPath.GetManagedObjectsFail", pldm::PelSeverity::WARNING); @@ -139,18 +143,16 @@ std::string DumpHandler::findDumpObjPath(uint32_t fileHandle) if (fileHandle == dumpId) { curResDumpEntryPath = object.first.str; - std::cout << "Hit the object path match for" - << curResDumpEntryPath << std::endl; + info("Hit the object path match for {CUR_RES_DUMP}", + "CUR_RES_DUMP", curResDumpEntryPath); return curResDumpEntryPath; } } else { - std::cerr - << "Invalid SourceDumpId in curResDumpEntryPath " - << curResDumpEntryPath - << " but continuing with next entry for a match..." - << std::endl; + error( + "Invalid SourceDumpId in curResDumpEntryPath {CUR_RES_DUMP} but continuing with next entry for a match...", + "CUR_RES_DUMP", curResDumpEntryPath); } } } @@ -164,7 +166,7 @@ int DumpHandler::newFileAvailable(uint64_t length) static constexpr auto dumpInterface = "xyz.openbmc_project.Dump.NewDump"; auto& bus = pldm::utils::DBusHandler::getBus(); - std::cout << "newFileAvailable for NewDump" << std::endl; + info("newFileAvailable for NewDump"); auto notifyObjPath = dumpObjPath; if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP) { @@ -180,13 +182,15 @@ int DumpHandler::newFileAvailable(uint64_t length) auto method = bus.new_method_call(service.c_str(), notifyObjPath, dumpInterface, "Notify"); method.append(fileHandle, length); - bus.call(method); + bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const sdbusplus::exception_t& e) { - std::cerr << "failed to make a d-bus call to notify" - " a new dump request using newFileAvailable, ERROR=" - << e.what() << "\n"; + error( + "failed to make a d-bus call to notify a new dump request using newFileAvailable, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.newFileAvailable.NewDumpNotifyFail", pldm::PelSeverity::ERROR); @@ -204,8 +208,9 @@ void DumpHandler::resetOffloadUri() return; } - std::cout << "DumpHandler::resetOffloadUri path = " << path.c_str() - << " fileHandle = " << fileHandle << std::endl; + info("DumpHandler::resetOffloadUri path = {PATH} fileHandle = {FILE_HNDLE}", + "PATH", path.c_str(), "FILE_HNDL", fileHandle); + PropertyValue offloadUriValue{""}; DBusMapping dbusMapping{path, dumpEntry, "OffloadUri", "string"}; try @@ -215,8 +220,8 @@ void DumpHandler::resetOffloadUri() } catch (const sdbusplus::exception_t& e) { - std::cerr << "Failed to set the OffloadUri dbus property, ERROR=" - << e.what() << "\n"; + error("Failed to set the OffloadUri dbus property, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAck.DumpEntryOffloadUriSetFail", pldm::PelSeverity::ERROR); @@ -227,8 +232,8 @@ void DumpHandler::resetOffloadUri() std::string DumpHandler::getOffloadUri(uint32_t fileHandle) { auto path = findDumpObjPath(fileHandle); - std::cout << "DumpHandler::getOffloadUri path = " << path.c_str() - << " fileHandle = " << fileHandle << std::endl; + info("DumpHandler::getOffloadUri path = {PATH} fileHandle = {FILE_HNDL}", + "PATH", path.c_str(), "FILE_HNDL", fileHandle); if (path.empty()) { return {}; @@ -241,12 +246,12 @@ std::string DumpHandler::getOffloadUri(uint32_t fileHandle) socketInterface = pldm::utils::DBusHandler().getDbusProperty( path.c_str(), "OffloadUri", dumpEntry); - std::cout << "socketInterface=" << socketInterface << std::endl; + info("socketInterface={SOCKET_INTF}", "SOCKET_INTF", socketInterface); } catch (const sdbusplus::exception_t& e) { - std::cerr << "Failed to get the OffloadUri d-bus property, ERROR=" - << e.what() << "\n"; + error("Failed to get the OffloadUri d-bus property, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.DumpHandler.getOffloadUriFail", pldm::PelSeverity::ERROR); @@ -260,9 +265,7 @@ int DumpHandler::postDataTransferCallBack(bool IsWriteToMemOp) /// execute when DMA transfer failed. if (IsWriteToMemOp) { - std::cerr - << "DumpHandler::writeFromMemory: transferFileDataToSocket failed" - << std::endl; + error("DumpHandler::writeFromMemory: transferFileDataToSocket failed"); if (DumpHandler::fd >= 0) { close(DumpHandler::fd); @@ -316,14 +319,14 @@ int DumpHandler::writeFromMemory(uint32_t, uint32_t length, uint64_t address, int DumpHandler::write(const char* buffer, uint32_t, uint32_t& length, oem_platform::Handler* /*oemPlatformHandler*/) { - std::cout << "Enter DumpHandler::write length = " << length - << " DumpHandler::fd = " << DumpHandler::fd << std::endl; + info( + "Enter DumpHandler::write length = {LEN} DumpHandler::fd ={FILE_DESCRIPTION}", + "LEN", length, "FILE_DESCRIPTION", DumpHandler::fd); int rc = writeToUnixSocket(DumpHandler::fd, buffer, length); if (rc < 0) { - std::cerr << "DumpHandler::write: Error while writing to Unix socket" - << std::endl; + error("DumpHandler::write: Error while writing to Unix socket"); close(fd); auto socketInterface = getOffloadUri(fileHandle); std::remove(socketInterface.c_str()); @@ -341,7 +344,7 @@ int DumpHandler::fileAck(uint8_t fileStatus) { if (fileStatus != PLDM_SUCCESS) { - std::cerr << "Failue in resource dump file ack" << std::endl; + error("Failue in resource dump file ack"); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAck.ResourceDumpFileAckFail", PelSeverity::INFORMATIONAL); @@ -356,10 +359,9 @@ int DumpHandler::fileAck(uint8_t fileStatus) } catch (const sdbusplus::exception_t& e) { - std::cerr - << "Failure in setting Progress as OperationStatus.Failed" - "in fileAck, ERROR=" - << e.what() << "\n"; + error( + "Failure in setting Progress as OperationStatus.Failed in fileAck, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -395,10 +397,9 @@ int DumpHandler::fileAck(uint8_t fileStatus) } catch (const sdbusplus::exception_t& e) { - std::cerr << "Failed to make a d-bus call to DUMP " - "manager to reset source dump id of " - << path.c_str() << ", with ERROR=" << e.what() - << "\n"; + error( + "Failed to make a d-bus call to DUMP manager to reset source dump id of {PATH}, with ERROR={ERR_EXCEP}", + "PATH", path.c_str(), "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAck.SourceDumpIdResetFail", pldm::PelSeverity::ERROR); @@ -412,13 +413,15 @@ int DumpHandler::fileAck(uint8_t fileStatus) auto method = bus.new_method_call( "xyz.openbmc_project.Dump.Manager", path.c_str(), "xyz.openbmc_project.Object.Delete", "Delete"); - bus.call(method); + bus.call(method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } catch (const sdbusplus::exception_t& e) { - std::cerr - << "Failed to make a d-bus method to delete the dump entry " - << path.c_str() << ", with ERROR=" << e.what() << "\n"; + error( + "Failed to make a d-bus method to delete the dump entry {PATH}, with ERROR={ERR_EXCEP}", + "PATH", path.c_str(), "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAck.DumpEntryDeleteFail", pldm::PelSeverity::ERROR); @@ -438,9 +441,9 @@ int DumpHandler::fileAck(uint8_t fileStatus) } catch (const sdbusplus::exception_t& e) { - std::cerr - << "Failed to set the Offloaded dbus property to true, ERROR=" - << e.what() << "\n"; + error( + "Failed to set the Offloaded dbus property to true, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAck.DumpEntryOffloadedSetFail", pldm::PelSeverity::ERROR); @@ -493,9 +496,9 @@ int DumpHandler::readIntoMemory(uint32_t offset, uint32_t& length, } catch (const sdbusplus::exception_t& e) { - std::cerr << "Failed to fetch the filepath of the dump entry" - << std::hex << fileHandle << ", error = " << e.what() - << "\n"; + error( + "Failed to fetch the filepath of the dump entry {FILE_HNDLE}, ERROR={ERR_EXCEP}", + "FILE_HNDLE", lg2::hex, fileHandle, "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.readIntoMemory.GetFilepathFail", pldm::PelSeverity::ERROR); @@ -532,9 +535,9 @@ int DumpHandler::read(uint32_t offset, uint32_t& length, Response& response, } catch (const sdbusplus::exception_t& e) { - std::cerr << "Failed to fetch the filepath of the dump entry" - << std::hex << fileHandle << ", error = " << e.what() - << "\n"; + error( + "Failed to fetch the filepath of the dump entry {FILE_HNDLE}, ERROR={ERR_EXCEP}", + "FILE_HNDL", lg2::hex, fileHandle, "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.read.GetFilepathFail", pldm::PelSeverity::ERROR); @@ -564,8 +567,9 @@ int DumpHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, pldm::utils::PropertyValue value = "com.ibm.Dump.Entry.Resource.HostResponse.Success"; - std::cout << "fileAckWithMetaData with token: " << metaDataValue1 - << " and status: " << metaDataValue2 << std::endl; + info( + "fileAckWithMetaData with token: {META_DATA_VAL1} and status: {META_DATA_VAL2}", + "META_DATA_VAL1", metaDataValue1, "META_DATA_VAL2", metaDataValue2); if (statusCode == DumpRequestStatus::ResourceSelectorInvalid) { value = @@ -603,9 +607,9 @@ int DumpHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set token for resource dump, ERROR=" - << e.what() << "\n"; - return PLDM_ERROR; + error("failed to set token for resource dump, + ERROR={ERR_EXCEP}", "ERR_EXCEP", e.what()); + return PLDM_ERROR; }*/ } @@ -615,17 +619,15 @@ int DumpHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const sdbusplus::exception_t& e) { - std::cerr - << "failed to set DumpRequestStatus property for resource dump entry, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set DumpRequestStatus property for resource dump entry, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } if (statusCode != DumpRequestStatus::Success) { - std::cerr << "Failue in resource dump file ack with metadata" - << std::endl; + error("Failue in resource dump file ack with metadata"); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAck.ResourceDumpFileAckWithMetaDataFail", pldm::PelSeverity::INFORMATIONAL); @@ -641,10 +643,9 @@ int DumpHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const sdbusplus::exception_t& e) { - std::cerr - << "Failure in setting Progress as OperationStatus.Failed" - "in fileAckWithMetaData, ERROR=" - << e.what() << "\n"; + error( + "Failure in setting Progress as OperationStatus.Failed in fileAckWithMetaData, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -668,9 +669,9 @@ int DumpHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const sdbusplus::exception_t& e) { - std::cerr - << "Failed to set the Offloaded dbus property to true, ERROR=" - << e.what() << "\n"; + error( + "Failed to set the Offloaded dbus property to true, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.fileAckWithMetaData.DumpEntryOffloadedSetFail", pldm::PelSeverity::ERROR); @@ -698,8 +699,8 @@ int DumpHandler::newFileAvailableWithMetaData(uint64_t length, static constexpr auto dumpInterface = "xyz.openbmc_project.Dump.NewDump"; auto& bus = pldm::utils::DBusHandler::getBus(); - std::cout << "newFileAvailableWithMetaData for NewDump with token :" - << metaDataValue1 << std::endl; + info("newFileAvailableWithMetaData for NewDump with token :{META_DATA_VAL}", + "META_DATA_VAL", metaDataValue1); auto notifyObjPath = dumpObjPath; if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP) { @@ -718,14 +719,15 @@ int DumpHandler::newFileAvailableWithMetaData(uint64_t length, // once dump manager changes are merged method.append(fileHandle, length); // need to append metaDataValue1 once // dump manager changes are merged - bus.call(method); + bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const sdbusplus::exception_t& e) { - std::cerr - << "failed to make a d-bus call to notify" - " a new dump request using newFileAvailableWithMetaData, ERROR=" - << e.what() << "\n"; + error( + "failed to make a d-bus call to notify a new dump request using newFileAvailableWithMetaData, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.newFileAvailableWithMetaData.NewDumpNotifyFail", pldm::PelSeverity::ERROR); diff --git a/oem/ibm/libpldmresponder/file_io_type_lic.cpp b/oem/ibm/libpldmresponder/file_io_type_lic.cpp index 269f418d1..db37580db 100644 --- a/oem/ibm/libpldmresponder/file_io_type_lic.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_lic.cpp @@ -7,8 +7,12 @@ #include +#include + #include +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace pldm::responder::utils; @@ -19,7 +23,6 @@ const std::vector emptyJsonList{}; namespace responder { - static constexpr auto codFilePath = "/var/lib/ibm/cod/"; static constexpr auto licFilePath = "/var/lib/pldm/license/"; constexpr auto newLicenseFile = "new_license.bin"; @@ -33,8 +36,8 @@ int LicenseHandler::updateBinFileAndLicObjs(const fs::path& newLicJsonFilePath) auto dataNew = Json::parse(jsonFileNew, nullptr, false); if (dataNew.is_discarded()) { - std::cerr << "Parsing the new license json file failed, FILE=" - << newLicJsonFilePath << "\n"; + error("Parsing the new license json file failed, FILE={NEW_LIC_JSON}", + "NEW_LIC_JSON", newLicJsonFilePath.c_str()); throw InternalFailure(); } @@ -45,8 +48,7 @@ int LicenseHandler::updateBinFileAndLicObjs(const fs::path& newLicJsonFilePath) rc = createOrUpdateLicenseObjs(); if (rc != PLDM_SUCCESS) { - std::cerr << "createOrUpdateLicenseObjs failed with rc= " << rc - << " \n"; + error("createOrUpdateLicenseObjs failed with rc= {RC}", "RC", rc); return rc; } return PLDM_SUCCESS; @@ -69,8 +71,8 @@ int LicenseHandler::writeFromMemory( std::ios::out | std::ios::binary); if (!licJsonFile) { - std::cerr << "license json file create error: " << newLicJsonFilePath - << std::endl; + error("license json file create error: {NEW_LIC_JSON}", "NEW_LIC_JSON", + newLicJsonFilePath.c_str()); FileHandler::dmaResponseToHost(responseHdr, PLDM_ERROR, 0); FileHandler::deleteAIOobjects(nullptr, responseHdr); return -1; @@ -91,8 +93,7 @@ int LicenseHandler::postDataTransferCallBack(bool IsWriteToMemOp) int rc = updateBinFileAndLicObjs(newLicJsonFilePath); if (rc != PLDM_SUCCESS) { - std::cerr << "updateBinFileAndLicObjs failed with rc= " << rc - << " \n"; + error("transferFileData failed with rc= {RC}", "RC", rc); return -1; } return rc; @@ -116,8 +117,8 @@ int LicenseHandler::write(const char* buffer, uint32_t /*offset*/, std::ios::out | std::ios::binary | std::ios::app); if (!licJsonFile) { - std::cerr << "license json file create error: " << newLicJsonFilePath - << std::endl; + error("license json file create error: {NEW_LIC_JSON}", "NEW_LIC_JSON", + newLicJsonFilePath.c_str()); return -1; } @@ -129,7 +130,7 @@ int LicenseHandler::write(const char* buffer, uint32_t /*offset*/, updateBinFileAndLicObjs(newLicJsonFilePath); if (rc != PLDM_SUCCESS) { - std::cerr << "updateBinFileAndLicObjs failed with rc= " << rc << " \n"; + error("updateBinFileAndLicObjs failed with rc= {RC}", "RC", rc); return rc; } @@ -186,9 +187,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -203,9 +204,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -220,9 +221,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -237,9 +238,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -254,9 +255,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -271,9 +272,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } @@ -288,9 +289,9 @@ int LicenseHandler::fileAckWithMetaData(uint8_t /*fileStatus*/, } catch (const std::exception& e) { - std::cerr << "failed to set status property of license manager, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set status property of license manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } diff --git a/oem/ibm/libpldmresponder/file_io_type_lid.hpp b/oem/ibm/libpldmresponder/file_io_type_lid.hpp index d9f314369..775b6f923 100644 --- a/oem/ibm/libpldmresponder/file_io_type_lid.hpp +++ b/oem/ibm/libpldmresponder/file_io_type_lid.hpp @@ -1,15 +1,19 @@ #pragma once -#include "config.h" - -#include "file_io.hpp" +#include "file_io_by_type.hpp" +#include "xyz/openbmc_project/Common/error.hpp" +#include +#include +#include #include #include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder @@ -20,9 +24,13 @@ using MarkerLIDremainingSize = uint64_t; constexpr auto markerLidName = "80a00001.lid"; constexpr auto accessKeyExpired = - "sdbusplus::xyz::openbmc_project::Software::Version::Error::ExpiredAccessKey"; + "xyz.openbmc_project.Software.Version.Error.ExpiredAccessKey"; +using AccessKeyExpired = + sdbusplus::xyz::openbmc_project::Software::Version::Error::ExpiredAccessKey; constexpr auto incompatibleErr = - "sdbusplus::xyz::openbmc_project::Software::Version::Error::Incompatible"; + "xyz.openbmc_project.Software.Version.Error.Incompatible"; +using IncompatibleErr = + sdbusplus::xyz::openbmc_project::Software::Version::Error::Incompatible; /** @class LidHandler * @@ -120,10 +128,8 @@ class LidHandler : public FileHandler return true; } - int validateMarkerLid(oem_platform::Handler* oemPlatformHandler, - const std::string& lidPath) + void validateMarkerLid(oem_platform::Handler* oemPlatformHandler) { - int rc = PLDM_SUCCESS; if (oemPlatformHandler != nullptr) { pldm::responder::oem_ibm_platform::Handler* oemIbmPlatformHandler = @@ -134,44 +140,37 @@ class LidHandler : public FileHandler using namespace pldm::responder::oem_ibm_platform; auto markerLidDirPath = fs::path(LID_STAGING_DIR) / "lid" / markerLidName; + uint8_t validateStatus = VALID; try { auto& bus = pldm::utils::DBusHandler::getBus(); - rc = processCodeUpdateLid(lidPath); - if (rc != PLDM_SUCCESS) - { - return rc; - } auto method = bus.new_method_call( "xyz.openbmc_project.Software.BMC.Updater", "/xyz/openbmc_project/software", "xyz.openbmc_project.Software.LID", "Validate"); method.append(markerLidDirPath.c_str()); - bus.call(method); + bus.call(method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } catch (const sdbusplus::exception::exception& e) { - uint8_t validateStatus = 0; - if (strcmp(e.name(), accessKeyExpired) != 0) + if (strcmp(e.name(), accessKeyExpired) == 0) { + phosphor::logging::commit(); validateStatus = ENTITLEMENT_FAIL; } - else if (strcmp(e.name(), incompatibleErr) != 0) + else if (strcmp(e.name(), incompatibleErr) == 0) { + phosphor::logging::commit(); validateStatus = MIN_MIF_FAIL; } - std::cerr << "Marker lid validate error, " - << "ERROR=" << e.what() << std::endl; - oemIbmPlatformHandler->sendStateSensorEvent( - sensorId, PLDM_STATE_SENSOR_STATE, 0, validateStatus, - VALID); - return PLDM_ERROR; + error("Marker lid validate error, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } oemIbmPlatformHandler->sendStateSensorEvent( - sensorId, PLDM_STATE_SENSOR_STATE, 0, VALID, VALID); - rc = PLDM_SUCCESS; + sensorId, PLDM_STATE_SENSOR_STATE, 0, validateStatus, VALID); } - return rc; } virtual int writeFromMemory(uint32_t offset, uint32_t length, @@ -212,8 +211,8 @@ class LidHandler : public FileHandler auto fd = open(lidPath.c_str(), flags, S_IRUSR); if (fd == -1) { - std::cerr << "Could not open file for writing " << lidPath.c_str() - << "\n"; + error("Could not open file for writing {LID_PATH}", "LID_PATH", + lidPath.c_str()); FileHandler::dmaResponseToHost(responseHdr, PLDM_ERROR, 0); FileHandler::deleteAIOobjects(nullptr, responseHdr); return PLDM_ERROR; @@ -234,20 +233,14 @@ class LidHandler : public FileHandler { if (lidType == PLDM_FILE_TYPE_LID_MARKER) { - markerLIDremainingSize -= m_length; + markerLIDremainingSize -= length; if (markerLIDremainingSize == 0) { - pldm::responder::oem_ibm_platform::Handler* - oemIbmPlatformHandler = dynamic_cast< - pldm::responder::oem_ibm_platform::Handler*>( - moemPlatformHandler); - auto sensorId = - oemIbmPlatformHandler->codeUpdate->getMarkerLidSensor(); - using namespace pldm::responder::oem_ibm_platform; - oemIbmPlatformHandler->sendStateSensorEvent( - sensorId, PLDM_STATE_SENSOR_STATE, 0, VALID, VALID); - // rc = validate api; - rc = PLDM_SUCCESS; + rc = processCodeUpdateLid(lidPath); + if (rc == PLDM_SUCCESS) + { + validateMarkerLid(oemPlatformHandler); + } } } else if (mcodeUpdateInProgress) @@ -310,8 +303,10 @@ class LidHandler : public FileHandler size_t fileSize = fs::file_size(lidPath); if (offset > fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << "\n"; + error( + "LidHandler::write: Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE} FILE_HANDLE={FILE_HANDLE}", + "OFFSET", offset, "FILE_SIZE", fileSize, "FILE_HANDLE", + fileHandle); return PLDM_DATA_OUT_OF_RANGE; } } @@ -320,28 +315,30 @@ class LidHandler : public FileHandler flags = O_WRONLY | O_CREAT | O_TRUNC | O_SYNC; if (offset > 0) { - std::cerr << "Offset is non zero in a new file \n"; + error("Offset is non zero in a new file"); return PLDM_DATA_OUT_OF_RANGE; } } auto fd = open(lidPath.c_str(), flags, S_IRUSR); if (fd == -1) { - std::cerr << "could not open file " << lidPath.c_str() << "\n"; + error("could not open file {LID_PATH}", "LID_PATH", + lidPath.c_str()); return PLDM_ERROR; } rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { - std::cerr << "lseek failed, ERROR=" << errno - << ", OFFSET=" << offset << "\n"; + error("lseek failed, ERROR={ERR}, OFFSET={OFFSET}", "ERR", errno, + "OFFSET", offset); return PLDM_ERROR; } rc = ::write(fd, buffer, length); if (rc == -1) { - std::cerr << "file write failed, ERROR=" << errno - << ", LENGTH=" << length << ", OFFSET=" << offset << "\n"; + error( + "file write failed, ERROR={ERR}, LENGTH={LEN}, OFFSET={OFFSET}", + "ERR", errno, "LEN", length, "OFFSET", offset); return PLDM_ERROR; } else if (rc == static_cast(length)) @@ -359,7 +356,11 @@ class LidHandler : public FileHandler markerLIDremainingSize -= length; if (markerLIDremainingSize == 0) { - rc = validateMarkerLid(oemPlatformHandler, lidPath); + rc = processCodeUpdateLid(lidPath); + if (rc == PLDM_SUCCESS) + { + validateMarkerLid(oemPlatformHandler); + } } } else if (codeUpdateInProgress) diff --git a/oem/ibm/libpldmresponder/file_io_type_pcie.cpp b/oem/ibm/libpldmresponder/file_io_type_pcie.cpp index 6acfbf1d4..c594563d4 100644 --- a/oem/ibm/libpldmresponder/file_io_type_pcie.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_pcie.cpp @@ -9,14 +9,17 @@ #include +#include + #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { - static constexpr auto pciePath = "/var/lib/pldm/pcie-topology/"; constexpr auto topologyFile = "topology"; constexpr auto cableInfoFile = "cableinfo"; @@ -24,6 +27,21 @@ constexpr auto itemPCIeSlot = "xyz.openbmc_project.Inventory.Item.PCIeSlot"; constexpr auto itemPCIeDevice = "xyz.openbmc_project.Inventory.Item.PCIeDevice"; constexpr auto itemConnector = "xyz.openbmc_project.Inventory.Item.Connector"; +// Slot location code structure contains multiple slot location code +// suffix structures. +// Each slot location code suffix structure is as follows +// {Slot location code suffix size(uint8_t), +// Slot location code suffix(variable size)} +constexpr auto sizeOfSuffixSizeDataMember = 1; + +// Each slot location structure contains +// { +// Number of slot location codes (1byte), +// Slot location code Common part size (1byte) +// Slot location common part (Var) +// } +constexpr auto slotLocationDataMemberSize = 2; + namespace fs = std::filesystem; std::unordered_map PCIeInfoHandler::receivedFiles; std::unordered_map(mexSlotandAdapter)); + std::vector> + associations; + for (auto slot : ioSlotLocationCode) + { + associations.emplace_back( + "containing", "contained_by", + getMexObjectFromLocationCode(slot, PLDM_ENTITY_SLOT)); + } + + pldm::dbus::CustomDBus::getCustomDBus().setAssociations( + std::get<1>(mexSlotandAdapter), associations); + // set topology info on both the slot and adapter object setTopologyOnSlotAndAdapter(linkType, mexSlotandAdapter, linkId, linkStatus, linkSpeed, linkWidth, true); @@ -623,8 +657,8 @@ void PCIeInfoHandler::parseSpeciallink(linkId_t linkId, // out the slot auto slotAndAdapter = pldm::responder::utils::getSlotAndAdapter( localPortLocCode.first); - std::cerr << "Special processing for link - [ " << linkId - << " ] \n"; + error("Special processing for link - [{LINK_ID}]", "LINK_ID", + linkId); setTopologyOnSlotAndAdapter( std::get<1>(linkInfo), slotAndAdapter, linkId, std::get<0>(linkInfo), std::get<2>(linkInfo), @@ -657,8 +691,7 @@ void PCIeInfoHandler::setTopologyAttrsOnDbus() std::get<0>(info), std::get<2>(info), std::get<3>(info)); break; case Unknown: - std::cerr << "link type is unkown : " << (unsigned)link - << std::endl; + error("link type is unkown : {LINK}", "LINK", (unsigned)link); switch (linkTypeInfo[link]) { case Primary: @@ -733,16 +766,15 @@ void PCIeInfoHandler::setTopologyAttrsOnDbus() pldm::dbus::CustomDBus::getCustomDBus().setAssociations( cableObjectPath.string(), associations); - - std::cerr << "Hosted Cable [ " << cable_no << " ] Length - [ " - << std::get<4>(info) << " ] Type - [ " << std::get<5>(info) - << " ] Status - [ " << std::get<6>(info) << " ] PN - [ " - << std::get<3>(info) << " ]\n"; - std::cerr << "Hosted Cable [ " << cable_no << " ] UPConnector - [ " - << upstreamInformation << " ] DNConnector - [ " - << downstreamInformation << " ] DChassis - [ " - << downstreamChassis << " ]\n"; - + error( + "Hosted Cable [ {CABLE_NO} ] Length - [ {LEN} ] Type - [ {CABLE_TYP} ] Status - [ {CABLE_STATUS} ] PN - [ {PN} ]", + "CABLE_NO", cable_no, "LEN", std::get<4>(info), "CABLE_TYP", + std::get<5>(info), "CABLE_STATUS", std::get<6>(info), "PN", + std::get<3>(info)); + error( + "Hosted Cable [ {CABLE_NO} ] UPConnector - [ {UP_CONN} ] DNConnector - [ {DN_CONN} ] DChassis - [ {D_CHASSIS} ]", + "CABLE_NO", cable_no, "UP_CONN", upstreamInformation, "DN_CONN", + downstreamInformation, "D_CHASSIS", downstreamChassis); cables.push_back(cableObjectPath.string()); } } @@ -785,7 +817,7 @@ void PCIeInfoHandler::parseTopologyData() if (MAP_FAILED == file_in_memory) { int rc = -errno; - std::cerr << "mmap on topology file failed, RC=" << rc << std::endl; + error("mmap on topology file failed, RC={RC}", "RC", rc); return; } @@ -801,8 +833,7 @@ void PCIeInfoHandler::parseTopologyData() } else { - std::cerr - << "Parsing of topology file failed : pcie_link_list is null\n"; + error("Parsing of topology file failed : pcie_link_list is null"); return; } @@ -811,7 +842,7 @@ void PCIeInfoHandler::parseTopologyData() if (single_entry_data == nullptr) { - std::cerr << "Parsing of topology file failed : single_link is null \n"; + error("Parsing of topology file failed : single_link is null"); return; } @@ -907,11 +938,9 @@ void PCIeInfoHandler::parseTopologyData() (struct SlotLocCode_t*)(((uint8_t*)single_entry_data) + htobe16(single_entry_data ->slot_loc_codes_offset)); - if (slot_data == nullptr) { - std::cerr - << "Parsing the topology file failed : slot_data is null \n"; + error("Parsing the topology file failed : slot_data is null"); return; } // get the Slot location code common part @@ -923,12 +952,12 @@ void PCIeInfoHandler::parseTopologyData() std::string slot_location_code(slot_location.begin(), slot_location.end()); - struct SlotLocCodeSuf_t* slot_loc_suf_data = - (struct SlotLocCodeSuf_t*)(((uint8_t*)slot_data) + 2 + - slot_data->slotLocCodesCmnPrtSize); - if (slot_loc_suf_data == nullptr) + uint8_t* suffix_data = (uint8_t*)slot_data + + slotLocationDataMemberSize + + slot_data->slotLocCodesCmnPrtSize; + if (suffix_data == nullptr) { - std::cerr << "slot location suffix data is nullptr \n"; + error("slot location suffix data is nullptr"); return; } @@ -939,6 +968,14 @@ void PCIeInfoHandler::parseTopologyData() for ([[maybe_unused]] const auto& slot : std::views::iota(0) | std::views::take(no_of_slots)) { + struct SlotLocCodeSuf_t* slot_loc_suf_data = + (struct SlotLocCodeSuf_t*)suffix_data; + if (slot_loc_suf_data == nullptr) + { + error("slot location suffix data is nullptr"); + break; + } + size_t slot_loccode_suffix_size = slot_loc_suf_data->slotLocCodeSz; if (slot_loccode_suffix_size > 0) { @@ -956,7 +993,8 @@ void PCIeInfoHandler::parseTopologyData() slot_final_location_code.push_back(slot_full_location_code); // move the pointer to next slot - slot_loc_suf_data += 2; + suffix_data += sizeOfSuffixSizeDataMember + + slot_loccode_suffix_size; } // store the information into a map @@ -1008,7 +1046,7 @@ void PCIeInfoHandler::parseCableInfo() if (MAP_FAILED == file_in_memory) { int rc = -errno; - std::cerr << "mmap on cable ifno file failed, RC=" << rc << std::endl; + error("mmap on cable ifno file failed, RC={RC}", "RC", rc); return; } @@ -1026,7 +1064,7 @@ void PCIeInfoHandler::parseCableInfo() if (cable_data == nullptr) { - std::cerr << "Cable info parsing failed , cable_data = nullptr \n"; + error("Cable info parsing failed , cable_data = nullptr"); return; } @@ -1118,8 +1156,8 @@ void PCIeInfoHandler::deleteTopologyFiles() } catch (const fs::filesystem_error& err) { - std::cerr << "Topology file deletion failed " << pciePath << " : " - << err.what() << "\n"; + error("Topology file deletion failed {PCIE_PATH} : {ERR_EXCEP}", + "PCIE_PATH", pciePath, "ERR_EXCEP", err.what()); } } } diff --git a/oem/ibm/libpldmresponder/file_io_type_pel.cpp b/oem/ibm/libpldmresponder/file_io_type_pel.cpp index a69048b98..5801e41fc 100644 --- a/oem/ibm/libpldmresponder/file_io_type_pel.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_pel.cpp @@ -1,5 +1,3 @@ -#include "config.h" - #include "file_io_type_pel.hpp" #include "libpldm/base.h" @@ -14,6 +12,8 @@ #include #include +#include +#include #include #include @@ -23,16 +23,17 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { - using namespace sdbusplus::xyz::openbmc_project::Logging::server; +using namespace sdbusplus::org::open_power::Logging::server; namespace detail { - /** * @brief Finds the Entry::Level value for the severity of the PEL * passed in. @@ -85,7 +86,8 @@ Entry::Level getEntryLevelFromPEL(const std::string& pelFileName) } else { - std::cerr << "Unable to open PEL file " << pelFileName << "\n"; + error("Unable to open PEL file {PEL_FILE_NAME}", "PEL_FILE_NAME", + pelFileName); } } @@ -115,8 +117,8 @@ int PelHandler::readIntoMemory(uint32_t offset, uint32_t& length, fd = dup(unixfd); if (fd == -1) { - std::cerr << "Error: Cloning pel file descriptor failed...Error:" - << errno << "\n"; + error("Error: Cloning pel file descriptor failed...Error:{ERROR}", + "ERROR", errno); FileHandler::dmaResponseToHost(responseHdr, PLDM_ERROR, 0); FileHandler::deleteAIOobjects(nullptr, responseHdr); } @@ -124,8 +126,10 @@ int PelHandler::readIntoMemory(uint32_t offset, uint32_t& length, } catch (const std::exception& e) { - std::cerr << "GetPEL D-Bus call failed, PEL id = 0x" << std::hex - << fileHandle << ", error = " << e.what() << "\n"; + error( + "GetPEL D-Bus call failed, PEL id = 0x{FILE_HNDL}, error ={ERR_EXCEP}", + "FILE_HNDL", lg2::hex, fileHandle, "ERR_EXCEP", e.what()); + FileHandler::dmaResponseToHost(responseHdr, PLDM_ERROR, 0); FileHandler::deleteAIOobjects(nullptr, responseHdr); } @@ -146,20 +150,24 @@ int PelHandler::read(uint32_t offset, uint32_t& length, Response& response, auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); sdbusplus::message::unix_fd fd{}; reply.read(fd); off_t fileSize = lseek(fd, 0, SEEK_END); if (fileSize == -1) { - std::cerr << "file seek failed"; + error("file seek failed"); return PLDM_ERROR; } if (offset >= fileSize) { - std::cerr << "Offset exceeds file size, OFFSET=" << offset - << " FILE_SIZE=" << fileSize << std::endl; + error( + "PelHandler::read: Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE} FILE_HANDLE={FILE_HANDLE}", + "OFFSET", offset, "FILE_SIZE", fileSize, "FILE_HANDLE", + fileHandle); return PLDM_DATA_OUT_OF_RANGE; } if (offset + length > fileSize) @@ -169,7 +177,7 @@ int PelHandler::read(uint32_t offset, uint32_t& length, Response& response, auto rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { - std::cerr << "file seek failed"; + error("file seek failed"); return PLDM_ERROR; } size_t currSize = response.size(); @@ -179,21 +187,22 @@ int PelHandler::read(uint32_t offset, uint32_t& length, Response& response, rc = ::read(fd, filePos, length); if (rc == -1) { - std::cerr << "file read failed"; + error("file read failed"); return PLDM_ERROR; } if (rc != length) { - std::cerr << "mismatch between number of characters to read and " - << "the length read, LENGTH=" << length << " COUNT=" << rc - << std::endl; + error( + "mismatch between number of characters to read and the length read, LENGTH={LEN} COUNT={COUNT}", + "LEN", length, "COUNT", rc); return PLDM_ERROR; } } catch (const std::exception& e) { - std::cerr << "GetPEL D-Bus call failed on PEL ID 0x" << std::hex - << fileHandle << ", error = " << e.what() << "\n"; + error( + "GetPEL D-Bus call failed on PEL ID 0x{FILE_HNDL}, error ={ERR_EXCEP}", + "FILE_HNDL", lg2::hex, fileHandle, "ERR_EXCEP", e.what()); return PLDM_ERROR; } return PLDM_SUCCESS; @@ -209,8 +218,8 @@ int PelHandler::writeFromMemory(uint32_t offset, uint32_t length, int fd = mkstemp(tmpFile); if (fd == -1) { - std::cerr << "failed to create a temporary pel, ERROR=" << errno - << "\n"; + error("failed to create a temporary pel, ERROR={ERR_EXCEP}", + "ERR_EXCEP", errno); FileHandler::dmaResponseToHost(responseHdr, PLDM_ERROR, 0); FileHandler::deleteAIOobjects(nullptr, responseHdr); return -1; @@ -241,26 +250,85 @@ int PelHandler::postDataTransferCallBack(bool IsWriteToMemOp) return PLDM_SUCCESS; } -int PelHandler::fileAck(uint8_t /*fileStatus*/) +int PelHandler::fileAck(uint8_t fileStatus) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; + static std::string service; auto& bus = pldm::utils::DBusHandler::getBus(); - try + if (service.empty()) { - auto service = pldm::utils::DBusHandler().getService(logObjPath, - logInterface); - auto method = bus.new_method_call(service.c_str(), logObjPath, - logInterface, "HostAck"); - method.append(fileHandle); - bus.call_noreply(method); + try + { + service = pldm::utils::DBusHandler().getService(logObjPath, + logInterface); + } + catch (const sdbusplus::exception_t& e) + { + error("Mapper call failed when trying to find logging service " + "to ack PEL ID {FILE_HANDLE} error = {ERR_EXCEP}", + "FILE_HANDLE", lg2::hex, fileHandle, "ERR_EXCEP", e); + return PLDM_ERROR; + } } - catch (const std::exception& e) + + if (fileStatus == PLDM_SUCCESS) { - std::cerr << "HostAck D-Bus call failed on PEL ID 0x" << std::hex - << fileHandle << ", error = " << e.what() << "\n"; - return PLDM_ERROR; + try + { + auto method = bus.new_method_call(service.c_str(), logObjPath, + logInterface, "HostAck"); + method.append(fileHandle); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); + } + catch (const std::exception& e) + { + error( + "HostAck D-Bus call failed on PEL ID {FILE_HANDLE}, error = {ERR_EXCEP}", + "FILE_HANDLE", lg2::hex, fileHandle, "ERR_EXCEP", e); + return PLDM_ERROR; + } + } + else + { + PEL::RejectionReason reason{}; + if (fileStatus == PLDM_FULL_FILE_DISCARDED) + { + reason = PEL::RejectionReason::HostFull; + } + else if (fileStatus == PLDM_ERROR_FILE_DISCARDED) + { + reason = PEL::RejectionReason::BadPEL; + } + else + { + error( + "Invalid file status {STATUS} in PEL file ack response for PEL {FILE_HANDLE}", + "STATUS", lg2::hex, fileStatus, "FILE_HANDLE", lg2::hex, + fileHandle); + return PLDM_ERROR; + } + + try + { + auto method = bus.new_method_call(service.c_str(), logObjPath, + logInterface, "HostReject"); + method.append(fileHandle, reason); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); + } + catch (const std::exception& e) + { + error("HostReject D-Bus call failed on PEL ID {FILE_HANDLE}, " + "error = {ERR_EXCEP}, status = {STATUS}", + "FILE_HANDLE", lg2::hex, fileHandle, "ERR_EXCEP", e, "STATUS", + lg2::hex, fileStatus); + return PLDM_ERROR; + } } return PLDM_SUCCESS; @@ -288,12 +356,14 @@ int PelHandler::storePel(std::string&& pelFileName) logInterface, "Create"); method.append("xyz.openbmc_project.Host.Error.Event", severity, addlData); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call to PEL daemon, ERROR=" - << e.what() << "\n"; + error("failed to make a d-bus call to PEL daemon, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } return PLDM_SUCCESS; @@ -306,7 +376,7 @@ int PelHandler::write(const char* buffer, uint32_t offset, uint32_t& length, if (offset > 0) { - std::cerr << "Offset is non zero \n"; + error("Offset is non zero"); return PLDM_ERROR; } @@ -314,8 +384,8 @@ int PelHandler::write(const char* buffer, uint32_t offset, uint32_t& length, auto fd = mkstemp(tmpFile); if (fd == -1) { - std::cerr << "failed to create a temporary pel, ERROR=" << errno - << "\n"; + error("failed to create a temporary pel, ERROR={ERR_EXCEP}", + "ERR_EXCEP", errno); return PLDM_ERROR; } @@ -333,8 +403,9 @@ int PelHandler::write(const char* buffer, uint32_t offset, uint32_t& length, if (rc == -1) { - std::cerr << "file write failed, ERROR=" << errno - << ", LENGTH=" << length << ", OFFSET=" << offset << "\n"; + error( + "file write failed, ERROR={ERR_EXCEP}, LENGTH={LEN}, OFFSET={OFFSET}", + "ERR_EXCEP", errno, "LEN", length, "ERR_EXCEP", offset); fs::remove(tmpFile); return PLDM_ERROR; } @@ -345,8 +416,8 @@ int PelHandler::write(const char* buffer, uint32_t offset, uint32_t& length, rc = storePel(path.string()); if (rc != PLDM_SUCCESS) { - std::cerr << "save PEL failed, ERROR = " << rc - << "tmpFile = " << tmpFile << "\n"; + error("save PEL failed, ERROR = {RC} tmpFile = {TMP_FILE}", "KEY0", + rc, "TMP_FILE", tmpFile); } } diff --git a/oem/ibm/libpldmresponder/file_io_type_progress_src.cpp b/oem/ibm/libpldmresponder/file_io_type_progress_src.cpp index 99aca372d..5de46031e 100644 --- a/oem/ibm/libpldmresponder/file_io_type_progress_src.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_progress_src.cpp @@ -2,12 +2,14 @@ #include "common/utils.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace responder { - int ProgressCodeHandler::setRawBootProperty( const std::tuple>& progressCodeBuffer) { @@ -31,12 +33,15 @@ int ProgressCodeHandler::setRawBootProperty( std::variant>>( progressCodeBuffer)); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call to host-postd daemon, ERROR=" - << e.what() << "\n"; + error( + "failed to make a d-bus call to host-postd daemon, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } diff --git a/oem/ibm/libpldmresponder/file_io_type_vpd.cpp b/oem/ibm/libpldmresponder/file_io_type_vpd.cpp index 8c3a460fa..6e6b1e9b3 100644 --- a/oem/ibm/libpldmresponder/file_io_type_vpd.cpp +++ b/oem/ibm/libpldmresponder/file_io_type_vpd.cpp @@ -7,8 +7,12 @@ #include +#include + #include +PHOSPHOR_LOG2_USING; + typedef uint8_t byte; namespace pldm @@ -34,21 +38,25 @@ int keywordHandler::read(uint32_t offset, uint32_t& length, Response& response, "org.freedesktop.DBus.Properties", "Get"); method.append(keywrdInterface, keywrdPropName); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(keywrd); } catch (const std::exception& e) { - std::cerr << "Get keyword error from dbus interface : " - << keywrdInterface << " ERROR= " << e.what() << std::endl; + error( + "Get keyword error from dbus interface : {INTF} ERROR= {ERR_EXCEP}", + "INTF", keywrdInterface, "ERR_EXCEP", e.what()); } auto keywrdSize = std::get>(keywrd).size(); if (length < keywrdSize) { - std::cerr << "length requested is less the keyword size, length: " - << length << " keyword size: " << keywrdSize << std::endl; + error( + "length requested is less the keyword size, length: {LEN} keyword size: {KEYWORD_SIZE}", + "LEN", length, "KEYWORD_SIZE", keywrdSize); return PLDM_ERROR_INVALID_DATA; } @@ -63,35 +71,48 @@ int keywordHandler::read(uint32_t offset, uint32_t& length, Response& response, fs::perms::others_read | fs::perms::owner_write); } - std::ofstream keywrdFile("vpdKeywrd.bin"); - keywrdFile.open(keywrdFilePath, std::ios::out | std::ofstream::binary); + std::ofstream keywrdFile(keywrdFilePath); + auto fd = open(keywrdFilePath, std::ios::out | std::ofstream::binary); if (!keywrdFile) { - std::cerr << "VPD keyword file open error: " << keywrdFilePath - << " errno: " << errno << std::endl; + error("VPD keyword file open error: {KEYWRD_PATH} errno: {ERR}", + "KEYWRD_PATH", keywrdFilePath, "ERR", errno); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.readKeywordHandler.keywordFileOpenError", pldm::PelSeverity::ERROR); return PLDM_ERROR; } + + if (offset > keywrdSize) + { + error("Offset exceeds file size, OFFSET={OFFSET} FILE_SIZE={FILE_SIZE}", + "OFFSET", offset, "FILE_SIZE", keywrdSize); + return PLDM_DATA_OUT_OF_RANGE; + } + // length of keyword data should be same as keyword data size in dbus object + length = static_cast(keywrdSize) - offset; + auto returnCode = lseek(fd, offset, SEEK_SET); + if (returnCode == -1) + { + error("Could not find keyword data at given offset. File Seek failed"); + return PLDM_ERROR; + } + keywrdFile.write((const char*)std::get>(keywrd).data(), keywrdSize); if (keywrdFile.bad()) { - std::cerr << "Error while writing to file: " << keywrdFilePath - << std::endl; + error("Error while writing to file: {KEYWRD_PATH}", "KEYWRD_PATH", + keywrdFilePath); } keywrdFile.close(); - // length of keyword data should be same as keyword data size in dbus object - length = (uint32_t)keywrdSize; - auto rc = readFile(keywrdFilePath, offset, keywrdSize, response); fs::remove(keywrdFilePath); if (rc) { - std::cerr << "Read error for keyword file with size: " << keywrdSize - << std::endl; + error("Read error for keyword file with size: {KEYWRD_SIZE}", + "KEYWRD_SIZE", keywrdSize); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.readKeywordHandler.keywordFileReadError", pldm::PelSeverity::ERROR); diff --git a/oem/ibm/libpldmresponder/file_table.cpp b/oem/ibm/libpldmresponder/file_table.cpp index 48388ee2e..38fc90ea6 100644 --- a/oem/ibm/libpldmresponder/file_table.cpp +++ b/oem/ibm/libpldmresponder/file_table.cpp @@ -2,30 +2,31 @@ #include "libpldm/utils.h" +#include + #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace filetable { - FileTable::FileTable(const std::string& fileTableConfigPath) { std::ifstream jsonFile(fileTableConfigPath); if (!jsonFile.is_open()) { - std::cerr << "File table config file does not exist, FILE=" - << fileTableConfigPath.c_str() << "\n"; + error("File table config file does not exist, FILE={FILE_TABLE_CONF}", + "FILE_TABLE_CONF", fileTableConfigPath.c_str()); return; } auto data = Json::parse(jsonFile, nullptr, false); if (data.is_discarded()) { - std::cerr << "Parsing config file failed" - << "\n"; + error("Parsing config file failed"); return; } diff --git a/oem/ibm/libpldmresponder/fru_oem_ibm.cpp b/oem/ibm/libpldmresponder/fru_oem_ibm.cpp index 9d0cd25c8..cead8850e 100644 --- a/oem/ibm/libpldmresponder/fru_oem_ibm.cpp +++ b/oem/ibm/libpldmresponder/fru_oem_ibm.cpp @@ -1,12 +1,15 @@ #include "fru_oem_ibm.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { namespace oem_ibm_fru { - void pldm::responder::oem_ibm_fru::Handler::setFruHandler( pldm::responder::fru::Handler* handler) { @@ -151,8 +154,8 @@ void Handler::dbus_map_update(const std::string& adapterObjPath, } catch (const std::exception& e) { - std::cerr << "Failed To set " << propertyName << "property" - << "ERROR=" << e.what() << std::endl; + error("Failed To set {PROP_NAME} property ERROR={ERR_EXCEP}", + "PROP_NAME", propertyName, "ERR_EXCEP", e.what()); } } @@ -170,15 +173,14 @@ void Handler::setFruPresence(const std::string& adapterObjPath) } catch (const std::exception& e) { - std::cerr << "Failed to set the present property" - << "ERROR=" << e.what() << std::endl; + error("Failed to set the present property ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } void Handler::setFirmwareUAK(std::vector data) { - std::cout << "Got a SetFRURecordTable cmd from host to set the firmware UAK" - << std::endl; + info("Got a SetFRURecordTable cmd from host to set the firmware UAK"); static constexpr auto uakObjPath = "/com/ibm/VPD/Manager"; static constexpr auto uakInterface = "com.ibm.VPD.Manager"; @@ -196,12 +198,14 @@ void Handler::setFirmwareUAK(std::vector data) uakInterface, "WriteKeyword"); method.append(static_cast(fruPath), fruRecord, fruKeyword, data); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "failed to make a DBus call to VPD manager, ERROR=" - << e.what() << "\n"; + error("failed to make a DBus call to VPD manager, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return; } } diff --git a/oem/ibm/libpldmresponder/inband_code_update.cpp b/oem/ibm/libpldmresponder/inband_code_update.cpp index 37bee93f6..ba67f51ef 100644 --- a/oem/ibm/libpldmresponder/inband_code_update.cpp +++ b/oem/ibm/libpldmresponder/inband_code_update.cpp @@ -8,11 +8,15 @@ #include +#include #include #include #include #include + +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace utils; @@ -63,7 +67,7 @@ int CodeUpdate::setCurrentBootSide(const std::string& currSide) int CodeUpdate::setNextBootSide(const std::string& nextSide) { - std::cout << "setNextBootSide, nextSide=" << nextSide << std::endl; + info("setNextBootSide, nextSide={NXT_SIDE}", "NXT_SIDE", nextSide); pldm_boot_side_data pldmBootSideData = readBootSideFile(); currBootSide = (pldmBootSideData.current_boot_side == "Perm" ? Pside : Tside); @@ -72,19 +76,19 @@ int CodeUpdate::setNextBootSide(const std::string& nextSide) std::string objPath{}; if (nextBootSide == currBootSide) { - std::cout << "Current bootside is same as next boot side,\n" - << "setting priority of running version 0" << std::endl; + info("Current bootside is same as next boot side"); + info("setting priority of running version 0"); objPath = runningVersion; } else { - std::cout << "Current bootside is not same as next boot side,\n" - << "setting priority of non running version 0" << std::endl; + info("Current bootside is not same as next boot side"); + info("setting priority of non running version 0"); objPath = nonRunningVersion; } if (objPath.empty()) { - std::cerr << "no nonRunningVersion present \n"; + error("no nonRunningVersion present"); return PLDM_PLATFORM_INVALID_STATE_VALUE; } @@ -115,8 +119,9 @@ int CodeUpdate::setNextBootSide(const std::string& nextSide) } catch (const std::exception& e) { - std::cerr << "failed to set the next boot side to " << objPath.c_str() - << " ERROR=" << e.what() << "\n"; + error( + "failed to set the next boot side to {OBJ_PATH} ERROR={ERR_EXCEP}", + "OBJ_PATH", objPath.c_str(), "ERR_EXCEP", e.what()); return PLDM_ERROR; } writeBootSideFile(pldmBootSideData); @@ -139,8 +144,8 @@ int CodeUpdate::setRequestedApplyTime() } catch (const std::exception& e) { - std::cerr << "Failed To set RequestedApplyTime property " - << "ERROR=" << e.what() << std::endl; + error("Failed To set RequestedApplyTime property ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); rc = PLDM_ERROR; } return rc; @@ -162,8 +167,8 @@ int CodeUpdate::setRequestedActivation() } catch (const std::exception& e) { - std::cerr << "Failed To set RequestedActivation property" - << "ERROR=" << e.what() << std::endl; + error("Failed To set RequestedActivation property ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); rc = PLDM_ERROR; } return rc; @@ -188,7 +193,9 @@ void CodeUpdate::setVersions() method.append("xyz.openbmc_project.Association", "endpoints"); std::variant> paths; - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(paths); runningVersion = std::get>(paths)[0]; @@ -200,7 +207,9 @@ void CodeUpdate::setVersions() propIntf, "Get"); method1.append("xyz.openbmc_project.Association", "endpoints"); - auto reply1 = bus.call(method1); + auto reply1 = bus.call( + method1, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply1.read(paths); for (const auto& path : std::get>(paths)) { @@ -230,13 +239,15 @@ void CodeUpdate::setVersions() else { pldm_boot_side_data pldmBootSideData = readBootSideFile(); + std::string runningVers; + runningVers = pldmBootSideData.running_version_object; if (pldmBootSideData.running_version_object != runningPath) { - std::cout << "BMC have booted with the new image runningPath=" - << runningPath << std::endl; - std::cout << "Previous Image was: " - << pldmBootSideData.running_version_object - << std::endl; + info( + "BMC have booted with the new image runningPath={RUNN_PATH}", + "RUNN_PATH", runningPath.c_str()); + info("Previous Image was: {RUNN_VERS}", "RUNN_VERS", + runningVers); auto current_boot_side = (pldmBootSideData.current_boot_side == "Temp" ? "Perm" : "Temp"); @@ -252,9 +263,9 @@ void CodeUpdate::setVersions() } else { - std::cout - << "BMC have booted with the previous image runningPath=" - << pldmBootSideData.running_version_object << std::endl; + info( + "BMC have booted with the previous image runningPath={RUNN_PATH}", + "RUNN_PATH", runningVers); pldm_boot_side_data pldmBootSideData = readBootSideFile(); pldmBootSideData.next_boot_side = pldmBootSideData.current_boot_side; @@ -273,9 +284,9 @@ void CodeUpdate::setVersions() } catch (const std::exception& e) { - std::cerr << "failed to make a d-bus call to Object Mapper " - "Association, ERROR=" - << e.what() << "\n"; + error( + "failed to make a d-bus call to Object Mapper Association, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); if (retrySetVersion < maxVersionRetry) { retrySetVersion++; @@ -324,20 +335,18 @@ void CodeUpdate::setVersions() try { - auto propVal = - pldm::utils::DBusHandler().getDbusPropertyVariant( - imageObjPath, "Activation", imageInterface); - const auto& activation = std::get(propVal); - - if (activation == - "xyz.openbmc_project.Software.Activation.Activations.Invalid") + if (isCodeUpdateInProgress()) { - if (isCodeUpdateInProgress()) + auto propVal = + pldm::utils::DBusHandler().getDbusPropertyVariant( + imageObjPath, "Activation", imageInterface); + const auto& activation = std::get(propVal); + + if (activation == + "xyz.openbmc_project.Software.Activation.Activations.Invalid") { - std::cerr - << "InbandCodeUpdate Failed: Received Invalid Signal, Sending " - << "Error on End update sensor event " - << "to PHYP\n"; + error( + "InbandCodeUpdate Failed: Received Invalid Signal, Sending Error on End update sensor event to PHYP"); setCodeUpdateProgress(false); auto sensorId = getFirmwareUpdateSensor(); sendStateSensorEvent( @@ -350,12 +359,10 @@ void CodeUpdate::setVersions() } catch (const std::exception& e) { - std::cerr - << "Code Update: Error getting Activation property, PATH=" - << imageObjPath << "INTERFACE=" << imageInterface - << "PROPERTY=" - << "Activation" - << "ERROR=" << e.what() << "\n"; + error( + "Code Update: Error getting Activation property, PATH={PATH} INTERFACE={INTF} PROPERTY = Activation ERROR={ERR_EXCEP}", + "PATH", imageObjPath, "INTF", imageInterface, + "ERR_EXCEP", e.what()); } try { @@ -363,7 +370,7 @@ void CodeUpdate::setVersions() if (isCodeUpdateInProgress()) { - std::cout << "Inband Code update is InProgress\n"; + info("Inband Code update is InProgress"); // Inband update newImageId = path.str; if (!imageActivationMatch) @@ -387,10 +394,8 @@ void CodeUpdate::setVersions() "xyz.openbmc_project.Software." "Activation.Activations.Active") { - std::cout - << "Received Active signal, Sending " - << "success on End update sensor event " - << "to PHYP\n"; + info( + "Received Active signal, Sending success on End update sensor event to PHYP"); CodeUpdateState state = CodeUpdateState::END; setCodeUpdateProgress(false); @@ -412,10 +417,8 @@ void CodeUpdate::setVersions() "Activations." "Invalid") { - std::cout - << "Image activation Failed or image " - << "Invalid, sending Failure on End " - << "update to PHYP\n"; + info( + "Image activation Failed or image Invalid, sending Failure on End update to PHYP"); CodeUpdateState state = CodeUpdateState::FAIL; setCodeUpdateProgress(false); @@ -441,7 +444,7 @@ void CodeUpdate::setVersions() sensorId, PLDM_STATE_SENSOR_STATE, 0, uint8_t(state), uint8_t(CodeUpdateState::START)); - std::cerr << "could not set RequestedActivation \n"; + error("could not set RequestedActivation"); } break; } @@ -453,10 +456,10 @@ void CodeUpdate::setVersions() } catch (const sdbusplus::exception::exception& e) { - std::cerr << "Error in getting Activation status," - << "ERROR=" << e.what() - << ", INTERFACE=" << imageInterface - << ", OBJECT PATH=" << imageObjPath << "\n"; + error( + "Error in getting Activation status, ERROR={ERR_EXCEP}, INTERFACE={INTF}, OBJECT PATH={OBJ_PATH}", + "ERR_EXCEP", e.what(), "INTF", imageInterface, + "OBJ_PATH", imageObjPath); } } } @@ -465,7 +468,7 @@ void CodeUpdate::setVersions() void CodeUpdate::processRenameEvent() { - std::cout << "Processing Rename Event" << std::endl; + info("Processing Rename Event"); BiosAttributeList biosAttrList; pldm_boot_side_data pldmBootSideData = readBootSideFile(); @@ -592,11 +595,14 @@ void CodeUpdate::deleteImage() { auto method = bus.new_method_call(UPDATER_SERVICE, SW_OBJ_PATH, DELETE_INTF, "DeleteAll"); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "Failed to delete image, ERROR=" << e.what() << "\n"; + error("Failed to delete image, ERROR={ERR_EXCEP}", "ERR_EXCEP", + e.what()); return; } } @@ -691,7 +697,8 @@ int processCodeUpdateLid(const std::string& filePath) std::ifstream ifs(filePath, std::ios::in | std::ios::binary); if (!ifs) { - std::cerr << "ifstream open error: " << filePath << "\n"; + error("ifstream open error: {FILE_PATH}", "FILE_PATH", + filePath.c_str()); return PLDM_ERROR; } ifs.seekg(0); @@ -710,7 +717,8 @@ int processCodeUpdateLid(const std::string& filePath) constexpr auto magicNumber = 0x0222; if (htons(header.magicNumber) != magicNumber) { - std::cerr << "Invalid magic number: " << filePath << "\n"; + error("Invalid magic number: {FILE_PATH}", "FILE_PATH", + filePath.c_str()); ifs.close(); return PLDM_ERROR; } @@ -729,8 +737,8 @@ int processCodeUpdateLid(const std::string& filePath) ec); if (ec) { - std::cerr << "Failed to set the lid directory permissions: " - << ec.message() << std::endl; + error("Failed to set the lid directory permissions:{ERR}", "ERR", + ec.message()); return PLDM_ERROR; } } @@ -765,8 +773,8 @@ int processCodeUpdateLid(const std::string& filePath) fs::perm_options::replace, ec); if (ec) { - std::cerr << "Failed to set the lid file permissions: " - << ec.message() << std::endl; + error("Failed to set the lid file permissions: {ERR}", "ERR", + ec.message()); return PLDM_ERROR; } } @@ -787,17 +795,19 @@ int CodeUpdate::assembleCodeUpdateImage() try { - std::cout << "InbandCodeUpdate: AssembleCodeUpdateImage \n"; + info("InbandCodeUpdate: AssembleCodeUpdateImage"); auto method = bus.new_method_call(UPDATER_SERVICE, SOFTWARE_PATH, LID_INTERFACE, "AssembleCodeUpdateImage"); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr - << "InbandCodeUpdate: Failed to Assemble code update image ERROR=" - << e.what() << "\n"; + error( + "InbandCodeUpdate: Failed to Assemble code update image ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); setCodeUpdateProgress(false); auto sensorId = getFirmwareUpdateSensor(); sendStateSensorEvent(sensorId, PLDM_STATE_SENSOR_STATE, 0, diff --git a/oem/ibm/libpldmresponder/oem_ibm_handler.cpp b/oem/ibm/libpldmresponder/oem_ibm_handler.cpp index e8bd2ef07..62675e60d 100644 --- a/oem/ibm/libpldmresponder/oem_ibm_handler.cpp +++ b/oem/ibm/libpldmresponder/oem_ibm_handler.cpp @@ -8,8 +8,12 @@ #include "libpldmresponder/file_io.hpp" #include "libpldmresponder/pdr_utils.hpp" +#include + #include +PHOSPHOR_LOG2_USING; + using namespace pldm::pdr; using namespace pldm::utils; @@ -139,7 +143,7 @@ int pldm::responder::oem_ibm_platform::Handler:: if (stateField[currState].effecter_state == uint8_t(CodeUpdateState::START)) { - std::cout << "Received Start Update Request From PHYP\n"; + info("Received Start Update Request From PHYP"); codeUpdate->setCodeUpdateProgress(true); startUpdateEvent = std::make_unique( @@ -151,7 +155,7 @@ int pldm::responder::oem_ibm_platform::Handler:: else if (stateField[currState].effecter_state == uint8_t(CodeUpdateState::END)) { - std::cout << "Received End Update Request From PHYP\n"; + info("Received End Update Request From PHYP"); rc = PLDM_SUCCESS; assembleImageEvent = std::make_unique< sdeventplus::source::Defer>( @@ -166,7 +170,7 @@ int pldm::responder::oem_ibm_platform::Handler:: else if (stateField[currState].effecter_state == uint8_t(CodeUpdateState::ABORT)) { - std::cout << "Received Abort Update Request From PHYP\n"; + info("Received Abort Update Request From PHYP"); codeUpdate->setCodeUpdateProgress(false); codeUpdate->clearDirPath(LID_STAGING_DIR); auto sensorId = codeUpdate->getFirmwareUpdateSensor(); @@ -201,7 +205,7 @@ int pldm::responder::oem_ibm_platform::Handler:: { if (stateField[currState].effecter_state == POWER_CYCLE_HARD) { - std::cout << "Got a Deep IPL request" << std::endl; + info("Got a Deep IPL request"); systemRebootEvent = std::make_unique( event, @@ -274,8 +278,8 @@ void buildAllCodeUpdateEffecterPDR(oem_ibm_platform::Handler* platformHandler, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_EFFECTER_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_EFFECTER_ID)); return; } pdr->hdr.record_handle = 0; @@ -325,8 +329,8 @@ void buildAllSlotEnabeEffecterPDR(oem_ibm_platform::Handler* platformHandler, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_EFFECTER_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_EFFECTER_ID)); return; } @@ -391,8 +395,8 @@ void buildAllCodeUpdateSensorPDR(oem_ibm_platform::Handler* platformHandler, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_SENSOR_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_SENSOR_ID)); return; } pdr->hdr.record_handle = 0; @@ -440,8 +444,8 @@ void buildAllSlotEnableSensorPDR(oem_ibm_platform::Handler* platformHandler, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_SENSOR_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_SENSOR_ID)); return; } auto& associatedEntityMap = platformHandler->getAssociateEntityMap(); @@ -502,8 +506,8 @@ void buildAllNumericEffecterPDR(oem_ibm_platform::Handler* platformHandler, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_EFFECTER_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_EFFECTER_ID)); return; } @@ -582,8 +586,8 @@ void buildAllSystemPowerStateEffecterPDR( reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_EFFECTER_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_EFFECTER_ID)); return; } pdr->hdr.record_handle = 0; @@ -647,8 +651,9 @@ void attachOemEntityToEntityAssociationPDR( { // parent node not found in the entity association tree, // this should not be possible - std::cerr << "Parent Entity of type " << parent_entity.entity_type - << " not found in the BMC Entity Association tree\n"; + error( + "Parent Entity of type {ENTITY_TYP} not found in the BMC Entity Association tree ", + "ENTITY_TYP", static_cast(parent_entity.entity_type)); return; } uint32_t bmc_record_handle = 0; @@ -698,14 +703,18 @@ std::filesystem::path pldm::responder::oem_ibm_platform::Handler::getConfigDir() serviceMap[0].first.c_str(), objectPath.c_str(), orgFreeDesktopInterface, getMethod); method.append(ibmCompatible[0].c_str(), namesProperty); - auto reply = bus.call(method); + auto reply = bus.call( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); reply.read(value); return fs::path{std::get>(value)[0]}; } catch (const std::exception& e) { - std::cerr << "Error getting Names property , PATH=" << objectPath - << " Compatible interface =" << ibmCompatible[0] << "\n"; + error( + "Error getting Names property , PATH={OBJ_PATH} Compatible interface = {INTF}", + "OBJ_PATH", objectPath.c_str(), "INTF", + ibmCompatible[0].c_str()); } } return fs::path(); @@ -725,8 +734,8 @@ void buildAllRealSAIEffecterPDR(oem_ibm_platform::Handler* platformHandler, reinterpret_cast(entry.data()); if (!pdr) { - std::cerr << "Failed to get record by PDR type, ERROR:" - << PLDM_PLATFORM_INVALID_EFFECTER_ID << std::endl; + error("Failed to get record by PDR type, ERROR:{ERR}", "ERR", lg2::hex, + static_cast(PLDM_PLATFORM_INVALID_EFFECTER_ID)); return; } pdr->hdr.record_handle = 0; @@ -844,10 +853,9 @@ int pldm::responder::oem_ibm_platform::Handler::sendEventToHost( &completionCode, &status); if (rc || completionCode) { - std::cerr << "Failed to decode_platform_event_message_resp: " - << " for code update event rc=" << rc - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_platform_event_message_resp: for code update event rc={RC}, cc={CC}", + "RC", rc, "CC", static_cast(completionCode)); } }; auto rc = handler->registerRequest( @@ -856,7 +864,7 @@ int pldm::responder::oem_ibm_platform::Handler::sendEventToHost( std::move(oemPlatformEventMessageResponseHandler)); if (rc) { - std::cerr << "Failed to send BIOS attribute change event message \n"; + error("Failed to send BIOS attribute change event message"); } return rc; @@ -915,9 +923,9 @@ void pldm::responder::oem_ibm_platform::Handler::setHostEffecterState( request); if (rc != PLDM_SUCCESS) { - std::cerr - << " Set state effecter state command failure. PLDM error code =" - << rc << std::endl; + error( + " Set state effecter state command failure. PLDM error code ={RC}", + "RC", rc); requester.markFree(mctp_eid, instanceId); return; } @@ -926,8 +934,8 @@ void pldm::responder::oem_ibm_platform::Handler::setHostEffecterState( size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for " - << "setstateEffecterSates command\n"; + error( + "Failed to receive response for setstateEffecterSates command"); return; } uint8_t completionCode{}; @@ -935,17 +943,17 @@ void pldm::responder::oem_ibm_platform::Handler::setHostEffecterState( response, respMsgLen, &completionCode); if (rc) { - std::cerr << "Failed to decode setStateEffecterStates response," - << " rc " << rc << "\n"; + error( + "Failed to decode setStateEffecterStates response,rc= {RC}", + "RC", static_cast(rc)); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SetHostEffecterFailed", pldm::PelSeverity::ERROR); } if (completionCode) { - std::cerr << "Failed to set a Host effecter " - << ", cc=" << static_cast(completionCode) - << "\n"; + error("Failed to set a Host effecter, cc={CC}", "CC", + static_cast(completionCode)); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SetHostEffecterFailed", pldm::PelSeverity::ERROR); @@ -957,7 +965,7 @@ void pldm::responder::oem_ibm_platform::Handler::setHostEffecterState( std::move(setStateEffecterStatesRespHandler)); if (rc) { - std::cerr << "Failed to send request to set an effecter on Host \n"; + error("Failed to send request to set an effecter on Host"); } } } @@ -1021,7 +1029,9 @@ int pldm::responder::oem_ibm_platform::Handler::setNumericEffecter( (uint64_t)entityInstance; method.append(createParams); - auto response = bus.call(method); + auto response = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); sdbusplus::message::object_path reply; response.read(reply); @@ -1030,9 +1040,9 @@ int pldm::responder::oem_ibm_platform::Handler::setNumericEffecter( } catch (const std::exception& e) { - std::cerr - << "Failed to make a DBus call as the dump policy is disabled,ERROR= " - << e.what() << "\n"; + error( + "Failed to make a DBus call as the dump policy is disabled,ERROR= {ERR_EXCEP}", + "ERR_EXCEP", e.what()); // case when the dump policy is disabled but we set the host effecter as // true and the host moves on setHostEffecterState(true); @@ -1082,16 +1092,14 @@ void pldm::responder::oem_ibm_platform::Handler::sendStateSensorEvent( instanceId); if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to encode state sensor event, rc = " << rc - << std::endl; + error("Failed to encode state sensor event, rc = {RC}", "RC", rc); requester.markFree(mctp_eid, instanceId); return; } rc = sendEventToHost(requestMsg, instanceId); if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to send event to host: " - << "rc=" << rc << std::endl; + error("Failed to send event to host: rc={RC}", "RC", rc); } return; } @@ -1100,7 +1108,7 @@ void pldm::responder::oem_ibm_platform::Handler::_processEndUpdate( sdeventplus::source::EventBase& /*source */) { assembleImageEvent.reset(); - std::cout << "Starting assembleCodeUpdateImage \n"; + info("Starting assembleCodeUpdateImage"); int retc = codeUpdate->assembleCodeUpdateImage(); if (retc != PLDM_SUCCESS) { @@ -1120,11 +1128,11 @@ void pldm::responder::oem_ibm_platform::Handler::_processStartUpdate( auto rc = codeUpdate->setRequestedApplyTime(); if (rc != PLDM_SUCCESS) { - std::cerr << "setRequestedApplyTime failed \n"; + error("setRequestedApplyTime failed"); state = CodeUpdateState::FAIL; } auto sensorId = codeUpdate->getFirmwareUpdateSensor(); - std::cout << "Sending Start Update sensor event to PHYP\n"; + info("Sending Start Update sensor event to PHYP"); sendStateSensorEvent(sensorId, PLDM_STATE_SENSOR_STATE, 0, uint8_t(state), uint8_t(CodeUpdateState::END)); } @@ -1164,14 +1172,14 @@ void pldm::responder::oem_ibm_platform::Handler::_processSystemReboot( "RequestedPowerTransition", "string"}; try { - std::cout << "InbandCodeUpdate: ChassifOff the host\n"; + info("InbandCodeUpdate: ChassifOff the host"); dBusIntf->setDbusProperty(dbusMapping, value); } catch (const std::exception& e) { - std::cerr << "Chassis State transition to Off failed," - << "unable to set property RequestedPowerTransition" - << "ERROR=" << e.what() << "\n"; + error( + "Chassis State transition to Off failed, unable to set property RequestedPowerTransition ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } using namespace sdbusplus::bus::match::rules; @@ -1199,15 +1207,14 @@ void pldm::responder::oem_ibm_platform::Handler::_processSystemReboot( "Policy.AlwaysOn"; try { - std::cout - << "InbandCodeUpdate: Setting the one time APR policy\n"; + info("InbandCodeUpdate: Setting the one time APR policy"); dBusIntf->setDbusProperty(dbusMapping, value); } catch (const std::exception& e) { - std::cerr << "Setting one-time restore policy failed," - << "unable to set property PowerRestorePolicy" - << "ERROR=" << e.what() << "\n"; + error( + "Setting one-time restore policy failed, unable to set property PowerRestorePolicy ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } dbusMapping = pldm::utils::DBusMapping{ "/xyz/openbmc_project/state/bmc0", @@ -1216,15 +1223,14 @@ void pldm::responder::oem_ibm_platform::Handler::_processSystemReboot( value = "xyz.openbmc_project.State.BMC.Transition.Reboot"; try { - std::cout << "InbandCodeUpdate: Rebooting the BMC\n"; + info("InbandCodeUpdate: Rebooting the BMC"); dBusIntf->setDbusProperty(dbusMapping, value); } catch (const std::exception& e) { - std::cerr << "BMC state transition to reboot failed," - << "unable to set property " - "RequestedBMCTransition" - << "ERROR=" << e.what() << "\n"; + error( + "BMC state transition to reboot failed, unable to set property RequestedBMCTransition ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } } @@ -1282,12 +1288,15 @@ void pldm::responder::oem_ibm_platform::Handler::resetWatchDogTimer() bus.new_method_call(watchDogService, watchDogObjectPath, watchDogInterface, watchDogResetPropName); resetMethod.append(true); - bus.call_noreply(resetMethod); + bus.call_noreply( + resetMethod, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "Failed To reset watchdog timer" - << "ERROR=" << e.what() << std::endl; + error("Failed To reset watchdog timer ERROR={ERR_EXCEP}", "ERR_EXCEP", + e.what()); + return; } } @@ -1310,8 +1319,8 @@ void pldm::responder::oem_ibm_platform::Handler::disableWatchDogTimer() } catch (const std::exception& e) { - std::cerr << "Failed To disable watchdog timer" - << "ERROR=" << e.what() << "\n"; + error("Failed To disable watchdog timer ERROR={ERR_EXCEP}", "ERR_EXCEP", + e.what()); } } int pldm::responder::oem_ibm_platform::Handler::checkBMCState() @@ -1326,14 +1335,14 @@ int pldm::responder::oem_ibm_platform::Handler::checkBMCState() if (std::get(propertyValue) != "xyz.openbmc_project.State.BMC.BMCState.Ready") { - std::cerr << "GetPDR : PLDM stack is not ready for PDR exchange" - << std::endl; + error("GetPDR : PLDM stack is not ready for PDR exchange"); + return PLDM_ERROR_NOT_READY; } } catch (const std::exception& e) { - std::cerr << "Error getting the current BMC state" << std::endl; + error("Error getting the current BMC state"); return PLDM_ERROR; } return PLDM_SUCCESS; @@ -1350,12 +1359,15 @@ void pldm::responder::oem_ibm_platform::Handler::setBitmapMethodCall( dbusMethod); auto val = std::get_if>(&value); method.append(*val); - bus.call_noreply(method); + bus.call_noreply( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); } catch (const std::exception& e) { - std::cerr << "Failed to call the D-Bus Method" - << "ERROR=" << e.what() << std::endl; + error("Failed to call the D-Bus Method ERROR={ERR_EXCEP}", "ERR_EXCEP", + e.what()); + return; } } @@ -1448,8 +1460,8 @@ void pldm::responder::oem_ibm_platform::Handler::handleBootTypesAtChassisOff() auto bootType = getBiosAttrValue("pvm_boot_type"); if (bootInitiator.empty() || bootType.empty()) { - std::cerr - << "ERROR in fetching the pvm_boot_initiator and pvm_boot_type BIOS attribute values\n"; + error( + "ERROR in fetching the pvm_boot_initiator and pvm_boot_type BIOS attribute values"); return; } else if (bootInitiator != "Host") @@ -1471,8 +1483,8 @@ void pldm::responder::oem_ibm_platform::Handler::turnOffRealSAIEffecter() } catch (const std::exception& e) { - std::cerr << "Failed to turn off partition SAI effecter" - << "ERROR=" << e.what() << "\n"; + error("Failed to turn off partition SAI effecter ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } try { @@ -1483,8 +1495,8 @@ void pldm::responder::oem_ibm_platform::Handler::turnOffRealSAIEffecter() } catch (const std::exception& e) { - std::cerr << "Failed to turn off platform SAI effecter" - << "ERROR=" << e.what() << "\n"; + error("Failed to turn off platform SAI effecter ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -1513,8 +1525,8 @@ uint8_t pldm::responder::oem_ibm_platform::Handler::fetchRealSAIStatus() } catch (const std::exception& e) { - std::cerr << "Failed to fetch Real SAI sensor status" - << "ERROR=" << e.what() << "\n"; + error("Failed to fetch Real SAI sensor status ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } return PLDM_SENSOR_NORMAL; } @@ -1522,7 +1534,7 @@ uint8_t pldm::responder::oem_ibm_platform::Handler::fetchRealSAIStatus() void pldm::responder::oem_ibm_platform::Handler:: processPowerCycleOffSoftGraceful() { - std::cerr << "Received soft graceful power cycle request" << std::endl; + error("Received soft graceful power cycle request"); pldm::utils::PropertyValue value = "xyz.openbmc_project.State.Host.Transition.ForceWarmReboot"; pldm::utils::DBusMapping dbusMapping{"/xyz/openbmc_project/state/host0", @@ -1534,15 +1546,15 @@ void pldm::responder::oem_ibm_platform::Handler:: } catch (const std::exception& e) { - std::cerr - << "Error to do a ForceWarmReboot, chassis power remains on, and boot the host back up. Unable to set property RequestedHostTransition. ERROR=" - << e.what() << "\n"; + error( + "Error to do a ForceWarmReboot, chassis power remains on, and boot the host back up. Unable to set property RequestedHostTransition. ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } void pldm::responder::oem_ibm_platform::Handler::processPowerOffSoftGraceful() { - std::cerr << "Received soft power off graceful request" << std::endl; + error("Received soft power off graceful request"); pldm::utils::PropertyValue value = "xyz.openbmc_project.State.Chassis.Transition.Off"; pldm::utils::DBusMapping dbusMapping{"/xyz/openbmc_project/state/chassis0", @@ -1554,15 +1566,15 @@ void pldm::responder::oem_ibm_platform::Handler::processPowerOffSoftGraceful() } catch (const std::exception& e) { - std::cerr - << "Error in powering down the host. Unable to set property RequestedPowerTransition. ERROR=" - << e.what() << "\n"; + error( + "Error in powering down the host. Unable to set property RequestedPowerTransition. ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } void pldm::responder::oem_ibm_platform::Handler::processPowerOffHardGraceful() { - std::cerr << "Received hard power off graceful request" << std::endl; + error("Received hard power off graceful request"); pldm::utils::PropertyValue value = "xyz.openbmc_project.Control.Power.RestorePolicy.Policy.AlwaysOn"; pldm::utils::DBusMapping dbusMapping{ @@ -1571,13 +1583,22 @@ void pldm::responder::oem_ibm_platform::Handler::processPowerOffHardGraceful() "string"}; try { - dBusIntf->setDbusProperty(dbusMapping, value); + auto customerPolicy = + pldm::utils::DBusHandler().getDbusProperty( + "/xyz/openbmc_project/control/host0/power_restore_policy", + "PowerRestorePolicy", + "xyz.openbmc_project.Control.Power.RestorePolicy"); + if (customerPolicy != + "xyz.openbmc_project.Control.Power.RestorePolicy.Policy.AlwaysOff") + { + dBusIntf->setDbusProperty(dbusMapping, value); + } } catch (const std::exception& e) { - std::cerr - << "Setting one-time restore policy failed, Unable to set property PowerRestorePolicy. ERROR=" - << e.what() << "\n"; + error( + "Setting one-time restore policy failed, Unable to set property PowerRestorePolicy. ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } processPowerOffSoftGraceful(); } @@ -1613,9 +1634,10 @@ void pldm::responder::oem_ibm_platform::Handler::setSurvTimer(uint8_t tid, } else if (!value && timer.isEnabled()) { - std::cout << "setSurvTimer:LogginPel:hostOff=" << (bool)hostOff - << " hostTransitioningToOff=" << (bool)hostTransitioningToOff - << " tid=" << (uint16_t)tid << std::endl; + info( + "setSurvTimer:LogginPel:hostOff={HOST_OFF} hostTransitioningToOff={HOST_TRANST_OFF} tid={TID}", + "HOST_OFF", (bool)hostOff, "HOST_TRANST_OFF", + (bool)hostTransitioningToOff, "TID", (uint16_t)tid); startStopTimer(false); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.setSurvTimer.RecvSurveillancePingFail", @@ -1626,7 +1648,8 @@ void pldm::responder::oem_ibm_platform::Handler::setSurvTimer(uint8_t tid, void pldm::responder::oem_ibm_platform::Handler::propertyChanged( const DbusChangedProps& chProperties, std::string objPath) { - std::cerr << "Got a link reset set for CEC path: " << objPath << std::endl; + error("Got a link reset set for CEC path: {OBJ_PATH}", "OBJ_PATH", + objPath.c_str()); static constexpr auto propName = "linkReset"; const auto it = chProperties.find(propName); if (it == chProperties.end()) @@ -1685,9 +1708,9 @@ void pldm::responder::oem_ibm_platform::Handler::triggerHostEffecter( if (stateEffecterPDRs.empty()) { - std::cerr - << "PCIe CEC LinkReset: The state set PDR can not be found, entityType = " - << entityType << std::endl; + error( + "PCIe CEC LinkReset: The state set PDR can not be found, entityType = {ENTITY_TYP}", + "ENTITY_TYP", entityType); return; } @@ -1703,8 +1726,9 @@ void pldm::responder::oem_ibm_platform::Handler::triggerHostEffecter( } catch (const std::exception& e) { - std::cerr << "Failed to fetch the BusID of the slot. ERROR= " - << e.what() << std::endl; + error("Failed to fetch the BusID of the slot. ERROR= {ERR_EXCEP}", + "ERR_EXCEP", e.what()); + return; } @@ -1718,13 +1742,14 @@ void pldm::responder::oem_ibm_platform::Handler::triggerHostEffecter( } } - std::cerr << "Sending effecter call to host with effecter ID : " - << effecterID << "and BusID : " << instanceId << std::endl; + error( + "Sending effecter call to host with effecter ID : {EFFECTER_ID} and BusID : {BUS_ID}", + "EFFECTER_ID", effecterID, "BUS_ID", instanceId); hostEffecterParser->sendSetStateEffecterStates( mctp_eid, effecterID, 1, stateField, nullptr, value); - - std::cerr << "Setting link reset on link: " << path - << " is successful setting it back to false" << std::endl; + error( + "Setting link reset on link: {LINK_PATH} is successful setting it back to false", + "LINK_PATH", path.c_str()); pldm::utils::DBusMapping dbusMapping; dbusMapping.objectPath = path; dbusMapping.interface = "com.ibm.Control.Host.PCIeLink"; @@ -1737,8 +1762,8 @@ void pldm::responder::oem_ibm_platform::Handler::triggerHostEffecter( } catch (const std::exception& e) { - std::cerr << "Failed to set the link reset property. ERROR = " - << e.what() << std::endl; + error("Failed to set the link reset property. ERROR = {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return; } } diff --git a/oem/ibm/libpldmresponder/platform_oem_ibm.cpp b/oem/ibm/libpldmresponder/platform_oem_ibm.cpp index e034a01df..298b7a62f 100644 --- a/oem/ibm/libpldmresponder/platform_oem_ibm.cpp +++ b/oem/ibm/libpldmresponder/platform_oem_ibm.cpp @@ -6,17 +6,19 @@ #include "common/utils.hpp" #include "libpldmresponder/pdr.hpp" +#include #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { namespace responder { namespace platform { - int sendBiosAttributeUpdateEvent( uint8_t eid, dbus_api::Requester* requester, const std::vector& handles, @@ -36,8 +38,6 @@ int sendBiosAttributeUpdateEvent( "ProgressStages.SystemInitComplete") && (currHostState != "xyz.openbmc_project.State.Boot.Progress." "ProgressStages.OSRunning") && - (currHostState != "xyz.openbmc_project.State.Boot.Progress." - "ProgressStages.OSStart") && (currHostState != "xyz.openbmc_project.State.Boot.Progress." "ProgressStages.SystemSetup")) { @@ -68,8 +68,8 @@ int sendBiosAttributeUpdateEvent( requestMsg.size() - sizeof(pldm_msg_hdr), request); if (rc != PLDM_SUCCESS) { - std::cerr << "Message encode failure 1. PLDM error code = " << std::hex - << std::showbase << rc << "\n"; + error("Message encode failure 1. PLDM error code = {RC}", "RC", + lg2::hex, rc); requester->markFree(eid, instanceId); return rc; } @@ -89,8 +89,7 @@ int sendBiosAttributeUpdateEvent( [](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr - << "Failed to receive response for platform event message \n"; + error("Failed to receive response for platform event message"); return; } uint8_t completionCode{}; @@ -99,10 +98,9 @@ int sendBiosAttributeUpdateEvent( &completionCode, &status); if (rc || completionCode) { - std::cerr << "Failed to decode_platform_event_message_resp: " - << "rc=" << rc - << ", cc=" << static_cast(completionCode) - << std::endl; + error( + "Failed to decode_platform_event_message_resp: RC = {RC}, cc = {CC}", + "RC", rc, "CC", static_cast(completionCode)); } }; rc = handler->registerRequest( @@ -110,7 +108,7 @@ int sendBiosAttributeUpdateEvent( std::move(requestMsg), std::move(platformEventMessageResponseHandler)); if (rc) { - std::cerr << "Failed to send the platform event message \n"; + error("Failed to send the platform event message"); } return rc; diff --git a/oem/ibm/libpldmresponder/utils.cpp b/oem/ibm/libpldmresponder/utils.cpp index 3e0ab4ee0..aa1d4013c 100644 --- a/oem/ibm/libpldmresponder/utils.cpp +++ b/oem/ibm/libpldmresponder/utils.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -18,12 +19,13 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { using namespace pldm::dbus; namespace responder { - std::mutex lockMutex; namespace utils @@ -58,7 +60,7 @@ int setupUnixSocket(const std::string& socketInterface) if (strnlen(socketInterface.c_str(), sizeof(addr.sun_path)) == sizeof(addr.sun_path)) { - std::cerr << "setupUnixSocket: UNIX socket path too long" << std::endl; + error("setupUnixSocket: UNIX socket path too long"); return -1; } @@ -66,21 +68,21 @@ int setupUnixSocket(const std::string& socketInterface) if ((sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) == -1) { - std::cerr << "setupUnixSocket: socket() call failed" << std::endl; + error("setupUnixSocket: socket() call failed"); return -1; } if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) { - std::cerr << "setupUnixSocket: bind() call failed with errno " << errno - << std::endl; + error("setupUnixSocket: bind() call failed with errno {ERR}", "ERR", + errno); close(sock); return -1; } if (listen(sock, 1) == -1) { - std::cerr << "setupUnixSocket: listen() call failed" << std::endl; + error("setupUnixSocket: listen() call failed"); close(sock); return -1; } @@ -98,8 +100,7 @@ int setupUnixSocket(const std::string& socketInterface) int retval = select(nfd, &rfd, NULL, NULL, &tv); if (retval < 0) { - std::cerr << "setupUnixSocket: select call failed " << errno - << std::endl; + error("setupUnixSocket: select call failed {ERR}", "ERR", errno); close(sock); return -1; } @@ -109,8 +110,7 @@ int setupUnixSocket(const std::string& socketInterface) fd = accept(sock, NULL, NULL); if (fd < 0) { - std::cerr << "setupUnixSocket: accept() call failed " << errno - << std::endl; + error("setupUnixSocket: accept() call failed {ERR}", "ERR", errno); close(sock); return -1; } @@ -139,8 +139,7 @@ int writeToUnixSocket(const int sock, const char* buf, const uint64_t blockSize) int retval = select(nfd, NULL, &wfd, NULL, &tv); if (retval < 0) { - std::cerr << "writeToUnixSocket: select call failed " << errno - << std::endl; + error("writeToUnixSocket: select call failed {ERR}", "ERR", errno); close(sock); return -1; } @@ -156,14 +155,12 @@ int writeToUnixSocket(const int sock, const char* buf, const uint64_t blockSize) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - std::cerr << "writeToUnixSocket: Write call failed with " - "EAGAIN or EWOULDBLOCK or EINTR" - << std::endl; + error( + "writeToUnixSocket: Write call failed with EAGAIN or EWOULDBLOCK or EINTR"); nwrite = 0; continue; } - std::cerr << "writeToUnixSocket: Failed to write " << errno - << std::endl; + error("writeToUnixSocket: Failed to write {ERR}", "ERR", errno); close(sock); return -1; } @@ -432,12 +429,15 @@ void findPortObjects(const std::string& cardObjPath, method.append(cardObjPath); method.append(0); method.append(std::vector({portInterface})); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(portObjects); } catch (const std::exception& e) { - std::cerr << "no ports under card " << cardObjPath << "\n"; + error("no ports under card {CARD_OBJ_PATH}", "CARD_OBJ_PATH", + cardObjPath.c_str()); } } @@ -511,8 +511,8 @@ std::string getObjectPathByLocationCode(const std::string& locationCode, } catch (const std::exception& e) { - std::cerr << "Look up of inventory objects failed for location " - << locationCode << std::endl; + error("Look up of inventory objects failed for location {LOC_CODE}", + "LOC_CODE", locationCode); return path; } @@ -534,8 +534,8 @@ std::string getObjectPathByLocationCode(const std::string& locationCode, } } } - std::cerr << "Location not found " << locationCode << " for Item type " - << inventoryItemType << std::endl; + error("Location not found {LOC_CODE} for Item type {INVEN_ITEM_TYP}", + "LOC_CODE", locationCode, "INVEN_ITEM_TYP", inventoryItemType); return path; } @@ -562,12 +562,15 @@ void findSlotObjects(const std::string& boardObjPath, method.append(boardObjPath); method.append(0); method.append(std::vector({slotInterface})); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(slotObjects); } catch (const std::exception& e) { - std::cerr << "no cec slots under motherboard" << boardObjPath << "\n"; + error("no cec slots under motherboard {BOARD_OBJ_PATH}", + "BOARD_OBJ_PATH", boardObjPath.c_str()); } } diff --git a/oem/ibm/requester/dbus_to_file_handler.cpp b/oem/ibm/requester/dbus_to_file_handler.cpp index e574d315a..ed4708744 100644 --- a/oem/ibm/requester/dbus_to_file_handler.cpp +++ b/oem/ibm/requester/dbus_to_file_handler.cpp @@ -5,6 +5,10 @@ #include "common/utils.hpp" +#include + +PHOSPHOR_LOG2_USING; + namespace pldm { namespace requester @@ -37,8 +41,8 @@ void DbusToFileHandler::sendNewFileAvailableCmd(uint64_t fileSize) { if (requester == NULL) { - std::cerr << "Failed to send resource dump parameters as requester is " - "not set"; + error( + "Failed to send resource dump parameters as requester is not set"); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.sendNewFileAvailableCmd.SendDumpParametersFail", pldm::PelSeverity::ERROR); @@ -57,7 +61,7 @@ void DbusToFileHandler::sendNewFileAvailableCmd(uint64_t fileSize) if (rc != PLDM_SUCCESS) { requester->markFree(mctp_eid, instanceId); - std::cerr << "Failed to encode_new_file_req, rc = " << rc << std::endl; + error("Failed to encode_new_file_req, rc = {RC}", "RC", rc); return; } @@ -66,19 +70,16 @@ void DbusToFileHandler::sendNewFileAvailableCmd(uint64_t fileSize) size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr - << "Failed to receive response for NewFileAvailable command \n"; + error("Failed to receive response for NewFileAvailable command"); return; } uint8_t completionCode{}; auto rc = decode_new_file_resp(response, respMsgLen, &completionCode); if (rc || completionCode) { - std::cerr << "Failed to decode_new_file_resp or" - << " Host returned error for new_file_available" - << " rc=" << rc - << ", cc=" << static_cast(completionCode) - << "\n"; + error( + "Failed to decode_new_file_resp or Host returned error for new_file_available rc={RC}, cc = {CC}", + "RC", rc, "CC", static_cast(completionCode)); reportResourceDumpFailure("decodeNewFileResp"); } }; @@ -87,7 +88,7 @@ void DbusToFileHandler::sendNewFileAvailableCmd(uint64_t fileSize) std::move(requestMsg), std::move(newFileAvailableRespHandler)); if (rc) { - std::cerr << "Failed to send NewFileAvailable Request to Host \n"; + error("Failed to send NewFileAvailable Request to Host"); reportResourceDumpFailure("newFileAvailableRequest"); } } @@ -108,9 +109,8 @@ void DbusToFileHandler::reportResourceDumpFailure(std::string str) } catch (const std::exception& e) { - std::cerr << "failed to set resource dump operation status, " - "ERROR=" - << e.what() << "\n"; + error("failed to set resource dump operation status, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } } @@ -132,7 +132,7 @@ void DbusToFileHandler::processNewResourceDump( } catch (const sdbusplus::exception::exception& e) { - std::cerr << "Error in getting current resource dump status \n"; + error("Error in getting current resource dump status"); return; } @@ -153,8 +153,8 @@ void DbusToFileHandler::processNewResourceDump( if (!fileHandleFd) { - std::cerr << "resource dump file open error: " << resDumpFilePath - << "\n"; + error("resource dump file open error:{RES_DUMP_PATH}", "RES_DUMP_PATH", + resDumpFilePath); PropertyValue value{resDumpStatus}; DBusMapping dbusMapping{resDumpCurrentObjPath, resDumpProgressIntf, "Status", "string"}; @@ -164,9 +164,9 @@ void DbusToFileHandler::processNewResourceDump( } catch (const std::exception& e) { - std::cerr << "failed to set resource dump operation status, " - "ERROR=" - << e.what() << "\n"; + error( + "failed to set resource dump operation status, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } return; } @@ -231,7 +231,8 @@ void DbusToFileHandler::newCsrFileAvailable(const std::string& csr, if (!certFile) { - std::cerr << "cert file open error: " << certFilePath << "\n"; + error("cert file open error: {CERT_FILE}", "CERT_FILE", + certFilePath.c_str()); return; } @@ -265,7 +266,8 @@ void DbusToFileHandler::newLicFileAvailable(const std::string& licenseStr) if (!licFile) { - std::cerr << "License file open error: " << licFilePath << "\n"; + error("License file open error: {LIC_FILE}", "LIC_FILE", + licFilePath.c_str()); return; } @@ -284,7 +286,7 @@ void DbusToFileHandler::newFileAvailableSendToHost(const uint32_t fileSize, { if (requester == NULL) { - std::cerr << "newFileAvailableSendToHost:Failed to send file to host."; + error("newFileAvailableSendToHost:Failed to send file to host."); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.SendFileToHostFail", pldm::PelSeverity::ERROR); @@ -300,21 +302,20 @@ void DbusToFileHandler::newFileAvailableSendToHost(const uint32_t fileSize, if (rc != PLDM_SUCCESS) { requester->markFree(mctp_eid, instanceId); - std::cerr - << "newFileAvailableSendToHost:Failed to encode_new_file_req, rc = " - << rc << std::endl; + error( + "newFileAvailableSendToHost:Failed to encode_new_file_req, rc = {RC}", + "RC", rc); return; } - std::cout - << "newFileAvailableSendToHost:Sending Sign CSR request to Host for fileHandle: " - << fileHandle << std::endl; + info( + "newFileAvailableSendToHost:Sending Sign CSR request to Host for fileHandle: {FILE_HNDL}", + "FILE_HNDL", fileHandle); auto newFileAvailableRespHandler = [fileHandle, type](mctp_eid_t /*eid*/, const pldm_msg* response, size_t respMsgLen) { if (response == nullptr || !respMsgLen) { - std::cerr << "Failed to receive response for NewFileAvailable " - "command\n"; + error("Failed to receive response for NewFileAvailable command"); if (type == PLDM_FILE_TYPE_CERT_SIGNING_REQUEST) { std::string filePath = certFilePath; @@ -333,10 +334,9 @@ void DbusToFileHandler::newFileAvailableSendToHost(const uint32_t fileSize, } catch (const std::exception& e) { - std::cerr - << "newFileAvailableSendToHost:Failed to set status property of certicate entry, " - "ERROR=" - << e.what() << "\n"; + error( + "newFileAvailableSendToHost:Failed to set status property of certicate entry, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } pldm::utils::reportError( @@ -349,11 +349,9 @@ void DbusToFileHandler::newFileAvailableSendToHost(const uint32_t fileSize, auto rc = decode_new_file_resp(response, respMsgLen, &completionCode); if (rc || completionCode) { - std::cerr << "Failed to decode_new_file_resp for file, or" - << " Host returned error for new_file_available" - << " rc=" << rc - << ", cc=" << static_cast(completionCode) - << "\n"; + error( + "Failed to decode_new_file_resp for file, or Host returned error for new_file_available rc = {RC}, cc= {CC}", + "RC", rc, "CC", static_cast(completionCode)); if (rc) { pldm::utils::reportError( @@ -367,8 +365,8 @@ void DbusToFileHandler::newFileAvailableSendToHost(const uint32_t fileSize, std::move(requestMsg), std::move(newFileAvailableRespHandler)); if (rc) { - std::cerr - << "newFileAvailableSendToHost:Failed to send NewFileAvailable Request to Host\n"; + error( + "newFileAvailableSendToHost:Failed to send NewFileAvailable Request to Host"); pldm::utils::reportError( "xyz.openbmc_project.PLDM.Error.NewFileAvailableRequestFail", pldm::PelSeverity::ERROR); diff --git a/oem/ibm/service_files/pldm-create-phyp-nvram-cksum.service b/oem/ibm/service_files/pldm-create-phyp-nvram-cksum.service index 4e0389ede..56d3e425f 100644 --- a/oem/ibm/service_files/pldm-create-phyp-nvram-cksum.service +++ b/oem/ibm/service_files/pldm-create-phyp-nvram-cksum.service @@ -7,7 +7,7 @@ After=obmc-flash-bios-init.service ConditionPathExists=!/var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM-CKSUM [Service] -ExecStart=/bin/sh -c "if [ -f /var/lib/pldm/PHYP-NVRAM-CKSUM ]; then mv /var/lib/pldm/PHYP-NVRAM-CKSUM /var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM-CKSUM; else dd if=/dev/zero of=/var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM-CKSUM bs=16 count=1; fi" +ExecStart=/bin/sh -c "if [ -f /var/lib/pldm/PHYP-NVRAM-CKSUM ]; then mv /var/lib/pldm/PHYP-NVRAM-CKSUM /var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM-CKSUM; else truncate -s 16 /var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM-CKSUM; fi" Type=oneshot RemainAfterExit=no diff --git a/oem/ibm/service_files/pldm-create-phyp-nvram.service b/oem/ibm/service_files/pldm-create-phyp-nvram.service index c1122a7af..1b3ad70f7 100644 --- a/oem/ibm/service_files/pldm-create-phyp-nvram.service +++ b/oem/ibm/service_files/pldm-create-phyp-nvram.service @@ -7,7 +7,7 @@ After=obmc-flash-bios-init.service ConditionPathExists=!/var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM [Service] -ExecStart=/bin/sh -c "if [ -f /var/lib/pldm/PHYP-NVRAM ]; then mv /var/lib/pldm/PHYP-NVRAM /var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM; else dd if=/dev/zero of=/var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM bs=1024 count=145408; fi" +ExecStart=/bin/sh -c "if [ -f /var/lib/pldm/PHYP-NVRAM ]; then mv /var/lib/pldm/PHYP-NVRAM /var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM; else truncate -s $((1024 * 145408)) /var/lib/phosphor-software-manager/hostfw/nvram/PHYP-NVRAM; fi" Type=oneshot RemainAfterExit=no diff --git a/pldmd/instance_id.cpp b/pldmd/instance_id.cpp index 9e9a643f6..a64f95a0c 100644 --- a/pldmd/instance_id.cpp +++ b/pldmd/instance_id.cpp @@ -1,12 +1,13 @@ -#include "config.h" - #include "instance_id.hpp" +#include + #include +PHOSPHOR_LOG2_USING; + namespace pldm { - uint8_t InstanceId::next() { uint8_t idx = 0; @@ -19,7 +20,7 @@ uint8_t InstanceId::next() { // check all the instance ids and free up the one // that is acquired oldest - std::cerr << "all the Instance ids are exhausted \n"; + error("lg2 all the Instance ids are exhausted"); auto instance = returnOldestId(); if (instance.has_value()) @@ -63,8 +64,8 @@ std::optional InstanceId::returnOldestId() } if (skipInstance) { - std::cerr - << "None of the instance id's are older then the pldm instance id expiration time\n"; + error( + "lg2 None of the instance id's are older then the pldm instance id expiration time"); return std::nullopt; } const std::time_t t_c = diff --git a/pldmd/pldmd.cpp b/pldmd/pldmd.cpp index 26a49f4e5..ae674c034 100644 --- a/pldmd/pldmd.cpp +++ b/pldmd/pldmd.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -75,11 +76,12 @@ using namespace pldm::responder; using namespace pldm::utils; using sdeventplus::source::Signal; using namespace pldm::flightrecorder; +PHOSPHOR_LOG2_USING; void interruptFlightRecorderCallBack(Signal& /*signal*/, const struct signalfd_siginfo*) { - std::cerr << "\nReceived SIGUR1(10) Signal interrupt\n"; + info("Received SIGUR1(10) Signal interrupt"); // obtain the flight recorder instance and dump the recorder FlightRecorder::GetInstance().playRecorder(); @@ -98,7 +100,7 @@ static std::optional requestMsg.data() + sizeof(eid) + sizeof(type)); if (PLDM_SUCCESS != unpack_pldm_header(hdr, &hdrFields)) { - std::cerr << "Empty PLDM request header \n"; + info("Empty PLDM request header"); return std::nullopt; } @@ -134,7 +136,7 @@ static std::optional header.command = hdrFields.command; if (PLDM_SUCCESS != pack_pldm_header(&header, responseHdr)) { - std::cerr << "Failed adding response header \n"; + error("Failed adding response header"); return std::nullopt; } response.insert(response.end(), completion_code); @@ -154,9 +156,9 @@ static std::optional void optionUsage(void) { - std::cerr << "Usage: pldmd [options]\n"; - std::cerr << "Options:\n"; - std::cerr << " [--verbose] - would enable verbosity\n"; + error("Usage: pldmd [options]"); + error("Options:"); + error(" [--verbose] - would enable verbosity"); } int main(int argc, char** argv) @@ -183,7 +185,7 @@ int main(int argc, char** argv) if (-1 == sockfd) { returnCode = -errno; - std::cerr << "Failed to create the socket, RC= " << returnCode << "\n"; + error("Failed to create the socket, RC={RC}", "RC", returnCode); exit(EXIT_FAILURE); } socklen_t optlen; @@ -196,8 +198,8 @@ int main(int argc, char** argv) &optlen); if (res == -1) { - std::cerr << "Error calling setsockopt. RC = " << res - << ", errno = " << errno << std::endl; + error("Error calling setsockopt. RC = {RC}, errno = {ERR}", "RC", res, + "ERR", errno); } auto event = Event::get_default(); auto& bus = pldm::utils::DBusHandler::getBus(); @@ -343,8 +345,7 @@ int main(int argc, char** argv) if (-1 == result) { returnCode = -errno; - std::cerr << "Failed to connect to the socket, RC= " << returnCode - << "\n"; + error("Failed to connect to the socket, RC= {RC}", "RC", returnCode); exit(EXIT_FAILURE); } @@ -352,8 +353,9 @@ int main(int argc, char** argv) if (-1 == result) { returnCode = -errno; - std::cerr << "Failed to send message type as pldm to mctp, RC= " - << returnCode << "\n"; + error("Failed to send message type as pldm to mctp, RC= {RC}", "RC", + returnCode); + exit(EXIT_FAILURE); } @@ -392,7 +394,7 @@ int main(int argc, char** argv) else if (peekedLength <= -1) { returnCode = -errno; - std::cerr << "recv system call failed, RC= " << returnCode << "\n"; + error("recv system call failed, RC= {RC}", "RC", returnCode); } else { @@ -410,8 +412,7 @@ int main(int argc, char** argv) if (MCTP_MSG_TYPE_PLDM != requestMsg[1]) { // Skip this message and continue. - std::cerr << "Encountered Non-PLDM type message" - << "\n"; + error("Encountered Non-PLDM type message"); } else { @@ -451,13 +452,11 @@ int main(int argc, char** argv) sizeof(currentSendbuffSize)); if (res == -1) { - std::cerr - << "Responder : Failed to set the new send buffer size [bytes] : " - << currentSendbuffSize - << " from current size [bytes] : " - << oldBuffSize - << ", Error : " << strerror(errno) - << std::endl; + error( + "Responder : Failed to set the new send buffer size [bytes] : {CUR_BUFF_SIZE} from current size [bytes] : {OLD_BUFF_SIZE}, Error : {ERR}", + "CUR_BUFF_SIZE", currentSendbuffSize, + "OLD_BUFF_SIZE", oldBuffSize, "ERR", + strerror(errno)); return; } } @@ -466,18 +465,17 @@ int main(int argc, char** argv) if (-1 == result) { returnCode = -errno; - std::cerr << "sendto system call failed, RC= " - << returnCode << "\n"; + error("sendto system call failed, RC= {RC}", "RC", + returnCode); } } } } else { - std::cerr - << "Failure to read peeked length packet. peekedLength= " - << peekedLength << " recvDataLength=" << recvDataLength - << "\n"; + error( + "Failure to read peeked length packet. peekedLength = {PEEK_LEN}, recvDataLength= {RECV_DATA}", + "PEEK_LEN", peekedLength, "RECV_DATA", recvDataLength); } } }; @@ -498,7 +496,7 @@ int main(int argc, char** argv) if (shutdown(sockfd, SHUT_RDWR)) { - std::perror("Failed to shutdown the socket"); + error("Failed to shutdown the socket"); } if (returnCode) { diff --git a/pldmtool/meson.build b/pldmtool/meson.build index 765bdba95..47b694457 100644 --- a/pldmtool/meson.build +++ b/pldmtool/meson.build @@ -27,6 +27,7 @@ executable( libpldmutils, nlohmann_json, phosphor_dbus_interfaces, + phosphor_logging_dep, sdbusplus, ], install: true, diff --git a/pldmtool/pldm_base_cmd.cpp b/pldmtool/pldm_base_cmd.cpp index 19dc3aec3..453717510 100644 --- a/pldmtool/pldm_base_cmd.cpp +++ b/pldmtool/pldm_base_cmd.cpp @@ -4,6 +4,8 @@ #include "pldm_cmd_helper.hpp" +#include + #ifdef OEM_IBM #include "libpldm/file_io.h" #include "libpldm/host.h" @@ -109,8 +111,8 @@ class GetPLDMTypes : public CommandInterface types.data()); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << "\n"; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } @@ -181,8 +183,8 @@ class GetPLDMVersion : public CommandInterface &version); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << "\n"; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } char buffer[16] = {0}; @@ -232,8 +234,8 @@ class GetTID : public CommandInterface auto rc = decode_get_tid_resp(responsePtr, payloadLength, &cc, &tid); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << "\n"; + lg2::error("Response Message Error:rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } ordered_json data; @@ -280,8 +282,8 @@ class GetPLDMCommands : public CommandInterface cmdTypes.data()); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << "\n"; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } printPldmCommands(cmdTypes, pldmType); diff --git a/pldmtool/pldm_bios_cmd.cpp b/pldmtool/pldm_bios_cmd.cpp index 5bd171808..7058c5ab2 100644 --- a/pldmtool/pldm_bios_cmd.cpp +++ b/pldmtool/pldm_bios_cmd.cpp @@ -7,6 +7,8 @@ #include "common/utils.hpp" #include "pldm_cmd_helper.hpp" +#include + #include #include @@ -31,6 +33,12 @@ const std::map pldmBIOSTableTypes{ {"AttributeValueTable", PLDM_BIOS_ATTR_VAL_TABLE}, }; +const std::map pldmBIOSTableMap{ + {PLDM_BIOS_STRING_TABLE, "String Table"}, + {PLDM_BIOS_ATTR_TABLE, "Attribute Table"}, + {PLDM_BIOS_ATTR_VAL_TABLE, "Attribute Value Table"}, +}; + } // namespace class GetDateTime : public CommandInterface @@ -65,8 +73,8 @@ class GetDateTime : public CommandInterface &month, &year); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } @@ -123,8 +131,7 @@ class SetDateTime : public CommandInterface if (!uintToDate(tmData, &year, &month, &day, &hours, &minutes, &seconds)) { - std::cerr << "decode date Error: " - << "tmData=" << tmData << std::endl; + lg2::error("decode date Error: tmData={KEY0}", "KEY0", tmData); return {PLDM_ERROR_INVALID_DATA, requestMsg}; } @@ -144,9 +151,9 @@ class SetDateTime : public CommandInterface if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)completionCode - << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)completionCode); + return; } @@ -203,15 +210,16 @@ class GetBIOSTableHandler : public CommandInterface tableType, request); if (rc != PLDM_SUCCESS) { - std::cerr << "Encode GetBIOSTable Error, tableType=," << tableType - << " ,rc=" << rc << std::endl; + lg2::error( + "Encode GetBIOSTable Error, tableType= {KEY0}, rc = {KEY1}", + "KEY0", pldmBIOSTableMap.at(tableType), "KEY1", rc); return std::nullopt; } std::vector responseMsg; rc = pldmSendRecv(requestMsg, responseMsg); if (rc != PLDM_SUCCESS) { - std::cerr << "PLDM: Communication Error, rc =" << rc << std::endl; + lg2::error("PLDM: Communication Error, rc ={KEY0}", "KEY0", rc); return std::nullopt; } @@ -228,8 +236,10 @@ class GetBIOSTableHandler : public CommandInterface if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "GetBIOSTable Response Error: tableType=" << tableType - << ", rc=" << rc << ", cc=" << (int)cc << std::endl; + lg2::error( + "GetBIOSTable Response Error: tableType={KEY0}, rc ={KEY1}, cc={KEY2}", + "KEY0", pldmBIOSTableMap.at(tableType), "KEY1", rc, "KEY2", + (int)cc); return std::nullopt; } auto tableData = @@ -285,8 +295,9 @@ class GetBIOSTableHandler : public CommandInterface auto strLength = pldm_bios_table_string_entry_decode_string_length(stringEntry); std::vector buffer(strLength + 1 /* sizeof '\0' */); - pldm_bios_table_string_entry_decode_string(stringEntry, buffer.data(), - buffer.size()); + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_string_entry_decode_string_check( + stringEntry, buffer.data(), buffer.size()); return std::string(buffer.data(), buffer.data() + strLength); } @@ -332,9 +343,16 @@ class GetBIOSTableHandler : public CommandInterface { return displayString; } - auto pvNum = pldm_bios_table_attr_entry_enum_decode_pv_num(attrEntry); + uint8_t pvNum; + int rc = pldm_bios_table_attr_entry_enum_decode_pv_num_check(attrEntry, + &pvNum); + if (rc != PLDM_SUCCESS) + { + return displayString; + } std::vector pvHandls(pvNum); - pldm_bios_table_attr_entry_enum_decode_pv_hdls( + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check( attrEntry, pvHandls.data(), pvHandls.size()); return displayStringHandle(pvHandls[index], stringTable, false); } @@ -360,7 +378,7 @@ class GetBIOSTableHandler : public CommandInterface } else { - std::cout << "Get AttributeType failed.\n"; + lg2::info("Get AttributeType failed."); } } switch (attrType) @@ -435,7 +453,7 @@ class GetBIOSTableHandler : public CommandInterface case PLDM_BIOS_PASSWORD: case PLDM_BIOS_PASSWORD_READ_ONLY: { - std::cout << "Password attribute: Not Supported" << std::endl; + lg2::info("Password attribute: Not Supported"); break; } } @@ -500,7 +518,7 @@ class GetBIOSTable : public GetBIOSTableHandler { if (!stringTable) { - std::cerr << "GetBIOSStringTable Error" << std::endl; + lg2::error("GetBIOSStringTable Error"); return; } ordered_json stringdata; @@ -520,7 +538,7 @@ class GetBIOSTable : public GetBIOSTableHandler { if (!stringTable) { - std::cerr << "GetBIOSAttributeTable Error" << std::endl; + lg2::error("GetBIOSAttributeTable Error"); return; } ordered_json output; @@ -546,7 +564,7 @@ class GetBIOSTable : public GetBIOSTableHandler } else { - std::cout << "Get AttributeType failed.\n"; + lg2::error("Get AttributeType failed."); } switch (attrType) @@ -554,13 +572,21 @@ class GetBIOSTable : public GetBIOSTableHandler case PLDM_BIOS_ENUMERATION: case PLDM_BIOS_ENUMERATION_READ_ONLY: { - auto pvNum = - pldm_bios_table_attr_entry_enum_decode_pv_num(entry); + uint8_t pvNum; + // Preconditions are upheld therefore no error check + // necessary + pldm_bios_table_attr_entry_enum_decode_pv_num_check(entry, + &pvNum); std::vector pvHandls(pvNum); - pldm_bios_table_attr_entry_enum_decode_pv_hdls( + // Preconditions are upheld therefore no error check + // necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check( entry, pvHandls.data(), pvHandls.size()); - auto defNum = - pldm_bios_table_attr_entry_enum_decode_def_num(entry); + uint8_t defNum; + // Preconditions are upheld therefore no error check + // necessary + pldm_bios_table_attr_entry_enum_decode_def_num_check( + entry, &defNum); std::vector defIndices(defNum); pldm_bios_table_attr_entry_enum_decode_def_indices( entry, defIndices.data(), defIndices.size()); @@ -609,9 +635,11 @@ class GetBIOSTable : public GetBIOSTableHandler auto max = pldm_bios_table_attr_entry_string_decode_max_length( entry); - auto def = - pldm_bios_table_attr_entry_string_decode_def_string_length( - entry); + uint16_t def; + // Preconditions are upheld therefore no error check + // necessary + pldm_bios_table_attr_entry_string_decode_def_string_length_check( + entry, &def); std::vector defString(def + 1); pldm_bios_table_attr_entry_string_decode_def_string( entry, defString.data(), defString.size()); @@ -629,8 +657,7 @@ class GetBIOSTable : public GetBIOSTableHandler } case PLDM_BIOS_PASSWORD: case PLDM_BIOS_PASSWORD_READ_ONLY: - std::cout << "Password attribute: Not Supported" - << std::endl; + lg2::alert("Password attribute: Not Supported"); } output.emplace_back(std::move(attrdata)); } @@ -642,7 +669,7 @@ class GetBIOSTable : public GetBIOSTableHandler { if (!attrValTable) { - std::cerr << "GetBIOSAttributeValueTable Error" << std::endl; + lg2::error("GetBIOSAttributeValueTable Error"); return; } ordered_json output; @@ -687,14 +714,14 @@ class GetBIOSAttributeCurrentValueByHandle : public GetBIOSTableHandler if (!stringTable || !attrTable) { - std::cout << "StringTable/AttrTable Unavaliable" << std::endl; + lg2::info("StringTable/AttrTable Unavaliable"); return; } auto handle = findAttrHandleByName(attrName, *attrTable, *stringTable); if (!handle) { - std::cerr << "Can not find the attribute " << attrName << std::endl; + lg2::error("Can not find the attribute {KEY0}", "KEY0", attrName); return; } @@ -707,7 +734,7 @@ class GetBIOSAttributeCurrentValueByHandle : public GetBIOSTableHandler instanceId, 0, PLDM_GET_FIRSTPART, *handle, request); if (rc != PLDM_SUCCESS) { - std::cerr << "PLDM: Request Message Error, rc =" << rc << std::endl; + lg2::error("PLDM: Request Message Error, rc ={KEY0}", "KEY0", rc); return; } @@ -715,7 +742,7 @@ class GetBIOSAttributeCurrentValueByHandle : public GetBIOSTableHandler rc = pldmSendRecv(requestMsg, responseMsg); if (rc != PLDM_SUCCESS) { - std::cerr << "PLDM: Communication Error, rc =" << rc << std::endl; + lg2::error("PLDM: Communication Error, rc ={KEY0}", "KEY0", rc); return; } @@ -731,8 +758,9 @@ class GetBIOSAttributeCurrentValueByHandle : public GetBIOSTableHandler &attributeData); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); + return; } @@ -781,7 +809,7 @@ class SetBIOSAttributeCurrentValue : public GetBIOSTableHandler if (!stringTable || !attrTable) { - std::cout << "StringTable/AttrTable Unavaliable" << std::endl; + lg2::info("StringTable/AttrTable Unavaliable"); return; } @@ -789,7 +817,7 @@ class SetBIOSAttributeCurrentValue : public GetBIOSTableHandler *stringTable); if (attrEntry == nullptr) { - std::cout << "Could not find attribute :" << attrName << std::endl; + lg2::info("Could not find attribute :{KEY0}", "KEY0", attrName); return; } @@ -807,19 +835,21 @@ class SetBIOSAttributeCurrentValue : public GetBIOSTableHandler { entryLength = pldm_bios_table_attr_value_entry_encode_enum_length(1); - auto pvNum = - pldm_bios_table_attr_entry_enum_decode_pv_num(attrEntry); + uint8_t pvNum; + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_num_check(attrEntry, + &pvNum); std::vector pvHdls(pvNum, 0); - pldm_bios_table_attr_entry_enum_decode_pv_hdls( + // Preconditions are upheld therefore no error check necessary + pldm_bios_table_attr_entry_enum_decode_pv_hdls_check( attrEntry, pvHdls.data(), pvNum); auto stringEntry = pldm_bios_table_string_find_by_string( stringTable->data(), stringTable->size(), attrValue.c_str()); if (stringEntry == nullptr) { - std::cout - << "Set Attribute Error: It's not a possible value" - << std::endl; + lg2::info("Set Attribute Error: It's not a possible value"); + return; } auto valueHandle = @@ -833,9 +863,7 @@ class SetBIOSAttributeCurrentValue : public GetBIOSTableHandler } if (i == pvNum) { - std::cout - << "Set Attribute Error: It's not a possible value" - << std::endl; + lg2::info("Set Attribute Error: It's not a possible value"); return; } @@ -885,14 +913,14 @@ class SetBIOSAttributeCurrentValue : public GetBIOSTableHandler if (rc != PLDM_SUCCESS) { - std::cerr << "PLDM: Request Message Error, rc =" << rc << std::endl; + lg2::error("PLDM: Request Message Error, rc ={KEY0}", "KEY0", rc); return; } std::vector responseMsg; rc = pldmSendRecv(requestMsg, responseMsg); if (rc != PLDM_SUCCESS) { - std::cerr << "PLDM: Communication Error, rc =" << rc << std::endl; + lg2::error("PLDM: Communication Error, rc ={KEY0}", "KEY0", rc); return; } uint8_t cc = 0; @@ -905,8 +933,8 @@ class SetBIOSAttributeCurrentValue : public GetBIOSTableHandler responsePtr, payloadLength, &cc, &nextTransferHandle); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } diff --git a/pldmtool/pldm_cmd_helper.cpp b/pldmtool/pldm_cmd_helper.cpp index 28096146a..8d5805f52 100644 --- a/pldmtool/pldm_cmd_helper.cpp +++ b/pldmtool/pldm_cmd_helper.cpp @@ -1,11 +1,11 @@ #include "pldm_cmd_helper.hpp" -#include "libpldm/pldm.h" - #include "xyz/openbmc_project/Common/error.hpp" +#include #include +#include #include #include @@ -32,7 +32,7 @@ int mctpSockSendRecv(const std::vector& requestMsg, if (-1 == sockFd) { returnCode = -errno; - std::cerr << "Failed to create the socket : RC = " << sockFd << "\n"; + lg2::error("Failed to create the socket : RC = {KEY0}", "KEY0", sockFd); return returnCode; } Logger(pldmVerbose, "Success in creating the socket : RC = ", sockFd); @@ -49,8 +49,9 @@ int mctpSockSendRecv(const std::vector& requestMsg, if (-1 == result) { returnCode = -errno; - std::cerr << "Failed to connect to socket : RC = " << returnCode - << "\n"; + lg2::error("Failed to connect to socket : RC = {KEY0}", "KEY0", + returnCode); + return returnCode; } Logger(pldmVerbose, "Success in connecting to socket : RC = ", returnCode); @@ -60,8 +61,8 @@ int mctpSockSendRecv(const std::vector& requestMsg, if (-1 == result) { returnCode = -errno; - std::cerr << "Failed to send message type as pldm to mctp : RC = " - << returnCode << "\n"; + lg2::error("Failed to send message type as pldm to mctp : RC = {KEY0}", + "KEY0", returnCode); return returnCode; } Logger( @@ -72,7 +73,7 @@ int mctpSockSendRecv(const std::vector& requestMsg, if (-1 == result) { returnCode = -errno; - std::cerr << "Write to socket failure : RC = " << returnCode << "\n"; + lg2::error("Write to socket failure : RC = {KEY0}", "KEY0", returnCode); return returnCode; } Logger(pldmVerbose, "Write to socket successful : RC = ", result); @@ -81,14 +82,16 @@ int mctpSockSendRecv(const std::vector& requestMsg, ssize_t peekedLength = recv(socketFd(), nullptr, 0, MSG_TRUNC | MSG_PEEK); if (0 == peekedLength) { - std::cerr << "Socket is closed : peekedLength = " << peekedLength - << "\n"; + lg2::error("Socket is closed : peekedLength = {KEY0}", "KEY0", + peekedLength); + return returnCode; } else if (peekedLength <= -1) { returnCode = -errno; - std::cerr << "recv() system call failed : RC = " << returnCode << "\n"; + lg2::error("recv() system call failed : RC = {KEY0}", "KEY0", + returnCode); return returnCode; } else @@ -113,8 +116,9 @@ int mctpSockSendRecv(const std::vector& requestMsg, } else if (recvDataLength != peekedLength) { - std::cerr << "Failure to read response length packet: length = " - << recvDataLength << "\n"; + lg2::error( + "Failure to read response length packet: length = {KEY0}", + "KEY0", recvDataLength); return returnCode; } } while (1); @@ -124,8 +128,8 @@ int mctpSockSendRecv(const std::vector& requestMsg, if (-1 == returnCode) { returnCode = -errno; - std::cerr << "Failed to shutdown the socket : RC = " << returnCode - << "\n"; + lg2::error("Failed to shutdown the socket : RC ={KEY0}", "KEY0", + returnCode); return returnCode; } @@ -145,20 +149,24 @@ void CommandInterface::exec() auto method = bus.new_method_call(service.c_str(), pldmObjPath, pldmRequester, "GetInstanceId"); method.append(mctp_eid); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(instanceId); } catch (const std::exception& e) { - std::cerr << "GetInstanceId D-Bus call failed, MCTP id = " - << (unsigned)mctp_eid << ", error = " << e.what() << "\n"; + lg2::error( + "GetInstanceId D-Bus call failed, MCTP id = {KEY0}, error = {KEY1}", + "KEY0", (unsigned)mctp_eid, "KEY1", e.what()); return; } auto [rc, requestMsg] = createRequestMsg(); if (rc != PLDM_SUCCESS) { - std::cerr << "Failed to encode request message for " << pldmType << ":" - << commandName << " rc = " << rc << "\n"; + lg2::error( + "Failed to encode request message for {KEY0} : {KEY1}, rc = {KEY1}", + "KEY0", pldmType, "KEY1", commandName, "KEY1", rc); return; } @@ -167,7 +175,7 @@ void CommandInterface::exec() if (rc != PLDM_SUCCESS) { - std::cerr << "pldmSendRecv: Failed to receive RC = " << rc << "\n"; + lg2::error("pldmSendRecv: Failed to receive RC = {KEY0}", "KEY0", rc); return; } @@ -202,8 +210,8 @@ int CommandInterface::pldmSendRecv(std::vector& requestMsg, int fd = pldm_open(); if (-1 == fd) { - std::cerr << "failed to init mctp " - << "\n"; + lg2::error("failed to init mctp "); + return -1; } uint8_t* responseMessage = nullptr; diff --git a/pldmtool/pldm_fru_cmd.cpp b/pldmtool/pldm_fru_cmd.cpp index f55599d95..e4267ee96 100644 --- a/pldmtool/pldm_fru_cmd.cpp +++ b/pldmtool/pldm_fru_cmd.cpp @@ -2,6 +2,8 @@ #include "pldm_cmd_helper.hpp" +#include + #ifdef OEM_IBM #include "libpldm/fru_oem_ibm.h" #endif @@ -63,8 +65,9 @@ class GetFruRecordTableMetadata : public CommandInterface &total_record_set_identifiers, &total_table_records, &checksum); if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); + return; } ordered_json output; @@ -382,8 +385,8 @@ class GetFRURecordByOption : public CommandInterface if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); return; } @@ -434,8 +437,9 @@ class GetFruRecordTable : public CommandInterface if (rc != PLDM_SUCCESS || cc != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)cc << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)cc); + return; } diff --git a/pldmtool/pldm_fw_update_cmd.cpp b/pldmtool/pldm_fw_update_cmd.cpp index 65dd41262..34ab97ab2 100644 --- a/pldmtool/pldm_fw_update_cmd.cpp +++ b/pldmtool/pldm_fw_update_cmd.cpp @@ -5,6 +5,8 @@ #include "common/utils.hpp" #include "pldm_cmd_helper.hpp" +#include + namespace pldmtool { @@ -92,8 +94,8 @@ class GetStatus : public CommandInterface &reasonCode, &updateOptionFlagsEnabled); if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)completionCode << "\n"; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)completionCode); return; } @@ -177,9 +179,9 @@ class GetFwParams : public CommandInterface &pendingCompImageSetVersion, &compParameterTable); if (rc != PLDM_SUCCESS || fwParams.completion_code != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)fwParams.completion_code - << "\n"; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)fwParams.completion_code); + return; } @@ -267,9 +269,9 @@ class GetFwParams : public CommandInterface &pendingCompVerStr); if (rc) { - std::cerr - << "Decoding component parameter table entry failed, RC=" - << rc << "\n"; + lg2::error( + "Decoding component parameter table entry failed, RC={KEY0}", + "KEY0", rc); return; } diff --git a/pldmtool/pldm_platform_cmd.cpp b/pldmtool/pldm_platform_cmd.cpp index e7c008eff..eb771f2b0 100644 --- a/pldmtool/pldm_platform_cmd.cpp +++ b/pldmtool/pldm_platform_cmd.cpp @@ -4,6 +4,8 @@ #include "common/types.hpp" #include "pldm_cmd_helper.hpp" +#include + #include #include @@ -119,10 +121,10 @@ class GetPDR : public CommandInterface prevRecordHandle); if (!result.second) { - std::cerr - << "Record handle " << recordHandle - << " has multiple references: " << result.first->second - << ", " << prevRecordHandle << "\n"; + lg2::error( + "Record handle {KEY0} has multiple references: {KEY1}, {KEY2}", + "KEY0", recordHandle, "KEY1", result.first->second, + "KEY2", prevRecordHandle); return; } prevRecordHandle = recordHandle; @@ -172,9 +174,8 @@ class GetPDR : public CommandInterface if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)completionCode - << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)completionCode); return; } @@ -731,7 +732,7 @@ class GetPDR : public CommandInterface reinterpret_cast(data); if (!pdr) { - std::cerr << "Failed to get the FRU record set PDR" << std::endl; + lg2::error("Failed to get the FRU record set PDR"); return; } @@ -759,8 +760,7 @@ class GetPDR : public CommandInterface reinterpret_cast(data); if (!pdr) { - std::cerr << "Failed to get the PDR eneity association" - << std::endl; + lg2::error("Failed to get the PDR eneity association"); return; } @@ -772,7 +772,7 @@ class GetPDR : public CommandInterface } else { - std::cout << "Get associationType failed.\n"; + lg2::info("Get associationType failed."); } output["containerEntityType"] = getEntityName(pdr->container.entity_type); @@ -805,7 +805,7 @@ class GetPDR : public CommandInterface (struct pldm_numeric_effecter_value_pdr*)data; if (!pdr) { - std::cerr << "Failed to get numeric effecter PDR" << std::endl; + lg2::error("Failed to get numeric effecter PDR"); return; } @@ -1000,7 +1000,7 @@ class GetPDR : public CommandInterface { if (data == NULL) { - std::cerr << "Failed to get PDR message" << std::endl; + lg2::error("Failed to get PDR message"); return; } @@ -1020,8 +1020,9 @@ class GetPDR : public CommandInterface // is not supported if (!strToPdrType.contains(pdrRecType)) { - std::cerr << "PDR type '" << pdrRecType - << "' is not supported or invalid\n"; + lg2::error("PDR type {KEY0} is not supported or invalid", + "KEY0", pdrRecType); + // PDR type not supported, setting next record handle to 0 // to avoid looping through all PDR records nextRecordHndl = 0; @@ -1113,16 +1114,18 @@ class SetStateEffecter : public CommandInterface if (effecterCount > maxEffecterCount || effecterCount < minEffecterCount) { - std::cerr << "Request Message Error: effecterCount size " - << effecterCount << "is invalid\n"; + lg2::error( + "Request Message Error: effecterCount size {KEY0} is invalid", + "KEY0", effecterCount); auto rc = PLDM_ERROR_INVALID_DATA; return {rc, requestMsg}; } if (effecterData.size() > maxEffecterDataSize) { - std::cerr << "Request Message Error: effecterData size " - << effecterData.size() << "is invalid\n"; + lg2::error( + "Request Message Error: effecterData size {KEY0} is invalid", + "KEY0", effecterData.size()); auto rc = PLDM_ERROR_INVALID_DATA; return {rc, requestMsg}; } @@ -1130,8 +1133,9 @@ class SetStateEffecter : public CommandInterface auto stateField = parseEffecterData(effecterData, effecterCount); if (!stateField) { - std::cerr << "Failed to parse effecter data, effecterCount size " - << effecterCount << "\n"; + lg2::error( + "Failed to parse effecter data, effecterCount size {KEY0}", + "KEY0", effecterCount); auto rc = PLDM_ERROR_INVALID_DATA; return {rc, requestMsg}; } @@ -1149,8 +1153,9 @@ class SetStateEffecter : public CommandInterface if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)completionCode << "\n"; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)completionCode); + return; } @@ -1230,9 +1235,9 @@ class SetNumericEffecterValue : public CommandInterface if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)completionCode - << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)completionCode); + return; } @@ -1297,9 +1302,9 @@ class GetStateSensorReadings : public CommandInterface if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS) { - std::cerr << "Response Message Error: " - << "rc=" << rc << ",cc=" << (int)completionCode - << std::endl; + lg2::error("Response Message Error: rc = {KEY0}, cc={KEY1}", "KEY0", + rc, "KEY1", (int)completionCode); + return; } ordered_json output; diff --git a/requester/handler.hpp b/requester/handler.hpp index cbb691350..b65d852fd 100644 --- a/requester/handler.hpp +++ b/requester/handler.hpp @@ -1,17 +1,15 @@ #pragma once -#include "config.h" - -#include "libpldm/base.h" -#include "libpldm/pldm.h" - #include "common/types.hpp" #include "pldmd/dbus_impl_requester.hpp" #include "request.hpp" +#include +#include #include #include +#include #include #include #include @@ -22,12 +20,12 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace requester { - /** @struct RequestKey * * RequestKey uniquely identifies the PLDM request message to match it with the @@ -133,21 +131,20 @@ class Handler auto instanceIdExpiryCallBack = [key, this](void) { if (this->handlers.contains(key)) { - std::cerr << "Response not received for the request, instance " - "ID expired." - << " EID = " << (unsigned)key.eid - << " INSTANCE_ID = " << (unsigned)key.instanceId - << " TYPE = " << (unsigned)key.type - << " COMMAND = " << (unsigned)key.command << "\n"; + error( + "Response not received for the request, instance ID expired. EID = {EID} INSTANCE_ID = {INST_ID} TYPE = {KEY_TYP} COMMAND = {CMD}", + "EID", (unsigned)key.eid, "INST_ID", + (unsigned)key.instanceId, "KEY_TYP", (unsigned)key.type, + "CMD", (unsigned)key.command); auto& [request, responseHandler, timerInstance] = this->handlers[key]; request->stop(); auto rc = timerInstance->stop(); if (rc) { - std::cerr - << "Failed to stop the instance ID expiry timer. RC = " - << rc << "\n"; + error( + "Failed to stop the instance ID expiry timer. RC = {RC}", + "RC", rc); } // Call response handler with an empty response to indicate no // response @@ -176,8 +173,7 @@ class Handler if (rc) { requester.markFree(eid, instanceId); - std::cerr << "Failure to send the PLDM request message" - << "\n"; + error("Failure to send the PLDM request message"); return rc; } @@ -189,8 +185,9 @@ class Handler catch (const std::runtime_error& e) { requester.markFree(eid, instanceId); - std::cerr << "Failed to start the instance ID expiry timer. RC = " - << e.what() << "\n"; + error( + "Failed to start the instance ID expiry timer. RC = {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } @@ -221,9 +218,8 @@ class Handler auto rc = timerInstance->stop(); if (rc) { - std::cerr - << "Failed to stop the instance ID expiry timer. RC = " - << rc << "\n"; + error("Failed to stop the instance ID expiry timer. RC = {RC}", + "RC", rc); } responseHandler(eid, response, respMsgLen); requester.markFree(key.eid, key.instanceId); diff --git a/requester/mctp_endpoint_discovery.cpp b/requester/mctp_endpoint_discovery.cpp index afdceaacf..8d9d8ce57 100644 --- a/requester/mctp_endpoint_discovery.cpp +++ b/requester/mctp_endpoint_discovery.cpp @@ -30,7 +30,9 @@ MctpDiscovery::MctpDiscovery(sdbusplus::bus_t& bus, auto method = bus.new_method_call( "xyz.openbmc_project.MCTP.Control", "/xyz/openbmc_project/mctp", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); - auto reply = bus.call(method); + auto reply = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); reply.read(objects); } catch (const std::exception& e) diff --git a/requester/request.hpp b/requester/request.hpp index bedd232ed..96fc7d6a2 100644 --- a/requester/request.hpp +++ b/requester/request.hpp @@ -9,6 +9,7 @@ #include +#include #include #include @@ -16,12 +17,12 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - namespace requester { - /** @class RequestRetryTimer * * The abstract base class for implementing the PLDM request retry logic. This @@ -75,8 +76,8 @@ class RequestRetryTimer } catch (const std::runtime_error& e) { - std::cerr << "Failed to start the request timer. RC = " << e.what() - << "\n"; + error("Failed to start the request timer. RC = {RC}", "RC", + e.what()); return PLDM_ERROR; } @@ -89,8 +90,8 @@ class RequestRetryTimer auto rc = timer.stop(); if (rc) { - std::cerr << "Failed to stop the request timer. RC = " << rc - << "\n"; + error("Failed to stop the request timer. RC = {RC}", "RC", + static_cast(rc)); } } @@ -188,11 +189,10 @@ class Request final : public RequestRetryTimer sizeof(currentSendbuffSize)); if (res == -1) { - std::cerr - << "Requester : Failed to set the new send buffer size [bytes] : " - << currentSendbuffSize - << " from current size [bytes]: " << oldSendbuffSize - << " , Error : " << strerror(errno) << std::endl; + error( + "Requester : Failed to set the new send buffer size [bytes] : {CUR_SND_BUFF_SIZE} from current size [bytes]: {OLD_BUF_SIZE} , Error : {ERR}", + "CUR_SND_BUFF_SIZE", currentSendbuffSize, "OLD_BUF_SIZE", + oldSendbuffSize, "ERR", strerror(errno)); return PLDM_ERROR; } } @@ -201,8 +201,8 @@ class Request final : public RequestRetryTimer auto rc = pldm_send(eid, fd, requestMsg.data(), requestMsg.size()); if (rc < 0) { - std::cerr << "Failed to send PLDM message. RC = " << rc - << ", errno = " << errno << "\n"; + error("Failed to send PLDM message. RC = {RC}, errno = {ERR}", "RC", + static_cast(rc), "ERR", errno); return PLDM_ERROR; } return PLDM_SUCCESS; diff --git a/requester/test/meson.build b/requester/test/meson.build index c5c016880..de038ee52 100644 --- a/requester/test/meson.build +++ b/requester/test/meson.build @@ -19,6 +19,7 @@ foreach t : tests gtest, gmock, libpldm_dep, + phosphor_logging_dep, nlohmann_json, phosphor_dbus_interfaces, sdbusplus, diff --git a/softoff/main.cpp b/softoff/main.cpp index 1c6971085..9ed8573c6 100644 --- a/softoff/main.cpp +++ b/softoff/main.cpp @@ -3,8 +3,12 @@ #include +#include + #include +PHOSPHOR_LOG2_USING; + int main(int argc, char* argv[]) { bool noTimeOut = false; @@ -16,7 +20,7 @@ int main(int argc, char* argv[]) { case 't': noTimeOut = true; - std::cout << "Not applying any time outs\n"; + info("Not applying any time outs"); break; case -1: break; @@ -37,15 +41,15 @@ int main(int argc, char* argv[]) if (softPower.isError()) { - std::cerr << "Host failed to gracefully shutdown, exiting " - "pldm-softpoweroff app\n"; + error( + "Host failed to gracefully shutdown, exiting pldm-softpoweroff app"); return -1; } if (softPower.isCompleted()) { - std::cerr << "Host current state is not Running, exiting " - "pldm-softpoweroff app\n"; + error( + "Host current state is not Running, exiting pldm-softpoweroff app"); return 0; } @@ -53,9 +57,8 @@ int main(int argc, char* argv[]) // wait the host gracefully shutdown. if (softPower.hostSoftOff(event)) { - std::cerr << "pldm-softpoweroff:Failure in sending soft off request to " - "the host. Exiting pldm-softpoweroff app\n"; - + error( + "pldm-softpoweroff:Failure in sending soft off request to the host. Exiting pldm-softpoweroff app"); return -1; } @@ -74,18 +77,18 @@ int main(int argc, char* argv[]) method.append( std::vector>>()); - bus.call_noreply(method); + bus.call_noreply( + method, std::chrono::duration_cast(sec(DBUS_TIMEOUT)) + .count()); } catch (const sdbusplus::exception::exception& e) { - std::cerr << "SoftPowerOff:Failed to create BMC dump, ERROR=" - << e.what() << std::endl; + error("SoftPowerOff:Failed to create BMC dump, ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); } - std::cerr - << "PLDM host soft off: ERROR! Wait for the host soft off timeout." - << "Exit the pldm-softpoweroff " - << "\n"; + error( + "PLDM host soft off: ERROR! Wait for the host soft off timeout. Exit the pldm-softpoweroff"); return -1; } diff --git a/softoff/meson.build b/softoff/meson.build index 73784fe21..7805ca2fc 100644 --- a/softoff/meson.build +++ b/softoff/meson.build @@ -5,6 +5,7 @@ deps = [ sdeventplus, sdbusplus, phosphor_dbus_interfaces, + phosphor_logging_dep, ] source = ['main.cpp','softoff.cpp'] diff --git a/softoff/softoff.cpp b/softoff/softoff.cpp index fb81efcfe..852a14cfd 100644 --- a/softoff/softoff.cpp +++ b/softoff/softoff.cpp @@ -1,5 +1,3 @@ -#include "config.h" - #include "softoff.hpp" #include "libpldm/entity.h" @@ -9,6 +7,7 @@ #include "common/utils.hpp" +#include #include #include #include @@ -18,9 +17,10 @@ #include #include +PHOSPHOR_LOG2_USING; + namespace pldm { - using namespace sdeventplus; using namespace sdeventplus::source; constexpr auto clockId = sdeventplus::ClockId::RealTime; @@ -50,8 +50,7 @@ SoftPowerOff::SoftPowerOff(sdbusplus::bus_t& bus, sd_event* event, auto rc = getEffecterID(); if (completed) { - std::cerr - << "pldm-softpoweroff: effecter to initiate softoff not found \n"; + error("pldm-softpoweroff: effecter to initiate softoff not found"); return; } else if (rc != PLDM_SUCCESS) @@ -63,9 +62,8 @@ SoftPowerOff::SoftPowerOff(sdbusplus::bus_t& bus, sd_event* event, rc = getSensorInfo(); if (rc != PLDM_SUCCESS) { - std::cerr << "Message get Sensor PDRs error. PLDM " - "error code = " - << std::hex << std::showbase << rc << "\n"; + error("Message get Sensor PDRs error. PLDM error code = {RC}", "RC", + lg2::hex, (int)rc); hasError = true; return; } @@ -101,7 +99,7 @@ int SoftPowerOff::getHostState() } catch (const std::exception& e) { - std::cerr << "PLDM host soft off: Can't get current host state.\n"; + error("PLDM host soft off: Can't get current host state."); hasError = true; return PLDM_ERROR; } @@ -124,7 +122,7 @@ void SoftPowerOff::hostSoftOffComplete(sdbusplus::message_t& msg) if (msgSensorID == sensorID && msgSensorOffset == sensorOffset && msgEventState == PLDM_SW_TERM_GRACEFUL_SHUTDOWN && msgTID == TID) { - std::cout << "Recieved the graceful shutdown signal from host\n"; + info("Recieved the graceful shutdown signal from host"); if (!noTimeOut) { // Receive Graceful shutdown completion event message. Disable the @@ -132,8 +130,8 @@ void SoftPowerOff::hostSoftOffComplete(sdbusplus::message_t& msg) auto rc = timer.stop(); if (rc < 0) { - std::cerr << "PLDM soft off: Failure to STOP the timer. ERRNO=" - << rc << "\n"; + error("PLDM soft off: Failure to STOP the timer. ERRNO={RC}", + "RC", rc); } } @@ -158,7 +156,9 @@ int SoftPowerOff::getEffecterID() VMMMethod.append(TID, entityType, (uint16_t)PLDM_STATE_SET_SW_TERMINATION_STATUS); - auto VMMResponseMsg = bus.call(VMMMethod); + auto VMMResponseMsg = bus.call( + VMMMethod, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); VMMResponseMsg.read(VMMResponse); if (VMMResponse.size() != 0) @@ -178,8 +178,8 @@ int SoftPowerOff::getEffecterID() } catch (const sdbusplus::exception_t& e) { - std::cerr << "PLDM soft off: Error get VMM PDR,ERROR=" << e.what() - << "\n"; + error("PLDM soft off: Error get VMM PDR,ERROR={ERR_EXCEP}", "ERR_EXCEP", + e.what()); VMMPdrExist = false; } @@ -202,15 +202,15 @@ int SoftPowerOff::getEffecterID() sysFwMethod.append(TID, entityType, (uint16_t)PLDM_STATE_SET_SW_TERMINATION_STATUS); - auto sysFwResponseMsg = bus.call(sysFwMethod); + auto sysFwResponseMsg = bus.call( + sysFwMethod, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); sysFwResponseMsg.read(sysFwResponse); if (sysFwResponse.size() == 0) { - std::cerr - << "No effecter ID has been found that matches the criteria" - << "\n"; + error("No effecter ID has been found that matches the criteria"); return PLDM_ERROR; } @@ -224,8 +224,8 @@ int SoftPowerOff::getEffecterID() } catch (const sdbusplus::exception_t& e) { - std::cerr << "PLDM soft off: Error get system firmware PDR,ERROR=" - << e.what() << "\n"; + error("PLDM soft off: Error get system firmware PDR,ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); completed = true; return PLDM_ERROR; } @@ -250,15 +250,15 @@ int SoftPowerOff::getSensorInfo() method.append(TID, entityType, (uint16_t)PLDM_STATE_SET_SW_TERMINATION_STATUS); - auto ResponseMsg = bus.call(method); + auto ResponseMsg = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); ResponseMsg.read(Response); if (Response.size() == 0) { - std::cerr - << "No sensor PDR has been found that matches the criteria" - << "\n"; + error("No sensor PDR has been found that matches the criteria"); return PLDM_ERROR; } @@ -268,7 +268,7 @@ int SoftPowerOff::getSensorInfo() pdr = reinterpret_cast(rep.data()); if (!pdr) { - std::cerr << "Failed to get state sensor PDR.\n"; + error("Failed to get state sensor PDR."); return PLDM_ERROR; } } @@ -297,8 +297,8 @@ int SoftPowerOff::getSensorInfo() } catch (const sdbusplus::exception_t& e) { - std::cerr << "PLDM soft off: Error get State Sensor PDR,ERROR=" - << e.what() << "\n"; + error("PLDM soft off: Error get State Sensor PDR,ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } @@ -337,14 +337,16 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) "xyz.openbmc_project.PLDM.Requester", "GetInstanceId"); method.append(mctpEID); - auto ResponseMsg = bus.call(method); + auto ResponseMsg = bus.call( + method, + std::chrono::duration_cast(sec(DBUS_TIMEOUT)).count()); ResponseMsg.read(instanceID); } catch (const sdbusplus::exception_t& e) { - std::cerr << "PLDM soft off: Error get instanceID,ERROR=" << e.what() - << "\n"; + error("PLDM soft off: Error get instanceID,ERROR={ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } @@ -358,8 +360,8 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) instanceID, effecterID, effecterCount, &stateField, request); if (rc != PLDM_SUCCESS) { - std::cerr << "Message encode failure. PLDM error code = " << std::hex - << std::showbase << rc << "\n"; + error("Message encode failure. PLDM error code = {RC}", "RC", lg2::hex, + static_cast(rc)); return PLDM_ERROR; } @@ -367,8 +369,7 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) int fd = pldm_open(); if (-1 == fd) { - std::cerr << "Failed to connect to mctp demux daemon" - << "\n"; + error("Failed to connect to mctp demux daemon"); return PLDM_ERROR; } @@ -377,9 +378,8 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) [=, this](Timer& /*source*/, Timer::TimePoint /*time*/) { if (!responseReceived) { - std::cerr << "PLDM soft off: ERROR! Can't get the response for the " - "PLDM request msg. Time out!\n" - << "Exit the pldm-softpoweroff\n"; + error( + "PLDM soft off: ERROR! Can't get the response for the PLDM request msg. Time out! Exit the pldm-softpoweroff"); exit(-1); } return; @@ -401,8 +401,8 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) &responseMsgSize); if (rc) { - std::cerr << "Soft off: failed to recv pldm data. PLDM RC = " << rc - << "\n"; + error("Soft off: failed to recv pldm data. PLDM RC = {RC}", "RC", + static_cast(rc)); return; } @@ -415,16 +415,15 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) auto response = reinterpret_cast(responseMsgPtr.get()); if (response->payload[0] != PLDM_SUCCESS) { - std::cerr - << "Got a bad respose for soft off seteffecter states command . PLDM RC = " - << (unsigned)response->payload[0] << "\n"; + error( + "Got a bad respose for soft off seteffecter states command . PLDM RC = {RC}", + "RC", static_cast(response->payload[0])); exit(-1); } - std::cerr - << "Got the response for set effecter states command, PLDM RC = " - << std::hex << std::showbase - << static_cast(response->payload[0]) << "\n"; + error( + "Got the response for set effecter states command, PLDM RC = {RC}", + "RC", lg2::hex, static_cast(response->payload[0])); std::vector responseMessage; responseMessage.resize(responseMsgSize); memcpy(responseMessage.data(), responseMsg, responseMessage.size()); @@ -442,16 +441,16 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) auto ret = startTimer(timeMicroseconds); if (ret < 0) { - std::cerr - << "Failure to start Host soft off wait timer, ERRNO = " - << ret << "Exit the pldm-softpoweroff\n"; + error( + "Failure to start Host soft off wait timer, ERRNO = {ERR} Exit the pldm-softpoweroff", + "ERR", ret); exit(-1); } else { - std::cerr - << "Timer started waiting for host soft off, TIMEOUT_IN_SEC = " - << SOFTOFF_TIMEOUT_SECONDS << "\n"; + error( + "Timer started waiting for host soft off, TIMEOUT_IN_SEC = {TIMEOUT_IN_SEC}", + "TIMEOUT_IN_SEC", SOFTOFF_TIMEOUT_SECONDS); } } return; @@ -462,8 +461,9 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) rc = pldm_send(mctpEID, fd, requestMsg.data(), requestMsg.size()); if (0 > rc) { - std::cerr << "Failed to send message/receive response. RC = " << rc - << ", errno = " << errno << "\n"; + error( + "Failed to send message/receive response. RC = {RC}, errno = {ERR}", + "RC", static_cast(rc), "ERR", errno); return PLDM_ERROR; } std::vector requestbuffer(requestMsg.begin(), requestMsg.end()); @@ -478,9 +478,9 @@ int SoftPowerOff::hostSoftOff(sdeventplus::Event& event) } catch (const sdeventplus::SdEventError& e) { - std::cerr - << "PLDM host soft off: Failure in processing request.ERROR= " - << e.what() << "\n"; + error( + "PLDM host soft off: Failure in processing request.ERROR= {ERR_EXCEP}", + "ERR_EXCEP", e.what()); return PLDM_ERROR; } } diff --git a/subprojects/phosphor-logging.wrap b/subprojects/phosphor-logging.wrap new file mode 100644 index 000000000..71eee8b84 --- /dev/null +++ b/subprojects/phosphor-logging.wrap @@ -0,0 +1,6 @@ +[wrap-git] +url = https://github.com/openbmc/phosphor-logging.git +revision = HEAD + +[provide] +phosphor-logging = phosphor_logging_dep diff --git a/test/meson.build b/test/meson.build index 04bbfdcc8..d795ee44c 100644 --- a/test/meson.build +++ b/test/meson.build @@ -16,6 +16,7 @@ foreach t : tests build_rpath: get_option('oe-sdk').enabled() ? rpath : '', dependencies: [ libpldm_dep, + phosphor_logging_dep, nlohmann_json, gtest, test_src]), diff --git a/utilities/meson.build b/utilities/meson.build index c7200c1fb..1977aa449 100644 --- a/utilities/meson.build +++ b/utilities/meson.build @@ -1,4 +1,4 @@ -deps = [ CLI11_dep, libpldm_dep, sdeventplus ] +deps = [ CLI11_dep, libpldm_dep, sdeventplus, phosphor_logging_dep ] executable('set-state-effecter', 'requester/set_state_effecter.cpp', implicit_include_directories: false, diff --git a/utilities/requester/set_state_effecter.cpp b/utilities/requester/set_state_effecter.cpp index 5384fa12b..dc174e70f 100644 --- a/utilities/requester/set_state_effecter.cpp +++ b/utilities/requester/set_state_effecter.cpp @@ -2,10 +2,13 @@ #include "libpldm/pldm.h" #include +#include #include #include +PHOSPHOR_LOG2_USING; + int main(int argc, char** argv) { CLI::App app{"Send PLDM command SetStateEffecterStates"}; @@ -29,8 +32,8 @@ int main(int argc, char** argv) &stateField, request); if (rc != PLDM_SUCCESS) { - std::cerr << "Message encode failure. PLDM error code = " << std::hex - << std::showbase << rc << "\n"; + error("Message encode failure. PLDM error code = {RC}", "RC", lg2::hex, + rc); return -1; } @@ -38,8 +41,7 @@ int main(int argc, char** argv) int fd = pldm_open(); if (-1 == fd) { - std::cerr << "Failed to init mctp" - << "\n"; + error("Failed to init mctp"); return -1; } @@ -50,13 +52,14 @@ int main(int argc, char** argv) &responseMsg, &responseMsgSize); if (0 > rc) { - std::cerr << "Failed to send message/receive response. RC = " << rc - << ", errno = " << errno << "\n"; + error( + "Failed to send message/receive response. RC = {RC}, errno = {ERR}", + "RC", rc, "ERR", errno); return -1; } pldm_msg* response = reinterpret_cast(responseMsg); - std::cout << "Done. PLDM RC = " << std::hex << std::showbase - << static_cast(response->payload[0]) << std::endl; + info("Done. PLDM RC = {RC}", "RC", lg2::hex, + static_cast(response->payload[0])); free(responseMsg); return 0; diff --git a/utilities/requester/set_state_effecter_async.cpp b/utilities/requester/set_state_effecter_async.cpp index f0b13b564..9620c8419 100644 --- a/utilities/requester/set_state_effecter_async.cpp +++ b/utilities/requester/set_state_effecter_async.cpp @@ -3,12 +3,15 @@ #include "libpldm/pldm.h" #include +#include #include #include #include #include +PHOSPHOR_LOG2_USING; + using namespace sdeventplus; using namespace sdeventplus::source; @@ -35,8 +38,8 @@ int main(int argc, char** argv) &stateField, request); if (rc != PLDM_SUCCESS) { - std::cerr << "Message encode failure. PLDM error code = " << std::hex - << std::showbase << rc << "\n"; + error("Message encode failure. PLDM error code = {RC}", "RC", lg2::hex, + rc); return -1; } @@ -44,8 +47,7 @@ int main(int argc, char** argv) int fd = pldm_open(); if (-1 == fd) { - std::cerr << "Failed to init mctp" - << "\n"; + error("Failed to init mctp"); return -1; } @@ -67,9 +69,8 @@ int main(int argc, char** argv) // sent out io.set_enabled(Enabled::Off); pldm_msg* response = reinterpret_cast(responseMsg); - std::cout << "Done. PLDM RC = " << std::hex << std::showbase - << static_cast(response->payload[0]) - << std::endl; + info("Done. PLDM RC = {RC}", "RC", lg2::hex, + static_cast(response->payload[0])); free(responseMsg); exit(EXIT_SUCCESS); } @@ -80,8 +81,9 @@ int main(int argc, char** argv) rc = pldm_send(mctpEid, fd, requestMsg.data(), requestMsg.size()); if (0 > rc) { - std::cerr << "Failed to send message/receive response. RC = " << rc - << ", errno = " << errno << "\n"; + error( + "Failed to send message/receive response. RC = {RC}, errno = {ERR}", + "RC", rc, "ERR", errno); return -1; }