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