blob: 7c90e71a9295f72c62152de284ff9b3210911f07 [file] [log] [blame]
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05001#include "config.h"
2
3#include "manager.hpp"
4
5#include "backup_restore.hpp"
6#include "constants.hpp"
7#include "exceptions.hpp"
8#include "logger.hpp"
9#include "parser.hpp"
10#include "parser_factory.hpp"
11#include "parser_interface.hpp"
12#include "types.hpp"
13#include "utility/dbus_utility.hpp"
14#include "utility/json_utility.hpp"
15#include "utility/vpd_specific_utility.hpp"
16
17#include <boost/asio/steady_timer.hpp>
18#include <sdbusplus/bus/match.hpp>
19#include <sdbusplus/message.hpp>
20
21namespace vpd
22{
23Manager::Manager(
24 const std::shared_ptr<boost::asio::io_context>& ioCon,
25 const std::shared_ptr<sdbusplus::asio::dbus_interface>& iFace,
26 const std::shared_ptr<sdbusplus::asio::connection>& asioConnection) :
27 m_ioContext(ioCon), m_interface(iFace), m_asioConnection(asioConnection)
28{
29 try
30 {
31#ifdef IBM_SYSTEM
Sunny Srivastava765cf7b2025-02-04 05:24:11 -060032 if (dbusUtility::isChassisPowerOn())
33 {
34 // At power on, less number of FRU(s) needs collection. we can scale
35 // down the threads to reduce CPU utilization.
36 m_worker = std::make_shared<Worker>(INVENTORY_JSON_DEFAULT,
37 constants::VALUE_1);
38 }
39 else
40 {
41 // Initialize with default configuration
42 m_worker = std::make_shared<Worker>(INVENTORY_JSON_DEFAULT);
43 }
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -050044
45 // Set up minimal things that is needed before bus name is claimed.
46 m_worker->performInitialSetup();
47
48 // set callback to detect any asset tag change
49 registerAssetTagChangeCallback();
50
51 // set async timer to detect if system VPD is published on D-Bus.
52 SetTimerToDetectSVPDOnDbus();
53
54 // set async timer to detect if VPD collection is done.
55 SetTimerToDetectVpdCollectionStatus();
56
57 // Instantiate GpioMonitor class
58 m_gpioMonitor = std::make_shared<GpioMonitor>(
59 m_worker->getSysCfgJsonObj(), m_worker, m_ioContext);
60
61#endif
62 // set callback to detect host state change.
63 registerHostStateChangeCallback();
64
65 // For backward compatibility. Should be depricated.
66 iFace->register_method(
67 "WriteKeyword",
68 [this](const sdbusplus::message::object_path i_path,
69 const std::string i_recordName, const std::string i_keyword,
70 const types::BinaryVector i_value) -> int {
71 return this->updateKeyword(
72 i_path, std::make_tuple(i_recordName, i_keyword, i_value));
73 });
74
75 // Register methods under com.ibm.VPD.Manager interface
76 iFace->register_method(
77 "UpdateKeyword",
78 [this](const types::Path i_vpdPath,
79 const types::WriteVpdParams i_paramsToWriteData) -> int {
80 return this->updateKeyword(i_vpdPath, i_paramsToWriteData);
81 });
82
83 iFace->register_method(
84 "WriteKeywordOnHardware",
85 [this](const types::Path i_fruPath,
86 const types::WriteVpdParams i_paramsToWriteData) -> int {
87 return this->updateKeywordOnHardware(i_fruPath,
88 i_paramsToWriteData);
89 });
90
91 iFace->register_method(
92 "ReadKeyword",
93 [this](const types::Path i_fruPath,
94 const types::ReadVpdParams i_paramsToReadData)
95 -> types::DbusVariantType {
96 return this->readKeyword(i_fruPath, i_paramsToReadData);
97 });
98
99 iFace->register_method(
100 "CollectFRUVPD",
101 [this](const sdbusplus::message::object_path& i_dbusObjPath) {
102 this->collectSingleFruVpd(i_dbusObjPath);
103 });
104
105 iFace->register_method(
106 "deleteFRUVPD",
107 [this](const sdbusplus::message::object_path& i_dbusObjPath) {
108 this->deleteSingleFruVpd(i_dbusObjPath);
109 });
110
111 iFace->register_method(
112 "GetExpandedLocationCode",
113 [this](const std::string& i_unexpandedLocationCode,
114 uint16_t& i_nodeNumber) -> std::string {
115 return this->getExpandedLocationCode(i_unexpandedLocationCode,
116 i_nodeNumber);
117 });
118
119 iFace->register_method("GetFRUsByExpandedLocationCode",
120 [this](const std::string& i_expandedLocationCode)
121 -> types::ListOfPaths {
122 return this->getFrusByExpandedLocationCode(
123 i_expandedLocationCode);
124 });
125
126 iFace->register_method(
127 "GetFRUsByUnexpandedLocationCode",
128 [this](const std::string& i_unexpandedLocationCode,
129 uint16_t& i_nodeNumber) -> types::ListOfPaths {
130 return this->getFrusByUnexpandedLocationCode(
131 i_unexpandedLocationCode, i_nodeNumber);
132 });
133
134 iFace->register_method(
135 "GetHardwarePath",
136 [this](const sdbusplus::message::object_path& i_dbusObjPath)
137 -> std::string { return this->getHwPath(i_dbusObjPath); });
138
139 iFace->register_method("PerformVPDRecollection", [this]() {
140 this->performVpdRecollection();
141 });
142
143 // Indicates FRU VPD collection for the system has not started.
144 iFace->register_property_rw<std::string>(
145 "CollectionStatus", sdbusplus::vtable::property_::emits_change,
146 [this](const std::string l_currStatus, const auto&) {
147 m_vpdCollectionStatus = l_currStatus;
148 return 0;
149 },
150 [this](const auto&) { return m_vpdCollectionStatus; });
151 }
152 catch (const std::exception& e)
153 {
154 logging::logMessage(
155 "VPD-Manager service failed. " + std::string(e.what()));
156 throw;
157 }
158}
159
160#ifdef IBM_SYSTEM
161void Manager::registerAssetTagChangeCallback()
162{
163 static std::shared_ptr<sdbusplus::bus::match_t> l_assetMatch =
164 std::make_shared<sdbusplus::bus::match_t>(
165 *m_asioConnection,
166 sdbusplus::bus::match::rules::propertiesChanged(
167 constants::systemInvPath, constants::assetTagInf),
168 [this](sdbusplus::message_t& l_msg) {
169 processAssetTagChangeCallback(l_msg);
170 });
171}
172
173void Manager::processAssetTagChangeCallback(sdbusplus::message_t& i_msg)
174{
175 try
176 {
177 if (i_msg.is_method_error())
178 {
179 throw std::runtime_error(
180 "Error reading callback msg for asset tag.");
181 }
182
183 std::string l_objectPath;
184 types::PropertyMap l_propMap;
185 i_msg.read(l_objectPath, l_propMap);
186
187 const auto& l_itrToAssetTag = l_propMap.find("AssetTag");
188 if (l_itrToAssetTag != l_propMap.end())
189 {
190 if (auto l_assetTag =
191 std::get_if<std::string>(&(l_itrToAssetTag->second)))
192 {
193 // Call Notify to persist the AssetTag
194 types::ObjectMap l_objectMap = {
195 {sdbusplus::message::object_path(constants::systemInvPath),
196 {{constants::assetTagInf, {{"AssetTag", *l_assetTag}}}}}};
197
198 // Notify PIM
199 if (!dbusUtility::callPIM(move(l_objectMap)))
200 {
201 throw std::runtime_error(
202 "Call to PIM failed for asset tag update.");
203 }
204 }
205 }
206 else
207 {
208 throw std::runtime_error(
209 "Could not find asset tag in callback message.");
210 }
211 }
212 catch (const std::exception& l_ex)
213 {
214 // TODO: Log PEL with below description.
215 logging::logMessage("Asset tag callback update failed with error: " +
216 std::string(l_ex.what()));
217 }
218}
219
220void Manager::SetTimerToDetectSVPDOnDbus()
221{
222 static boost::asio::steady_timer timer(*m_ioContext);
223
224 // timer for 2 seconds
225 auto asyncCancelled = timer.expires_after(std::chrono::seconds(2));
226
227 (asyncCancelled == 0) ? logging::logMessage("Timer started")
228 : logging::logMessage("Timer re-started");
229
230 timer.async_wait([this](const boost::system::error_code& ec) {
231 if (ec == boost::asio::error::operation_aborted)
232 {
233 throw std::runtime_error(
234 "Timer to detect system VPD collection status was aborted");
235 }
236
237 if (ec)
238 {
239 throw std::runtime_error(
240 "Timer to detect System VPD collection failed");
241 }
242
243 if (m_worker->isSystemVPDOnDBus())
244 {
245 // cancel the timer
246 timer.cancel();
247
248 // Triggering FRU VPD collection. Setting status to "In
249 // Progress".
250 m_interface->set_property("CollectionStatus",
251 std::string("InProgress"));
252 m_worker->collectFrusFromJson();
253 }
254 });
255}
256
257void Manager::SetTimerToDetectVpdCollectionStatus()
258{
Sunny Srivastava59f91a82025-02-12 13:19:04 -0600259 // Keeping max retry for 2 minutes. TODO: Make it configurable based on
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500260 // system type.
Sunny Srivastava59f91a82025-02-12 13:19:04 -0600261 static constexpr auto MAX_RETRY = 12;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500262
263 static boost::asio::steady_timer l_timer(*m_ioContext);
264 static uint8_t l_timerRetry = 0;
265
Sunny Srivastava59f91a82025-02-12 13:19:04 -0600266 auto l_asyncCancelled = l_timer.expires_after(std::chrono::seconds(10));
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500267
268 (l_asyncCancelled == 0)
269 ? logging::logMessage("Collection Timer started")
270 : logging::logMessage("Collection Timer re-started");
271
272 l_timer.async_wait([this](const boost::system::error_code& ec) {
273 if (ec == boost::asio::error::operation_aborted)
274 {
275 throw std::runtime_error(
276 "Timer to detect thread collection status was aborted");
277 }
278
279 if (ec)
280 {
281 throw std::runtime_error(
282 "Timer to detect thread collection failed");
283 }
284
285 if (m_worker->isAllFruCollectionDone())
286 {
287 // cancel the timer
288 l_timer.cancel();
Souvik Roy1f4c8f82025-01-23 00:37:43 -0600289 processFailedEeproms();
Sunny Srivastava4c7798a2025-02-19 18:50:34 +0530290
291 // update VPD for powerVS system.
292 ConfigurePowerVsSystem();
293
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500294 m_interface->set_property("CollectionStatus",
295 std::string("Completed"));
296
297 const nlohmann::json& l_sysCfgJsonObj =
298 m_worker->getSysCfgJsonObj();
299 if (jsonUtility::isBackupAndRestoreRequired(l_sysCfgJsonObj))
300 {
301 BackupAndRestore l_backupAndRestoreObj(l_sysCfgJsonObj);
302 l_backupAndRestoreObj.backupAndRestore();
303 }
304 }
305 else
306 {
307 auto l_threadCount = m_worker->getActiveThreadCount();
308 if (l_timerRetry == MAX_RETRY)
309 {
310 l_timer.cancel();
311 logging::logMessage("Taking too long. Active thread = " +
312 std::to_string(l_threadCount));
313 }
314 else
315 {
316 l_timerRetry++;
Sunny Srivastava59f91a82025-02-12 13:19:04 -0600317 logging::logMessage("Collection is in progress for [" +
318 std::to_string(l_threadCount) + "] FRUs.");
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500319
320 SetTimerToDetectVpdCollectionStatus();
321 }
322 }
323 });
324}
Sunny Srivastava4c7798a2025-02-19 18:50:34 +0530325
Sunny Srivastava022112b2025-02-19 19:53:29 +0530326void Manager::checkAndUpdatePowerVsVpd(
327 const nlohmann::json& i_powerVsJsonObj,
328 std::vector<std::string>& o_failedPathList)
329{
Sunny Srivastava0cd15e12025-02-20 00:01:02 +0530330 for (const auto& [l_fruPath, l_recJson] : i_powerVsJsonObj.items())
331 {
332 // TODO add special handling for PROC CCIN check.
333 for (const auto& [l_recordName, l_kwdJson] : l_recJson.items())
334 {
335 for (const auto& [l_kwdName, l_kwdValue] : l_kwdJson.items())
336 {
337 // Is value of type array.
338 if (!l_kwdValue.is_array())
339 {
340 o_failedPathList.push_back(l_fruPath);
341 continue;
342 }
343
344 nlohmann::json l_sysCfgJsonObj{};
345 if (m_worker.get() != nullptr)
346 {
347 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
348 }
349
350 // The utility method will handle empty JSON case. No explicit
351 // handling required here.
352 auto l_inventoryPath = jsonUtility::getInventoryObjPathFromJson(
353 l_sysCfgJsonObj, l_fruPath);
354
355 // Mark it as failed if inventory path not found in JSON.
356 if (l_inventoryPath.empty())
357 {
358 o_failedPathList.push_back(l_fruPath);
359 continue;
360 }
361
362 // Get current Part number.
363 auto l_retVal = dbusUtility::readDbusProperty(
364 constants::pimServiceName, l_inventoryPath,
365 constants::viniInf, constants::kwdPN);
366
367 auto l_ptrToPn = std::get_if<types::BinaryVector>(&l_retVal);
368
369 if (!l_ptrToPn)
370 {
371 o_failedPathList.push_back(l_fruPath);
372 continue;
373 }
374
375 types::BinaryVector l_binaryKwdValue =
376 l_kwdValue.get<types::BinaryVector>();
377 if (l_binaryKwdValue == (*l_ptrToPn))
378 {
379 continue;
380 }
381
382 // Update part number only if required.
383 if (updateKeyword(
384 l_fruPath,
385 std::make_tuple(l_recordName, l_kwdName, l_kwdValue)) ==
386 constants::FAILURE)
387 {
388 o_failedPathList.push_back(l_fruPath);
389 continue;
390 }
391
392 // Just needed for logging.
393 std::string l_initialPartNum((*l_ptrToPn).begin(),
394 (*l_ptrToPn).end());
395 std::string l_finalPartNum(l_binaryKwdValue.begin(),
396 l_binaryKwdValue.end());
397 logging::logMessage(
398 "Part number updated for path [" + l_inventoryPath + "]" +
399 "From [" + l_initialPartNum + "]" + " to [" +
400 l_finalPartNum + "]");
401 }
402 }
403 }
Sunny Srivastava022112b2025-02-19 19:53:29 +0530404}
405
Sunny Srivastava4c7798a2025-02-19 18:50:34 +0530406void Manager::ConfigurePowerVsSystem()
407{
Sunny Srivastava022112b2025-02-19 19:53:29 +0530408 std::vector<std::string> l_failedPathList;
Sunny Srivastava1a48f0c2025-02-19 19:02:03 +0530409 try
410 {
411 types::BinaryVector l_imValue = dbusUtility::getImFromDbus();
412 if (l_imValue.empty())
413 {
414 throw DbusException("Invalid IM value read from Dbus");
415 }
Sunny Srivastavac6ef42d2025-02-19 19:17:10 +0530416
417 if (!vpdSpecificUtility::isPowerVsConfiguration(l_imValue))
418 {
419 // TODO: Should booting be blocked in case of some
420 // misconfigurations?
421 return;
422 }
Sunny Srivastava022112b2025-02-19 19:53:29 +0530423
424 const nlohmann::json& l_powerVsJsonObj =
425 jsonUtility::getPowerVsJson(l_imValue);
426
427 if (l_powerVsJsonObj.empty())
428 {
429 throw std::runtime_error("PowerVS Json not found");
430 }
431
432 checkAndUpdatePowerVsVpd(l_powerVsJsonObj, l_failedPathList);
433
434 if (!l_failedPathList.empty())
435 {
436 throw std::runtime_error(
437 "Part number update failed for following paths: ");
438 }
Sunny Srivastava1a48f0c2025-02-19 19:02:03 +0530439 }
440 catch (const std::exception& l_ex)
441 {
442 // TODO log appropriate PEL
443 }
Sunny Srivastava4c7798a2025-02-19 18:50:34 +0530444}
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500445#endif
446
447int Manager::updateKeyword(const types::Path i_vpdPath,
448 const types::WriteVpdParams i_paramsToWriteData)
449{
450 if (i_vpdPath.empty())
451 {
452 logging::logMessage("Given VPD path is empty.");
453 return -1;
454 }
455
456 types::Path l_fruPath;
457 nlohmann::json l_sysCfgJsonObj{};
458
459 if (m_worker.get() != nullptr)
460 {
461 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
462
463 // Get the EEPROM path
464 if (!l_sysCfgJsonObj.empty())
465 {
466 try
467 {
468 l_fruPath =
469 jsonUtility::getFruPathFromJson(l_sysCfgJsonObj, i_vpdPath);
470 }
471 catch (const std::exception& l_exception)
472 {
473 logging::logMessage(
474 "Error while getting FRU path, Path: " + i_vpdPath +
475 ", error: " + std::string(l_exception.what()));
476 return -1;
477 }
478 }
479 }
480
481 if (l_fruPath.empty())
482 {
483 l_fruPath = i_vpdPath;
484 }
485
486 try
487 {
488 std::shared_ptr<Parser> l_parserObj =
489 std::make_shared<Parser>(l_fruPath, l_sysCfgJsonObj);
490 return l_parserObj->updateVpdKeyword(i_paramsToWriteData);
491 }
492 catch (const std::exception& l_exception)
493 {
494 // TODO:: error log needed
495 logging::logMessage("Update keyword failed for file[" + i_vpdPath +
496 "], reason: " + std::string(l_exception.what()));
497 return -1;
498 }
499}
500
501int Manager::updateKeywordOnHardware(
502 const types::Path i_fruPath,
503 const types::WriteVpdParams i_paramsToWriteData) noexcept
504{
505 try
506 {
507 if (i_fruPath.empty())
508 {
509 throw std::runtime_error("Given FRU path is empty");
510 }
511
512 nlohmann::json l_sysCfgJsonObj{};
513
514 if (m_worker.get() != nullptr)
515 {
516 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
517 }
518
519 std::shared_ptr<Parser> l_parserObj =
520 std::make_shared<Parser>(i_fruPath, l_sysCfgJsonObj);
521 return l_parserObj->updateVpdKeywordOnHardware(i_paramsToWriteData);
522 }
523 catch (const std::exception& l_exception)
524 {
525 EventLogger::createAsyncPel(
526 types::ErrorType::InvalidEeprom, types::SeverityType::Informational,
527 __FILE__, __FUNCTION__, 0,
528 "Update keyword on hardware failed for file[" + i_fruPath +
529 "], reason: " + std::string(l_exception.what()),
530 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
531
532 return constants::FAILURE;
533 }
534}
535
536types::DbusVariantType Manager::readKeyword(
537 const types::Path i_fruPath, const types::ReadVpdParams i_paramsToReadData)
538{
539 try
540 {
541 nlohmann::json l_jsonObj{};
542
543 if (m_worker.get() != nullptr)
544 {
545 l_jsonObj = m_worker->getSysCfgJsonObj();
546 }
547
548 std::error_code ec;
549
550 // Check if given path is filesystem path
551 if (!std::filesystem::exists(i_fruPath, ec) && (ec))
552 {
553 throw std::runtime_error(
554 "Given file path " + i_fruPath + " not found.");
555 }
556
557 logging::logMessage("Performing VPD read on " + i_fruPath);
558
559 std::shared_ptr<vpd::Parser> l_parserObj =
560 std::make_shared<vpd::Parser>(i_fruPath, l_jsonObj);
561
562 std::shared_ptr<vpd::ParserInterface> l_vpdParserInstance =
563 l_parserObj->getVpdParserInstance();
564
565 return (
566 l_vpdParserInstance->readKeywordFromHardware(i_paramsToReadData));
567 }
568 catch (const std::exception& e)
569 {
570 logging::logMessage(
571 e.what() + std::string(". VPD manager read operation failed for ") +
572 i_fruPath);
573 throw types::DeviceError::ReadFailure();
574 }
575}
576
577void Manager::collectSingleFruVpd(
578 const sdbusplus::message::object_path& i_dbusObjPath)
579{
580 try
581 {
582 if (m_vpdCollectionStatus != "Completed")
583 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600584 logging::logMessage(
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500585 "Currently VPD CollectionStatus is not completed. Cannot perform single FRU VPD collection for " +
586 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600587 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500588 }
589
590 // Get system config JSON object from worker class
591 nlohmann::json l_sysCfgJsonObj{};
592
593 if (m_worker.get() != nullptr)
594 {
595 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
596 }
597
598 // Check if system config JSON is present
599 if (l_sysCfgJsonObj.empty())
600 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600601 logging::logMessage(
602 "System config JSON object not present. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500603 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600604 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500605 }
606
607 // Get FRU path for the given D-bus object path from JSON
608 const std::string& l_fruPath =
609 jsonUtility::getFruPathFromJson(l_sysCfgJsonObj, i_dbusObjPath);
610
611 if (l_fruPath.empty())
612 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600613 logging::logMessage(
614 "D-bus object path not present in JSON. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500615 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600616 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500617 }
618
619 // Check if host is up and running
620 if (dbusUtility::isHostRunning())
621 {
622 if (!jsonUtility::isFruReplaceableAtRuntime(l_sysCfgJsonObj,
623 l_fruPath))
624 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600625 logging::logMessage(
626 "Given FRU is not replaceable at host runtime. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500627 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600628 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500629 }
630 }
631 else if (dbusUtility::isBMCReady())
632 {
633 if (!jsonUtility::isFruReplaceableAtStandby(l_sysCfgJsonObj,
634 l_fruPath) &&
635 (!jsonUtility::isFruReplaceableAtRuntime(l_sysCfgJsonObj,
636 l_fruPath)))
637 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600638 logging::logMessage(
639 "Given FRU is neither replaceable at standby nor replaceable at runtime. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500640 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600641 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500642 }
643 }
644
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600645 // Set CollectionStatus as InProgress. Since it's an intermediate state
646 // D-bus set-property call is good enough to update the status.
RekhaAparna01c532b182025-02-19 19:56:49 -0600647 const std::string& l_collStatusProp = "CollectionStatus";
648
649 if (!dbusUtility::writeDbusProperty(
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600650 jsonUtility::getServiceName(l_sysCfgJsonObj,
651 std::string(i_dbusObjPath)),
652 std::string(i_dbusObjPath), constants::vpdCollectionInterface,
653 l_collStatusProp,
RekhaAparna01c532b182025-02-19 19:56:49 -0600654 types::DbusVariantType{constants::vpdCollectionInProgress}))
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600655 {
656 logging::logMessage(
657 "Unable to set CollectionStatus as InProgress for " +
658 std::string(i_dbusObjPath) +
659 ". Continue single FRU VPD collection.");
660 }
661
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500662 // Parse VPD
663 types::VPDMapVariant l_parsedVpd = m_worker->parseVpdFile(l_fruPath);
664
665 // If l_parsedVpd is pointing to std::monostate
666 if (l_parsedVpd.index() == 0)
667 {
668 throw std::runtime_error(
669 "VPD parsing failed for " + std::string(i_dbusObjPath));
670 }
671
672 // Get D-bus object map from worker class
673 types::ObjectMap l_dbusObjectMap;
674 m_worker->populateDbus(l_parsedVpd, l_dbusObjectMap, l_fruPath);
675
676 if (l_dbusObjectMap.empty())
677 {
678 throw std::runtime_error(
679 "Failed to create D-bus object map. Single FRU VPD collection failed for " +
680 std::string(i_dbusObjPath));
681 }
682
683 // Call PIM's Notify method
684 if (!dbusUtility::callPIM(move(l_dbusObjectMap)))
685 {
686 throw std::runtime_error(
687 "Notify PIM failed. Single FRU VPD collection failed for " +
688 std::string(i_dbusObjPath));
689 }
690 }
691 catch (const std::exception& l_error)
692 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600693 // Notify FRU's VPD CollectionStatus as Failure
694 if (!dbusUtility::notifyFRUCollectionStatus(
695 std::string(i_dbusObjPath), constants::vpdCollectionFailure))
696 {
697 logging::logMessage(
698 "Call to PIM Notify method failed to update Collection status as Failure for " +
699 std::string(i_dbusObjPath));
700 }
701
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500702 // TODO: Log PEL
703 logging::logMessage(std::string(l_error.what()));
704 }
705}
706
707void Manager::deleteSingleFruVpd(
708 const sdbusplus::message::object_path& i_dbusObjPath)
709{
710 try
711 {
712 if (std::string(i_dbusObjPath).empty())
713 {
714 throw std::runtime_error(
715 "Given DBus object path is empty. Aborting FRU VPD deletion.");
716 }
717
718 if (m_worker.get() == nullptr)
719 {
720 throw std::runtime_error(
721 "Worker object not found, can't perform FRU VPD deletion for: " +
722 std::string(i_dbusObjPath));
723 }
724
725 m_worker->deleteFruVpd(std::string(i_dbusObjPath));
726 }
727 catch (const std::exception& l_ex)
728 {
729 // TODO: Log PEL
730 logging::logMessage(l_ex.what());
731 }
732}
733
734bool Manager::isValidUnexpandedLocationCode(
735 const std::string& i_unexpandedLocationCode)
736{
737 if ((i_unexpandedLocationCode.length() <
738 constants::UNEXP_LOCATION_CODE_MIN_LENGTH) ||
739 ((i_unexpandedLocationCode.compare(0, 4, "Ufcs") !=
740 constants::STR_CMP_SUCCESS) &&
741 (i_unexpandedLocationCode.compare(0, 4, "Umts") !=
742 constants::STR_CMP_SUCCESS)) ||
743 ((i_unexpandedLocationCode.length() >
744 constants::UNEXP_LOCATION_CODE_MIN_LENGTH) &&
745 (i_unexpandedLocationCode.find("-") != 4)))
746 {
747 return false;
748 }
749
750 return true;
751}
752
753std::string Manager::getExpandedLocationCode(
754 const std::string& i_unexpandedLocationCode,
755 [[maybe_unused]] const uint16_t i_nodeNumber)
756{
757 if (!isValidUnexpandedLocationCode(i_unexpandedLocationCode))
758 {
759 phosphor::logging::elog<types::DbusInvalidArgument>(
760 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
761 types::InvalidArgument::ARGUMENT_VALUE(
762 i_unexpandedLocationCode.c_str()));
763 }
764
765 const nlohmann::json& l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
766 if (!l_sysCfgJsonObj.contains("frus"))
767 {
768 logging::logMessage("Missing frus tag in system config JSON");
769 }
770
771 const nlohmann::json& l_listOfFrus =
772 l_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
773
774 for (const auto& l_frus : l_listOfFrus.items())
775 {
776 for (const auto& l_aFru : l_frus.value())
777 {
778 if (l_aFru["extraInterfaces"].contains(
779 constants::locationCodeInf) &&
780 l_aFru["extraInterfaces"][constants::locationCodeInf].value(
781 "LocationCode", "") == i_unexpandedLocationCode)
782 {
783 return std::get<std::string>(dbusUtility::readDbusProperty(
784 l_aFru["serviceName"], l_aFru["inventoryPath"],
785 constants::locationCodeInf, "LocationCode"));
786 }
787 }
788 }
789 phosphor::logging::elog<types::DbusInvalidArgument>(
790 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
791 types::InvalidArgument::ARGUMENT_VALUE(
792 i_unexpandedLocationCode.c_str()));
793}
794
795types::ListOfPaths Manager::getFrusByUnexpandedLocationCode(
796 const std::string& i_unexpandedLocationCode,
797 [[maybe_unused]] const uint16_t i_nodeNumber)
798{
799 types::ListOfPaths l_inventoryPaths;
800
801 if (!isValidUnexpandedLocationCode(i_unexpandedLocationCode))
802 {
803 phosphor::logging::elog<types::DbusInvalidArgument>(
804 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
805 types::InvalidArgument::ARGUMENT_VALUE(
806 i_unexpandedLocationCode.c_str()));
807 }
808
809 const nlohmann::json& l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
810 if (!l_sysCfgJsonObj.contains("frus"))
811 {
812 logging::logMessage("Missing frus tag in system config JSON");
813 }
814
815 const nlohmann::json& l_listOfFrus =
816 l_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
817
818 for (const auto& l_frus : l_listOfFrus.items())
819 {
820 for (const auto& l_aFru : l_frus.value())
821 {
822 if (l_aFru["extraInterfaces"].contains(
823 constants::locationCodeInf) &&
824 l_aFru["extraInterfaces"][constants::locationCodeInf].value(
825 "LocationCode", "") == i_unexpandedLocationCode)
826 {
827 l_inventoryPaths.push_back(
828 l_aFru.at("inventoryPath")
829 .get_ref<const nlohmann::json::string_t&>());
830 }
831 }
832 }
833
834 if (l_inventoryPaths.empty())
835 {
836 phosphor::logging::elog<types::DbusInvalidArgument>(
837 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
838 types::InvalidArgument::ARGUMENT_VALUE(
839 i_unexpandedLocationCode.c_str()));
840 }
841
842 return l_inventoryPaths;
843}
844
Patrick Williams43fedab2025-02-03 14:28:05 -0500845std::string Manager::getHwPath(
846 const sdbusplus::message::object_path& i_dbusObjPath)
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500847{
848 // Dummy code to supress unused variable warning. To be removed.
849 logging::logMessage(std::string(i_dbusObjPath));
850
851 return std::string{};
852}
853
854std::tuple<std::string, uint16_t> Manager::getUnexpandedLocationCode(
855 const std::string& i_expandedLocationCode)
856{
857 /**
858 * Location code should always start with U and fulfil minimum length
859 * criteria.
860 */
861 if (i_expandedLocationCode[0] != 'U' ||
862 i_expandedLocationCode.length() <
863 constants::EXP_LOCATION_CODE_MIN_LENGTH)
864 {
865 phosphor::logging::elog<types::DbusInvalidArgument>(
866 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
867 types::InvalidArgument::ARGUMENT_VALUE(
868 i_expandedLocationCode.c_str()));
869 }
870
871 std::string l_fcKwd;
872
873 auto l_fcKwdValue = dbusUtility::readDbusProperty(
874 "xyz.openbmc_project.Inventory.Manager",
875 "/xyz/openbmc_project/inventory/system/chassis/motherboard",
876 "com.ibm.ipzvpd.VCEN", "FC");
877
878 if (auto l_kwdValue = std::get_if<types::BinaryVector>(&l_fcKwdValue))
879 {
880 l_fcKwd.assign(l_kwdValue->begin(), l_kwdValue->end());
881 }
882
883 // Get the first part of expanded location code to check for FC or TM.
884 std::string l_firstKwd = i_expandedLocationCode.substr(1, 4);
885
886 std::string l_unexpandedLocationCode{};
887 uint16_t l_nodeNummber = constants::INVALID_NODE_NUMBER;
888
889 // Check if this value matches the value of FC keyword.
890 if (l_fcKwd.substr(0, 4) == l_firstKwd)
891 {
892 /**
893 * Period(.) should be there in expanded location code to seggregate
894 * FC, node number and SE values.
895 */
896 size_t l_nodeStartPos = i_expandedLocationCode.find('.');
897 if (l_nodeStartPos == std::string::npos)
898 {
899 phosphor::logging::elog<types::DbusInvalidArgument>(
900 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
901 types::InvalidArgument::ARGUMENT_VALUE(
902 i_expandedLocationCode.c_str()));
903 }
904
905 size_t l_nodeEndPos =
906 i_expandedLocationCode.find('.', l_nodeStartPos + 1);
907 if (l_nodeEndPos == std::string::npos)
908 {
909 phosphor::logging::elog<types::DbusInvalidArgument>(
910 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
911 types::InvalidArgument::ARGUMENT_VALUE(
912 i_expandedLocationCode.c_str()));
913 }
914
915 // Skip 3 bytes for '.ND'
916 l_nodeNummber = std::stoi(i_expandedLocationCode.substr(
917 l_nodeStartPos + 3, (l_nodeEndPos - l_nodeStartPos - 3)));
918
919 /**
920 * Confirm if there are other details apart FC, node number and SE
921 * in location code
922 */
923 if (i_expandedLocationCode.length() >
924 constants::EXP_LOCATION_CODE_MIN_LENGTH)
925 {
926 l_unexpandedLocationCode =
927 i_expandedLocationCode[0] + std::string("fcs") +
928 i_expandedLocationCode.substr(
929 l_nodeEndPos + 1 + constants::SE_KWD_LENGTH,
930 std::string::npos);
931 }
932 else
933 {
934 l_unexpandedLocationCode = "Ufcs";
935 }
936 }
937 else
938 {
939 std::string l_tmKwd;
940 // Read TM keyword value.
941 auto l_tmKwdValue = dbusUtility::readDbusProperty(
942 "xyz.openbmc_project.Inventory.Manager",
943 "/xyz/openbmc_project/inventory/system/chassis/motherboard",
944 "com.ibm.ipzvpd.VSYS", "TM");
945
946 if (auto l_kwdValue = std::get_if<types::BinaryVector>(&l_tmKwdValue))
947 {
948 l_tmKwd.assign(l_kwdValue->begin(), l_kwdValue->end());
949 }
950
951 // Check if the substr matches to TM keyword value.
952 if (l_tmKwd.substr(0, 4) == l_firstKwd)
953 {
954 /**
955 * System location code will not have node number and any other
956 * details.
957 */
958 l_unexpandedLocationCode = "Umts";
959 }
960 // The given location code is neither "fcs" or "mts".
961 else
962 {
963 phosphor::logging::elog<types::DbusInvalidArgument>(
964 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
965 types::InvalidArgument::ARGUMENT_VALUE(
966 i_expandedLocationCode.c_str()));
967 }
968 }
969
970 return std::make_tuple(l_unexpandedLocationCode, l_nodeNummber);
971}
972
973types::ListOfPaths Manager::getFrusByExpandedLocationCode(
974 const std::string& i_expandedLocationCode)
975{
976 std::tuple<std::string, uint16_t> l_locationAndNodePair =
977 getUnexpandedLocationCode(i_expandedLocationCode);
978
979 return getFrusByUnexpandedLocationCode(std::get<0>(l_locationAndNodePair),
980 std::get<1>(l_locationAndNodePair));
981}
982
983void Manager::registerHostStateChangeCallback()
984{
985 static std::shared_ptr<sdbusplus::bus::match_t> l_hostState =
986 std::make_shared<sdbusplus::bus::match_t>(
987 *m_asioConnection,
988 sdbusplus::bus::match::rules::propertiesChanged(
989 constants::hostObjectPath, constants::hostInterface),
990 [this](sdbusplus::message_t& i_msg) {
991 hostStateChangeCallBack(i_msg);
992 });
993}
994
995void Manager::hostStateChangeCallBack(sdbusplus::message_t& i_msg)
996{
997 try
998 {
999 if (i_msg.is_method_error())
1000 {
1001 throw std::runtime_error(
1002 "Error reading callback message for host state");
1003 }
1004
1005 std::string l_objectPath;
1006 types::PropertyMap l_propMap;
1007 i_msg.read(l_objectPath, l_propMap);
1008
1009 const auto l_itr = l_propMap.find("CurrentHostState");
1010
1011 if (l_itr == l_propMap.end())
1012 {
1013 throw std::runtime_error(
1014 "CurrentHostState field is missing in callback message");
1015 }
1016
1017 if (auto l_hostState = std::get_if<std::string>(&(l_itr->second)))
1018 {
1019 // implies system is moving from standby to power on state
1020 if (*l_hostState == "xyz.openbmc_project.State.Host.HostState."
1021 "TransitioningToRunning")
1022 {
1023 // TODO: check for all the essential FRUs in the system.
1024
1025 // Perform recollection.
1026 performVpdRecollection();
1027 return;
1028 }
1029 }
1030 else
1031 {
1032 throw std::runtime_error(
1033 "Invalid type recieved in variant for host state.");
1034 }
1035 }
1036 catch (const std::exception& l_ex)
1037 {
1038 // TODO: Log PEL.
1039 logging::logMessage(l_ex.what());
1040 }
1041}
1042
1043void Manager::performVpdRecollection()
1044{
1045 try
1046 {
1047 if (m_worker.get() != nullptr)
1048 {
1049 nlohmann::json l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
1050
1051 // Check if system config JSON is present
1052 if (l_sysCfgJsonObj.empty())
1053 {
1054 throw std::runtime_error(
1055 "System config json object is empty, can't process recollection.");
1056 }
1057
1058 const auto& l_frusReplaceableAtStandby =
1059 jsonUtility::getListOfFrusReplaceableAtStandby(l_sysCfgJsonObj);
1060
1061 for (const auto& l_fruInventoryPath : l_frusReplaceableAtStandby)
1062 {
1063 // ToDo: Add some logic/trace to know the flow to
1064 // collectSingleFruVpd has been directed via
1065 // performVpdRecollection.
1066 collectSingleFruVpd(l_fruInventoryPath);
1067 }
1068 return;
1069 }
1070
1071 throw std::runtime_error(
1072 "Worker object not found can't process recollection");
1073 }
1074 catch (const std::exception& l_ex)
1075 {
1076 // TODO Log PEL
1077 logging::logMessage(
1078 "VPD recollection failed with error: " + std::string(l_ex.what()));
1079 }
1080}
Souvik Roy1f4c8f82025-01-23 00:37:43 -06001081
1082void Manager::processFailedEeproms()
1083{
1084 if (m_worker.get() != nullptr)
1085 {
1086 // TODO:
1087 // - iterate through list of EEPROMs for which thread creation has
1088 // failed
1089 // - For each failed EEPROM, trigger VPD collection
1090 m_worker->getFailedEepromPaths().clear();
1091 }
1092}
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05001093} // namespace vpd