blob: 87fcc30a4a0f43666381ea83972c207d9d3969aa [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 Srivastavafa5e4d32023-03-12 11:59:49 -0500290 m_interface->set_property("CollectionStatus",
291 std::string("Completed"));
292
293 const nlohmann::json& l_sysCfgJsonObj =
294 m_worker->getSysCfgJsonObj();
295 if (jsonUtility::isBackupAndRestoreRequired(l_sysCfgJsonObj))
296 {
297 BackupAndRestore l_backupAndRestoreObj(l_sysCfgJsonObj);
298 l_backupAndRestoreObj.backupAndRestore();
299 }
300 }
301 else
302 {
303 auto l_threadCount = m_worker->getActiveThreadCount();
304 if (l_timerRetry == MAX_RETRY)
305 {
306 l_timer.cancel();
307 logging::logMessage("Taking too long. Active thread = " +
308 std::to_string(l_threadCount));
309 }
310 else
311 {
312 l_timerRetry++;
Sunny Srivastava59f91a82025-02-12 13:19:04 -0600313 logging::logMessage("Collection is in progress for [" +
314 std::to_string(l_threadCount) + "] FRUs.");
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500315
316 SetTimerToDetectVpdCollectionStatus();
317 }
318 }
319 });
320}
321#endif
322
323int Manager::updateKeyword(const types::Path i_vpdPath,
324 const types::WriteVpdParams i_paramsToWriteData)
325{
326 if (i_vpdPath.empty())
327 {
328 logging::logMessage("Given VPD path is empty.");
329 return -1;
330 }
331
332 types::Path l_fruPath;
333 nlohmann::json l_sysCfgJsonObj{};
334
335 if (m_worker.get() != nullptr)
336 {
337 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
338
339 // Get the EEPROM path
340 if (!l_sysCfgJsonObj.empty())
341 {
342 try
343 {
344 l_fruPath =
345 jsonUtility::getFruPathFromJson(l_sysCfgJsonObj, i_vpdPath);
346 }
347 catch (const std::exception& l_exception)
348 {
349 logging::logMessage(
350 "Error while getting FRU path, Path: " + i_vpdPath +
351 ", error: " + std::string(l_exception.what()));
352 return -1;
353 }
354 }
355 }
356
357 if (l_fruPath.empty())
358 {
359 l_fruPath = i_vpdPath;
360 }
361
362 try
363 {
364 std::shared_ptr<Parser> l_parserObj =
365 std::make_shared<Parser>(l_fruPath, l_sysCfgJsonObj);
366 return l_parserObj->updateVpdKeyword(i_paramsToWriteData);
367 }
368 catch (const std::exception& l_exception)
369 {
370 // TODO:: error log needed
371 logging::logMessage("Update keyword failed for file[" + i_vpdPath +
372 "], reason: " + std::string(l_exception.what()));
373 return -1;
374 }
375}
376
377int Manager::updateKeywordOnHardware(
378 const types::Path i_fruPath,
379 const types::WriteVpdParams i_paramsToWriteData) noexcept
380{
381 try
382 {
383 if (i_fruPath.empty())
384 {
385 throw std::runtime_error("Given FRU path is empty");
386 }
387
388 nlohmann::json l_sysCfgJsonObj{};
389
390 if (m_worker.get() != nullptr)
391 {
392 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
393 }
394
395 std::shared_ptr<Parser> l_parserObj =
396 std::make_shared<Parser>(i_fruPath, l_sysCfgJsonObj);
397 return l_parserObj->updateVpdKeywordOnHardware(i_paramsToWriteData);
398 }
399 catch (const std::exception& l_exception)
400 {
401 EventLogger::createAsyncPel(
402 types::ErrorType::InvalidEeprom, types::SeverityType::Informational,
403 __FILE__, __FUNCTION__, 0,
404 "Update keyword on hardware failed for file[" + i_fruPath +
405 "], reason: " + std::string(l_exception.what()),
406 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
407
408 return constants::FAILURE;
409 }
410}
411
412types::DbusVariantType Manager::readKeyword(
413 const types::Path i_fruPath, const types::ReadVpdParams i_paramsToReadData)
414{
415 try
416 {
417 nlohmann::json l_jsonObj{};
418
419 if (m_worker.get() != nullptr)
420 {
421 l_jsonObj = m_worker->getSysCfgJsonObj();
422 }
423
424 std::error_code ec;
425
426 // Check if given path is filesystem path
427 if (!std::filesystem::exists(i_fruPath, ec) && (ec))
428 {
429 throw std::runtime_error(
430 "Given file path " + i_fruPath + " not found.");
431 }
432
433 logging::logMessage("Performing VPD read on " + i_fruPath);
434
435 std::shared_ptr<vpd::Parser> l_parserObj =
436 std::make_shared<vpd::Parser>(i_fruPath, l_jsonObj);
437
438 std::shared_ptr<vpd::ParserInterface> l_vpdParserInstance =
439 l_parserObj->getVpdParserInstance();
440
441 return (
442 l_vpdParserInstance->readKeywordFromHardware(i_paramsToReadData));
443 }
444 catch (const std::exception& e)
445 {
446 logging::logMessage(
447 e.what() + std::string(". VPD manager read operation failed for ") +
448 i_fruPath);
449 throw types::DeviceError::ReadFailure();
450 }
451}
452
453void Manager::collectSingleFruVpd(
454 const sdbusplus::message::object_path& i_dbusObjPath)
455{
456 try
457 {
458 if (m_vpdCollectionStatus != "Completed")
459 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600460 logging::logMessage(
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500461 "Currently VPD CollectionStatus is not completed. Cannot perform single FRU VPD collection for " +
462 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600463 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500464 }
465
466 // Get system config JSON object from worker class
467 nlohmann::json l_sysCfgJsonObj{};
468
469 if (m_worker.get() != nullptr)
470 {
471 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
472 }
473
474 // Check if system config JSON is present
475 if (l_sysCfgJsonObj.empty())
476 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600477 logging::logMessage(
478 "System config JSON object not present. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500479 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600480 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500481 }
482
483 // Get FRU path for the given D-bus object path from JSON
484 const std::string& l_fruPath =
485 jsonUtility::getFruPathFromJson(l_sysCfgJsonObj, i_dbusObjPath);
486
487 if (l_fruPath.empty())
488 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600489 logging::logMessage(
490 "D-bus object path not present in JSON. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500491 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600492 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500493 }
494
495 // Check if host is up and running
496 if (dbusUtility::isHostRunning())
497 {
498 if (!jsonUtility::isFruReplaceableAtRuntime(l_sysCfgJsonObj,
499 l_fruPath))
500 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600501 logging::logMessage(
502 "Given FRU is not replaceable at host runtime. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500503 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600504 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500505 }
506 }
507 else if (dbusUtility::isBMCReady())
508 {
509 if (!jsonUtility::isFruReplaceableAtStandby(l_sysCfgJsonObj,
510 l_fruPath) &&
511 (!jsonUtility::isFruReplaceableAtRuntime(l_sysCfgJsonObj,
512 l_fruPath)))
513 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600514 logging::logMessage(
515 "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 -0500516 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600517 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500518 }
519 }
520
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600521 // Set CollectionStatus as InProgress. Since it's an intermediate state
522 // D-bus set-property call is good enough to update the status.
523 try
524 {
525 const std::string& l_collStatusProp = "CollectionStatus";
526 dbusUtility::writeDbusProperty(
527 jsonUtility::getServiceName(l_sysCfgJsonObj,
528 std::string(i_dbusObjPath)),
529 std::string(i_dbusObjPath), constants::vpdCollectionInterface,
530 l_collStatusProp,
531 types::DbusVariantType{constants::vpdCollectionInProgress});
532 }
533 catch (const std::exception& e)
534 {
535 logging::logMessage(
536 "Unable to set CollectionStatus as InProgress for " +
537 std::string(i_dbusObjPath) +
538 ". Continue single FRU VPD collection.");
539 }
540
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500541 // Parse VPD
542 types::VPDMapVariant l_parsedVpd = m_worker->parseVpdFile(l_fruPath);
543
544 // If l_parsedVpd is pointing to std::monostate
545 if (l_parsedVpd.index() == 0)
546 {
547 throw std::runtime_error(
548 "VPD parsing failed for " + std::string(i_dbusObjPath));
549 }
550
551 // Get D-bus object map from worker class
552 types::ObjectMap l_dbusObjectMap;
553 m_worker->populateDbus(l_parsedVpd, l_dbusObjectMap, l_fruPath);
554
555 if (l_dbusObjectMap.empty())
556 {
557 throw std::runtime_error(
558 "Failed to create D-bus object map. Single FRU VPD collection failed for " +
559 std::string(i_dbusObjPath));
560 }
561
562 // Call PIM's Notify method
563 if (!dbusUtility::callPIM(move(l_dbusObjectMap)))
564 {
565 throw std::runtime_error(
566 "Notify PIM failed. Single FRU VPD collection failed for " +
567 std::string(i_dbusObjPath));
568 }
569 }
570 catch (const std::exception& l_error)
571 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600572 // Notify FRU's VPD CollectionStatus as Failure
573 if (!dbusUtility::notifyFRUCollectionStatus(
574 std::string(i_dbusObjPath), constants::vpdCollectionFailure))
575 {
576 logging::logMessage(
577 "Call to PIM Notify method failed to update Collection status as Failure for " +
578 std::string(i_dbusObjPath));
579 }
580
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500581 // TODO: Log PEL
582 logging::logMessage(std::string(l_error.what()));
583 }
584}
585
586void Manager::deleteSingleFruVpd(
587 const sdbusplus::message::object_path& i_dbusObjPath)
588{
589 try
590 {
591 if (std::string(i_dbusObjPath).empty())
592 {
593 throw std::runtime_error(
594 "Given DBus object path is empty. Aborting FRU VPD deletion.");
595 }
596
597 if (m_worker.get() == nullptr)
598 {
599 throw std::runtime_error(
600 "Worker object not found, can't perform FRU VPD deletion for: " +
601 std::string(i_dbusObjPath));
602 }
603
604 m_worker->deleteFruVpd(std::string(i_dbusObjPath));
605 }
606 catch (const std::exception& l_ex)
607 {
608 // TODO: Log PEL
609 logging::logMessage(l_ex.what());
610 }
611}
612
613bool Manager::isValidUnexpandedLocationCode(
614 const std::string& i_unexpandedLocationCode)
615{
616 if ((i_unexpandedLocationCode.length() <
617 constants::UNEXP_LOCATION_CODE_MIN_LENGTH) ||
618 ((i_unexpandedLocationCode.compare(0, 4, "Ufcs") !=
619 constants::STR_CMP_SUCCESS) &&
620 (i_unexpandedLocationCode.compare(0, 4, "Umts") !=
621 constants::STR_CMP_SUCCESS)) ||
622 ((i_unexpandedLocationCode.length() >
623 constants::UNEXP_LOCATION_CODE_MIN_LENGTH) &&
624 (i_unexpandedLocationCode.find("-") != 4)))
625 {
626 return false;
627 }
628
629 return true;
630}
631
632std::string Manager::getExpandedLocationCode(
633 const std::string& i_unexpandedLocationCode,
634 [[maybe_unused]] const uint16_t i_nodeNumber)
635{
636 if (!isValidUnexpandedLocationCode(i_unexpandedLocationCode))
637 {
638 phosphor::logging::elog<types::DbusInvalidArgument>(
639 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
640 types::InvalidArgument::ARGUMENT_VALUE(
641 i_unexpandedLocationCode.c_str()));
642 }
643
644 const nlohmann::json& l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
645 if (!l_sysCfgJsonObj.contains("frus"))
646 {
647 logging::logMessage("Missing frus tag in system config JSON");
648 }
649
650 const nlohmann::json& l_listOfFrus =
651 l_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
652
653 for (const auto& l_frus : l_listOfFrus.items())
654 {
655 for (const auto& l_aFru : l_frus.value())
656 {
657 if (l_aFru["extraInterfaces"].contains(
658 constants::locationCodeInf) &&
659 l_aFru["extraInterfaces"][constants::locationCodeInf].value(
660 "LocationCode", "") == i_unexpandedLocationCode)
661 {
662 return std::get<std::string>(dbusUtility::readDbusProperty(
663 l_aFru["serviceName"], l_aFru["inventoryPath"],
664 constants::locationCodeInf, "LocationCode"));
665 }
666 }
667 }
668 phosphor::logging::elog<types::DbusInvalidArgument>(
669 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
670 types::InvalidArgument::ARGUMENT_VALUE(
671 i_unexpandedLocationCode.c_str()));
672}
673
674types::ListOfPaths Manager::getFrusByUnexpandedLocationCode(
675 const std::string& i_unexpandedLocationCode,
676 [[maybe_unused]] const uint16_t i_nodeNumber)
677{
678 types::ListOfPaths l_inventoryPaths;
679
680 if (!isValidUnexpandedLocationCode(i_unexpandedLocationCode))
681 {
682 phosphor::logging::elog<types::DbusInvalidArgument>(
683 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
684 types::InvalidArgument::ARGUMENT_VALUE(
685 i_unexpandedLocationCode.c_str()));
686 }
687
688 const nlohmann::json& l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
689 if (!l_sysCfgJsonObj.contains("frus"))
690 {
691 logging::logMessage("Missing frus tag in system config JSON");
692 }
693
694 const nlohmann::json& l_listOfFrus =
695 l_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
696
697 for (const auto& l_frus : l_listOfFrus.items())
698 {
699 for (const auto& l_aFru : l_frus.value())
700 {
701 if (l_aFru["extraInterfaces"].contains(
702 constants::locationCodeInf) &&
703 l_aFru["extraInterfaces"][constants::locationCodeInf].value(
704 "LocationCode", "") == i_unexpandedLocationCode)
705 {
706 l_inventoryPaths.push_back(
707 l_aFru.at("inventoryPath")
708 .get_ref<const nlohmann::json::string_t&>());
709 }
710 }
711 }
712
713 if (l_inventoryPaths.empty())
714 {
715 phosphor::logging::elog<types::DbusInvalidArgument>(
716 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
717 types::InvalidArgument::ARGUMENT_VALUE(
718 i_unexpandedLocationCode.c_str()));
719 }
720
721 return l_inventoryPaths;
722}
723
Patrick Williams43fedab2025-02-03 14:28:05 -0500724std::string Manager::getHwPath(
725 const sdbusplus::message::object_path& i_dbusObjPath)
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500726{
727 // Dummy code to supress unused variable warning. To be removed.
728 logging::logMessage(std::string(i_dbusObjPath));
729
730 return std::string{};
731}
732
733std::tuple<std::string, uint16_t> Manager::getUnexpandedLocationCode(
734 const std::string& i_expandedLocationCode)
735{
736 /**
737 * Location code should always start with U and fulfil minimum length
738 * criteria.
739 */
740 if (i_expandedLocationCode[0] != 'U' ||
741 i_expandedLocationCode.length() <
742 constants::EXP_LOCATION_CODE_MIN_LENGTH)
743 {
744 phosphor::logging::elog<types::DbusInvalidArgument>(
745 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
746 types::InvalidArgument::ARGUMENT_VALUE(
747 i_expandedLocationCode.c_str()));
748 }
749
750 std::string l_fcKwd;
751
752 auto l_fcKwdValue = dbusUtility::readDbusProperty(
753 "xyz.openbmc_project.Inventory.Manager",
754 "/xyz/openbmc_project/inventory/system/chassis/motherboard",
755 "com.ibm.ipzvpd.VCEN", "FC");
756
757 if (auto l_kwdValue = std::get_if<types::BinaryVector>(&l_fcKwdValue))
758 {
759 l_fcKwd.assign(l_kwdValue->begin(), l_kwdValue->end());
760 }
761
762 // Get the first part of expanded location code to check for FC or TM.
763 std::string l_firstKwd = i_expandedLocationCode.substr(1, 4);
764
765 std::string l_unexpandedLocationCode{};
766 uint16_t l_nodeNummber = constants::INVALID_NODE_NUMBER;
767
768 // Check if this value matches the value of FC keyword.
769 if (l_fcKwd.substr(0, 4) == l_firstKwd)
770 {
771 /**
772 * Period(.) should be there in expanded location code to seggregate
773 * FC, node number and SE values.
774 */
775 size_t l_nodeStartPos = i_expandedLocationCode.find('.');
776 if (l_nodeStartPos == std::string::npos)
777 {
778 phosphor::logging::elog<types::DbusInvalidArgument>(
779 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
780 types::InvalidArgument::ARGUMENT_VALUE(
781 i_expandedLocationCode.c_str()));
782 }
783
784 size_t l_nodeEndPos =
785 i_expandedLocationCode.find('.', l_nodeStartPos + 1);
786 if (l_nodeEndPos == std::string::npos)
787 {
788 phosphor::logging::elog<types::DbusInvalidArgument>(
789 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
790 types::InvalidArgument::ARGUMENT_VALUE(
791 i_expandedLocationCode.c_str()));
792 }
793
794 // Skip 3 bytes for '.ND'
795 l_nodeNummber = std::stoi(i_expandedLocationCode.substr(
796 l_nodeStartPos + 3, (l_nodeEndPos - l_nodeStartPos - 3)));
797
798 /**
799 * Confirm if there are other details apart FC, node number and SE
800 * in location code
801 */
802 if (i_expandedLocationCode.length() >
803 constants::EXP_LOCATION_CODE_MIN_LENGTH)
804 {
805 l_unexpandedLocationCode =
806 i_expandedLocationCode[0] + std::string("fcs") +
807 i_expandedLocationCode.substr(
808 l_nodeEndPos + 1 + constants::SE_KWD_LENGTH,
809 std::string::npos);
810 }
811 else
812 {
813 l_unexpandedLocationCode = "Ufcs";
814 }
815 }
816 else
817 {
818 std::string l_tmKwd;
819 // Read TM keyword value.
820 auto l_tmKwdValue = dbusUtility::readDbusProperty(
821 "xyz.openbmc_project.Inventory.Manager",
822 "/xyz/openbmc_project/inventory/system/chassis/motherboard",
823 "com.ibm.ipzvpd.VSYS", "TM");
824
825 if (auto l_kwdValue = std::get_if<types::BinaryVector>(&l_tmKwdValue))
826 {
827 l_tmKwd.assign(l_kwdValue->begin(), l_kwdValue->end());
828 }
829
830 // Check if the substr matches to TM keyword value.
831 if (l_tmKwd.substr(0, 4) == l_firstKwd)
832 {
833 /**
834 * System location code will not have node number and any other
835 * details.
836 */
837 l_unexpandedLocationCode = "Umts";
838 }
839 // The given location code is neither "fcs" or "mts".
840 else
841 {
842 phosphor::logging::elog<types::DbusInvalidArgument>(
843 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
844 types::InvalidArgument::ARGUMENT_VALUE(
845 i_expandedLocationCode.c_str()));
846 }
847 }
848
849 return std::make_tuple(l_unexpandedLocationCode, l_nodeNummber);
850}
851
852types::ListOfPaths Manager::getFrusByExpandedLocationCode(
853 const std::string& i_expandedLocationCode)
854{
855 std::tuple<std::string, uint16_t> l_locationAndNodePair =
856 getUnexpandedLocationCode(i_expandedLocationCode);
857
858 return getFrusByUnexpandedLocationCode(std::get<0>(l_locationAndNodePair),
859 std::get<1>(l_locationAndNodePair));
860}
861
862void Manager::registerHostStateChangeCallback()
863{
864 static std::shared_ptr<sdbusplus::bus::match_t> l_hostState =
865 std::make_shared<sdbusplus::bus::match_t>(
866 *m_asioConnection,
867 sdbusplus::bus::match::rules::propertiesChanged(
868 constants::hostObjectPath, constants::hostInterface),
869 [this](sdbusplus::message_t& i_msg) {
870 hostStateChangeCallBack(i_msg);
871 });
872}
873
874void Manager::hostStateChangeCallBack(sdbusplus::message_t& i_msg)
875{
876 try
877 {
878 if (i_msg.is_method_error())
879 {
880 throw std::runtime_error(
881 "Error reading callback message for host state");
882 }
883
884 std::string l_objectPath;
885 types::PropertyMap l_propMap;
886 i_msg.read(l_objectPath, l_propMap);
887
888 const auto l_itr = l_propMap.find("CurrentHostState");
889
890 if (l_itr == l_propMap.end())
891 {
892 throw std::runtime_error(
893 "CurrentHostState field is missing in callback message");
894 }
895
896 if (auto l_hostState = std::get_if<std::string>(&(l_itr->second)))
897 {
898 // implies system is moving from standby to power on state
899 if (*l_hostState == "xyz.openbmc_project.State.Host.HostState."
900 "TransitioningToRunning")
901 {
902 // TODO: check for all the essential FRUs in the system.
903
904 // Perform recollection.
905 performVpdRecollection();
906 return;
907 }
908 }
909 else
910 {
911 throw std::runtime_error(
912 "Invalid type recieved in variant for host state.");
913 }
914 }
915 catch (const std::exception& l_ex)
916 {
917 // TODO: Log PEL.
918 logging::logMessage(l_ex.what());
919 }
920}
921
922void Manager::performVpdRecollection()
923{
924 try
925 {
926 if (m_worker.get() != nullptr)
927 {
928 nlohmann::json l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
929
930 // Check if system config JSON is present
931 if (l_sysCfgJsonObj.empty())
932 {
933 throw std::runtime_error(
934 "System config json object is empty, can't process recollection.");
935 }
936
937 const auto& l_frusReplaceableAtStandby =
938 jsonUtility::getListOfFrusReplaceableAtStandby(l_sysCfgJsonObj);
939
940 for (const auto& l_fruInventoryPath : l_frusReplaceableAtStandby)
941 {
942 // ToDo: Add some logic/trace to know the flow to
943 // collectSingleFruVpd has been directed via
944 // performVpdRecollection.
945 collectSingleFruVpd(l_fruInventoryPath);
946 }
947 return;
948 }
949
950 throw std::runtime_error(
951 "Worker object not found can't process recollection");
952 }
953 catch (const std::exception& l_ex)
954 {
955 // TODO Log PEL
956 logging::logMessage(
957 "VPD recollection failed with error: " + std::string(l_ex.what()));
958 }
959}
Souvik Roy1f4c8f82025-01-23 00:37:43 -0600960
961void Manager::processFailedEeproms()
962{
963 if (m_worker.get() != nullptr)
964 {
965 // TODO:
966 // - iterate through list of EEPROMs for which thread creation has
967 // failed
968 // - For each failed EEPROM, trigger VPD collection
969 m_worker->getFailedEepromPaths().clear();
970 }
971}
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500972} // namespace vpd