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