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