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