blob: 7421ac6482b559a0d1599194f5dbe925af62b74a [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 {
RekhaAparna017fea9f52025-02-17 04:14:02 -0600516 l_fruPath =
517 jsonUtility::getFruPathFromJson(l_sysCfgJsonObj, i_vpdPath);
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500518 }
519 }
520
521 if (l_fruPath.empty())
522 {
523 l_fruPath = i_vpdPath;
524 }
525
526 try
527 {
528 std::shared_ptr<Parser> l_parserObj =
529 std::make_shared<Parser>(l_fruPath, l_sysCfgJsonObj);
530 return l_parserObj->updateVpdKeyword(i_paramsToWriteData);
531 }
532 catch (const std::exception& l_exception)
533 {
534 // TODO:: error log needed
535 logging::logMessage("Update keyword failed for file[" + i_vpdPath +
536 "], reason: " + std::string(l_exception.what()));
537 return -1;
538 }
539}
540
541int Manager::updateKeywordOnHardware(
542 const types::Path i_fruPath,
543 const types::WriteVpdParams i_paramsToWriteData) noexcept
544{
545 try
546 {
547 if (i_fruPath.empty())
548 {
549 throw std::runtime_error("Given FRU path is empty");
550 }
551
552 nlohmann::json l_sysCfgJsonObj{};
553
554 if (m_worker.get() != nullptr)
555 {
556 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
557 }
558
559 std::shared_ptr<Parser> l_parserObj =
560 std::make_shared<Parser>(i_fruPath, l_sysCfgJsonObj);
561 return l_parserObj->updateVpdKeywordOnHardware(i_paramsToWriteData);
562 }
563 catch (const std::exception& l_exception)
564 {
565 EventLogger::createAsyncPel(
566 types::ErrorType::InvalidEeprom, types::SeverityType::Informational,
567 __FILE__, __FUNCTION__, 0,
568 "Update keyword on hardware failed for file[" + i_fruPath +
569 "], reason: " + std::string(l_exception.what()),
570 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
571
572 return constants::FAILURE;
573 }
574}
575
576types::DbusVariantType Manager::readKeyword(
577 const types::Path i_fruPath, const types::ReadVpdParams i_paramsToReadData)
578{
579 try
580 {
581 nlohmann::json l_jsonObj{};
582
583 if (m_worker.get() != nullptr)
584 {
585 l_jsonObj = m_worker->getSysCfgJsonObj();
586 }
587
588 std::error_code ec;
589
590 // Check if given path is filesystem path
591 if (!std::filesystem::exists(i_fruPath, ec) && (ec))
592 {
593 throw std::runtime_error(
594 "Given file path " + i_fruPath + " not found.");
595 }
596
597 logging::logMessage("Performing VPD read on " + i_fruPath);
598
599 std::shared_ptr<vpd::Parser> l_parserObj =
600 std::make_shared<vpd::Parser>(i_fruPath, l_jsonObj);
601
602 std::shared_ptr<vpd::ParserInterface> l_vpdParserInstance =
603 l_parserObj->getVpdParserInstance();
604
605 return (
606 l_vpdParserInstance->readKeywordFromHardware(i_paramsToReadData));
607 }
608 catch (const std::exception& e)
609 {
610 logging::logMessage(
611 e.what() + std::string(". VPD manager read operation failed for ") +
612 i_fruPath);
613 throw types::DeviceError::ReadFailure();
614 }
615}
616
617void Manager::collectSingleFruVpd(
618 const sdbusplus::message::object_path& i_dbusObjPath)
619{
620 try
621 {
622 if (m_vpdCollectionStatus != "Completed")
623 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600624 logging::logMessage(
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500625 "Currently VPD CollectionStatus is not completed. Cannot perform single FRU VPD collection for " +
626 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600627 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500628 }
629
630 // Get system config JSON object from worker class
631 nlohmann::json l_sysCfgJsonObj{};
632
633 if (m_worker.get() != nullptr)
634 {
635 l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
636 }
637
638 // Check if system config JSON is present
639 if (l_sysCfgJsonObj.empty())
640 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600641 logging::logMessage(
642 "System config JSON object not present. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500643 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600644 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500645 }
646
647 // Get FRU path for the given D-bus object path from JSON
648 const std::string& l_fruPath =
649 jsonUtility::getFruPathFromJson(l_sysCfgJsonObj, i_dbusObjPath);
650
651 if (l_fruPath.empty())
652 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600653 logging::logMessage(
654 "D-bus object path not present in JSON. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500655 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600656 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500657 }
658
659 // Check if host is up and running
660 if (dbusUtility::isHostRunning())
661 {
662 if (!jsonUtility::isFruReplaceableAtRuntime(l_sysCfgJsonObj,
663 l_fruPath))
664 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600665 logging::logMessage(
666 "Given FRU is not replaceable at host runtime. Single FRU VPD collection is not performed for " +
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500667 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600668 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500669 }
670 }
671 else if (dbusUtility::isBMCReady())
672 {
673 if (!jsonUtility::isFruReplaceableAtStandby(l_sysCfgJsonObj,
674 l_fruPath) &&
675 (!jsonUtility::isFruReplaceableAtRuntime(l_sysCfgJsonObj,
676 l_fruPath)))
677 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600678 logging::logMessage(
679 "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 -0500680 std::string(i_dbusObjPath));
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600681 return;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500682 }
683 }
684
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600685 // Set CollectionStatus as InProgress. Since it's an intermediate state
686 // D-bus set-property call is good enough to update the status.
RekhaAparna01c532b182025-02-19 19:56:49 -0600687 const std::string& l_collStatusProp = "CollectionStatus";
688
689 if (!dbusUtility::writeDbusProperty(
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600690 jsonUtility::getServiceName(l_sysCfgJsonObj,
691 std::string(i_dbusObjPath)),
692 std::string(i_dbusObjPath), constants::vpdCollectionInterface,
693 l_collStatusProp,
RekhaAparna01c532b182025-02-19 19:56:49 -0600694 types::DbusVariantType{constants::vpdCollectionInProgress}))
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600695 {
696 logging::logMessage(
697 "Unable to set CollectionStatus as InProgress for " +
698 std::string(i_dbusObjPath) +
699 ". Continue single FRU VPD collection.");
700 }
701
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500702 // Parse VPD
703 types::VPDMapVariant l_parsedVpd = m_worker->parseVpdFile(l_fruPath);
704
705 // If l_parsedVpd is pointing to std::monostate
706 if (l_parsedVpd.index() == 0)
707 {
708 throw std::runtime_error(
709 "VPD parsing failed for " + std::string(i_dbusObjPath));
710 }
711
712 // Get D-bus object map from worker class
713 types::ObjectMap l_dbusObjectMap;
714 m_worker->populateDbus(l_parsedVpd, l_dbusObjectMap, l_fruPath);
715
716 if (l_dbusObjectMap.empty())
717 {
718 throw std::runtime_error(
719 "Failed to create D-bus object map. Single FRU VPD collection failed for " +
720 std::string(i_dbusObjPath));
721 }
722
723 // Call PIM's Notify method
724 if (!dbusUtility::callPIM(move(l_dbusObjectMap)))
725 {
726 throw std::runtime_error(
727 "Notify PIM failed. Single FRU VPD collection failed for " +
728 std::string(i_dbusObjPath));
729 }
730 }
731 catch (const std::exception& l_error)
732 {
Priyanga Ramasamy46b73d92025-01-09 10:52:07 -0600733 // Notify FRU's VPD CollectionStatus as Failure
734 if (!dbusUtility::notifyFRUCollectionStatus(
735 std::string(i_dbusObjPath), constants::vpdCollectionFailure))
736 {
737 logging::logMessage(
738 "Call to PIM Notify method failed to update Collection status as Failure for " +
739 std::string(i_dbusObjPath));
740 }
741
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500742 // TODO: Log PEL
743 logging::logMessage(std::string(l_error.what()));
744 }
745}
746
747void Manager::deleteSingleFruVpd(
748 const sdbusplus::message::object_path& i_dbusObjPath)
749{
750 try
751 {
752 if (std::string(i_dbusObjPath).empty())
753 {
754 throw std::runtime_error(
755 "Given DBus object path is empty. Aborting FRU VPD deletion.");
756 }
757
758 if (m_worker.get() == nullptr)
759 {
760 throw std::runtime_error(
761 "Worker object not found, can't perform FRU VPD deletion for: " +
762 std::string(i_dbusObjPath));
763 }
764
765 m_worker->deleteFruVpd(std::string(i_dbusObjPath));
766 }
767 catch (const std::exception& l_ex)
768 {
769 // TODO: Log PEL
770 logging::logMessage(l_ex.what());
771 }
772}
773
774bool Manager::isValidUnexpandedLocationCode(
775 const std::string& i_unexpandedLocationCode)
776{
777 if ((i_unexpandedLocationCode.length() <
778 constants::UNEXP_LOCATION_CODE_MIN_LENGTH) ||
779 ((i_unexpandedLocationCode.compare(0, 4, "Ufcs") !=
780 constants::STR_CMP_SUCCESS) &&
781 (i_unexpandedLocationCode.compare(0, 4, "Umts") !=
782 constants::STR_CMP_SUCCESS)) ||
783 ((i_unexpandedLocationCode.length() >
784 constants::UNEXP_LOCATION_CODE_MIN_LENGTH) &&
785 (i_unexpandedLocationCode.find("-") != 4)))
786 {
787 return false;
788 }
789
790 return true;
791}
792
793std::string Manager::getExpandedLocationCode(
794 const std::string& i_unexpandedLocationCode,
795 [[maybe_unused]] const uint16_t i_nodeNumber)
796{
797 if (!isValidUnexpandedLocationCode(i_unexpandedLocationCode))
798 {
799 phosphor::logging::elog<types::DbusInvalidArgument>(
800 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
801 types::InvalidArgument::ARGUMENT_VALUE(
802 i_unexpandedLocationCode.c_str()));
803 }
804
805 const nlohmann::json& l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
806 if (!l_sysCfgJsonObj.contains("frus"))
807 {
808 logging::logMessage("Missing frus tag in system config JSON");
809 }
810
811 const nlohmann::json& l_listOfFrus =
812 l_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
813
814 for (const auto& l_frus : l_listOfFrus.items())
815 {
816 for (const auto& l_aFru : l_frus.value())
817 {
818 if (l_aFru["extraInterfaces"].contains(
819 constants::locationCodeInf) &&
820 l_aFru["extraInterfaces"][constants::locationCodeInf].value(
821 "LocationCode", "") == i_unexpandedLocationCode)
822 {
823 return std::get<std::string>(dbusUtility::readDbusProperty(
824 l_aFru["serviceName"], l_aFru["inventoryPath"],
825 constants::locationCodeInf, "LocationCode"));
826 }
827 }
828 }
829 phosphor::logging::elog<types::DbusInvalidArgument>(
830 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
831 types::InvalidArgument::ARGUMENT_VALUE(
832 i_unexpandedLocationCode.c_str()));
833}
834
835types::ListOfPaths Manager::getFrusByUnexpandedLocationCode(
836 const std::string& i_unexpandedLocationCode,
837 [[maybe_unused]] const uint16_t i_nodeNumber)
838{
839 types::ListOfPaths l_inventoryPaths;
840
841 if (!isValidUnexpandedLocationCode(i_unexpandedLocationCode))
842 {
843 phosphor::logging::elog<types::DbusInvalidArgument>(
844 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
845 types::InvalidArgument::ARGUMENT_VALUE(
846 i_unexpandedLocationCode.c_str()));
847 }
848
849 const nlohmann::json& l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
850 if (!l_sysCfgJsonObj.contains("frus"))
851 {
852 logging::logMessage("Missing frus tag in system config JSON");
853 }
854
855 const nlohmann::json& l_listOfFrus =
856 l_sysCfgJsonObj["frus"].get_ref<const nlohmann::json::object_t&>();
857
858 for (const auto& l_frus : l_listOfFrus.items())
859 {
860 for (const auto& l_aFru : l_frus.value())
861 {
862 if (l_aFru["extraInterfaces"].contains(
863 constants::locationCodeInf) &&
864 l_aFru["extraInterfaces"][constants::locationCodeInf].value(
865 "LocationCode", "") == i_unexpandedLocationCode)
866 {
867 l_inventoryPaths.push_back(
868 l_aFru.at("inventoryPath")
869 .get_ref<const nlohmann::json::string_t&>());
870 }
871 }
872 }
873
874 if (l_inventoryPaths.empty())
875 {
876 phosphor::logging::elog<types::DbusInvalidArgument>(
877 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
878 types::InvalidArgument::ARGUMENT_VALUE(
879 i_unexpandedLocationCode.c_str()));
880 }
881
882 return l_inventoryPaths;
883}
884
Patrick Williams43fedab2025-02-03 14:28:05 -0500885std::string Manager::getHwPath(
886 const sdbusplus::message::object_path& i_dbusObjPath)
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500887{
888 // Dummy code to supress unused variable warning. To be removed.
889 logging::logMessage(std::string(i_dbusObjPath));
890
891 return std::string{};
892}
893
894std::tuple<std::string, uint16_t> Manager::getUnexpandedLocationCode(
895 const std::string& i_expandedLocationCode)
896{
897 /**
898 * Location code should always start with U and fulfil minimum length
899 * criteria.
900 */
901 if (i_expandedLocationCode[0] != 'U' ||
902 i_expandedLocationCode.length() <
903 constants::EXP_LOCATION_CODE_MIN_LENGTH)
904 {
905 phosphor::logging::elog<types::DbusInvalidArgument>(
906 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
907 types::InvalidArgument::ARGUMENT_VALUE(
908 i_expandedLocationCode.c_str()));
909 }
910
911 std::string l_fcKwd;
912
913 auto l_fcKwdValue = dbusUtility::readDbusProperty(
914 "xyz.openbmc_project.Inventory.Manager",
915 "/xyz/openbmc_project/inventory/system/chassis/motherboard",
916 "com.ibm.ipzvpd.VCEN", "FC");
917
918 if (auto l_kwdValue = std::get_if<types::BinaryVector>(&l_fcKwdValue))
919 {
920 l_fcKwd.assign(l_kwdValue->begin(), l_kwdValue->end());
921 }
922
923 // Get the first part of expanded location code to check for FC or TM.
924 std::string l_firstKwd = i_expandedLocationCode.substr(1, 4);
925
926 std::string l_unexpandedLocationCode{};
927 uint16_t l_nodeNummber = constants::INVALID_NODE_NUMBER;
928
929 // Check if this value matches the value of FC keyword.
930 if (l_fcKwd.substr(0, 4) == l_firstKwd)
931 {
932 /**
933 * Period(.) should be there in expanded location code to seggregate
934 * FC, node number and SE values.
935 */
936 size_t l_nodeStartPos = i_expandedLocationCode.find('.');
937 if (l_nodeStartPos == std::string::npos)
938 {
939 phosphor::logging::elog<types::DbusInvalidArgument>(
940 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
941 types::InvalidArgument::ARGUMENT_VALUE(
942 i_expandedLocationCode.c_str()));
943 }
944
945 size_t l_nodeEndPos =
946 i_expandedLocationCode.find('.', l_nodeStartPos + 1);
947 if (l_nodeEndPos == 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 // Skip 3 bytes for '.ND'
956 l_nodeNummber = std::stoi(i_expandedLocationCode.substr(
957 l_nodeStartPos + 3, (l_nodeEndPos - l_nodeStartPos - 3)));
958
959 /**
960 * Confirm if there are other details apart FC, node number and SE
961 * in location code
962 */
963 if (i_expandedLocationCode.length() >
964 constants::EXP_LOCATION_CODE_MIN_LENGTH)
965 {
966 l_unexpandedLocationCode =
967 i_expandedLocationCode[0] + std::string("fcs") +
968 i_expandedLocationCode.substr(
969 l_nodeEndPos + 1 + constants::SE_KWD_LENGTH,
970 std::string::npos);
971 }
972 else
973 {
974 l_unexpandedLocationCode = "Ufcs";
975 }
976 }
977 else
978 {
979 std::string l_tmKwd;
980 // Read TM keyword value.
981 auto l_tmKwdValue = dbusUtility::readDbusProperty(
982 "xyz.openbmc_project.Inventory.Manager",
983 "/xyz/openbmc_project/inventory/system/chassis/motherboard",
984 "com.ibm.ipzvpd.VSYS", "TM");
985
986 if (auto l_kwdValue = std::get_if<types::BinaryVector>(&l_tmKwdValue))
987 {
988 l_tmKwd.assign(l_kwdValue->begin(), l_kwdValue->end());
989 }
990
991 // Check if the substr matches to TM keyword value.
992 if (l_tmKwd.substr(0, 4) == l_firstKwd)
993 {
994 /**
995 * System location code will not have node number and any other
996 * details.
997 */
998 l_unexpandedLocationCode = "Umts";
999 }
1000 // The given location code is neither "fcs" or "mts".
1001 else
1002 {
1003 phosphor::logging::elog<types::DbusInvalidArgument>(
1004 types::InvalidArgument::ARGUMENT_NAME("LOCATIONCODE"),
1005 types::InvalidArgument::ARGUMENT_VALUE(
1006 i_expandedLocationCode.c_str()));
1007 }
1008 }
1009
1010 return std::make_tuple(l_unexpandedLocationCode, l_nodeNummber);
1011}
1012
1013types::ListOfPaths Manager::getFrusByExpandedLocationCode(
1014 const std::string& i_expandedLocationCode)
1015{
1016 std::tuple<std::string, uint16_t> l_locationAndNodePair =
1017 getUnexpandedLocationCode(i_expandedLocationCode);
1018
1019 return getFrusByUnexpandedLocationCode(std::get<0>(l_locationAndNodePair),
1020 std::get<1>(l_locationAndNodePair));
1021}
1022
1023void Manager::registerHostStateChangeCallback()
1024{
1025 static std::shared_ptr<sdbusplus::bus::match_t> l_hostState =
1026 std::make_shared<sdbusplus::bus::match_t>(
1027 *m_asioConnection,
1028 sdbusplus::bus::match::rules::propertiesChanged(
1029 constants::hostObjectPath, constants::hostInterface),
1030 [this](sdbusplus::message_t& i_msg) {
1031 hostStateChangeCallBack(i_msg);
1032 });
1033}
1034
1035void Manager::hostStateChangeCallBack(sdbusplus::message_t& i_msg)
1036{
1037 try
1038 {
1039 if (i_msg.is_method_error())
1040 {
1041 throw std::runtime_error(
1042 "Error reading callback message for host state");
1043 }
1044
1045 std::string l_objectPath;
1046 types::PropertyMap l_propMap;
1047 i_msg.read(l_objectPath, l_propMap);
1048
1049 const auto l_itr = l_propMap.find("CurrentHostState");
1050
1051 if (l_itr == l_propMap.end())
1052 {
1053 throw std::runtime_error(
1054 "CurrentHostState field is missing in callback message");
1055 }
1056
1057 if (auto l_hostState = std::get_if<std::string>(&(l_itr->second)))
1058 {
1059 // implies system is moving from standby to power on state
1060 if (*l_hostState == "xyz.openbmc_project.State.Host.HostState."
1061 "TransitioningToRunning")
1062 {
1063 // TODO: check for all the essential FRUs in the system.
1064
1065 // Perform recollection.
1066 performVpdRecollection();
1067 return;
1068 }
1069 }
1070 else
1071 {
1072 throw std::runtime_error(
1073 "Invalid type recieved in variant for host state.");
1074 }
1075 }
1076 catch (const std::exception& l_ex)
1077 {
1078 // TODO: Log PEL.
1079 logging::logMessage(l_ex.what());
1080 }
1081}
1082
1083void Manager::performVpdRecollection()
1084{
1085 try
1086 {
1087 if (m_worker.get() != nullptr)
1088 {
1089 nlohmann::json l_sysCfgJsonObj = m_worker->getSysCfgJsonObj();
1090
1091 // Check if system config JSON is present
1092 if (l_sysCfgJsonObj.empty())
1093 {
1094 throw std::runtime_error(
1095 "System config json object is empty, can't process recollection.");
1096 }
1097
1098 const auto& l_frusReplaceableAtStandby =
1099 jsonUtility::getListOfFrusReplaceableAtStandby(l_sysCfgJsonObj);
1100
1101 for (const auto& l_fruInventoryPath : l_frusReplaceableAtStandby)
1102 {
1103 // ToDo: Add some logic/trace to know the flow to
1104 // collectSingleFruVpd has been directed via
1105 // performVpdRecollection.
1106 collectSingleFruVpd(l_fruInventoryPath);
1107 }
1108 return;
1109 }
1110
1111 throw std::runtime_error(
1112 "Worker object not found can't process recollection");
1113 }
1114 catch (const std::exception& l_ex)
1115 {
1116 // TODO Log PEL
1117 logging::logMessage(
1118 "VPD recollection failed with error: " + std::string(l_ex.what()));
1119 }
1120}
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05001121} // namespace vpd