blob: 2cf8cb5c95dd50f8d6e20933016eaf60afbb84ca [file] [log] [blame]
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05001#include "config.h"
2
3#include "worker.hpp"
4
5#include "backup_restore.hpp"
6#include "configuration.hpp"
7#include "constants.hpp"
8#include "event_logger.hpp"
9#include "exceptions.hpp"
10#include "logger.hpp"
11#include "parser.hpp"
12#include "parser_factory.hpp"
13#include "parser_interface.hpp"
14
15#include <utility/dbus_utility.hpp>
16#include <utility/json_utility.hpp>
17#include <utility/vpd_specific_utility.hpp>
18
19#include <filesystem>
20#include <fstream>
21#include <future>
22#include <typeindex>
23#include <unordered_set>
24
25namespace vpd
26{
27
28Worker::Worker(std::string pathToConfigJson) :
29 m_configJsonPath(pathToConfigJson)
30{
31 // Implies the processing is based on some config JSON
32 if (!m_configJsonPath.empty())
33 {
34 // Check if symlink is already there to confirm fresh boot/factory
35 // reset.
36 if (std::filesystem::exists(INVENTORY_JSON_SYM_LINK))
37 {
38 logging::logMessage("Sym Link already present");
39 m_configJsonPath = INVENTORY_JSON_SYM_LINK;
40 m_isSymlinkPresent = true;
41 }
42
43 try
44 {
45 m_parsedJson = jsonUtility::getParsedJson(m_configJsonPath);
46
47 // check for mandatory fields at this point itself.
48 if (!m_parsedJson.contains("frus"))
49 {
50 throw std::runtime_error("Mandatory tag(s) missing from JSON");
51 }
52 }
53 catch (const std::exception& ex)
54 {
55 throw(JsonException(ex.what(), m_configJsonPath));
56 }
57 }
58 else
59 {
60 logging::logMessage("Processing in not based on any config JSON");
61 }
62}
63
64void Worker::enableMuxChips()
65{
66 if (m_parsedJson.empty())
67 {
68 // config JSON should not be empty at this point of execution.
69 throw std::runtime_error("Config JSON is empty. Can't enable muxes");
70 return;
71 }
72
73 if (!m_parsedJson.contains("muxes"))
74 {
75 logging::logMessage("No mux defined for the system in config JSON");
76 return;
77 }
78
79 // iterate over each MUX detail and enable them.
80 for (const auto& item : m_parsedJson["muxes"])
81 {
82 if (item.contains("holdidlepath"))
83 {
84 std::string cmd = "echo 0 > ";
85 cmd += item["holdidlepath"];
86
87 logging::logMessage("Enabling mux with command = " + cmd);
88
89 commonUtility::executeCmd(cmd);
90 continue;
91 }
92
93 logging::logMessage(
94 "Mux Entry does not have hold idle path. Can't enable the mux");
95 }
96}
97
98#ifdef IBM_SYSTEM
99void Worker::primeSystemBlueprint()
100{
101 if (m_parsedJson.empty())
102 {
103 return;
104 }
105
106 const nlohmann::json& l_listOfFrus =
107 m_parsedJson["frus"].get_ref<const nlohmann::json::object_t&>();
108
109 for (const auto& l_itemFRUS : l_listOfFrus.items())
110 {
111 const std::string& l_vpdFilePath = l_itemFRUS.key();
112
113 if (l_vpdFilePath == SYSTEM_VPD_FILE_PATH)
114 {
115 continue;
116 }
117
118 // Prime the inventry for FRUs which
119 // are not present/processing had some error.
120 if (!primeInventory(l_vpdFilePath))
121 {
122 logging::logMessage(
123 "Priming of inventory failed for FRU " + l_vpdFilePath);
124 }
125 }
126}
127
128void Worker::performInitialSetup()
129{
130 try
131 {
132 if (!dbusUtility::isChassisPowerOn())
133 {
134 logging::logMessage("Chassis is in Off state.");
135 setDeviceTreeAndJson();
136 primeSystemBlueprint();
137 }
138
139 // Enable all mux which are used for connecting to the i2c on the
140 // pcie slots for pcie cards. These are not enabled by kernel due to
141 // an issue seen with Castello cards, where the i2c line hangs on a
142 // probe.
143 enableMuxChips();
144
145 // Nothing needs to be done. Service restarted or BMC re-booted for
146 // some reason at system power on.
147 return;
148 }
149 catch (const std::exception& ex)
150 {
151 if (typeid(ex) == std::type_index(typeid(DataException)))
152 {
153 // TODO:Catch logic to be implemented once PEL code goes in.
154 }
155 else if (typeid(ex) == std::type_index(typeid(EccException)))
156 {
157 // TODO:Catch logic to be implemented once PEL code goes in.
158 }
159 else if (typeid(ex) == std::type_index(typeid(JsonException)))
160 {
161 // TODO:Catch logic to be implemented once PEL code goes in.
162 }
163
164 logging::logMessage(ex.what());
165 throw;
166 }
167}
168#endif
169
170static std::string readFitConfigValue()
171{
172 std::vector<std::string> output =
173 commonUtility::executeCmd("/sbin/fw_printenv");
174 std::string fitConfigValue;
175
176 for (const auto& entry : output)
177 {
178 auto pos = entry.find("=");
179 auto key = entry.substr(0, pos);
180 if (key != "fitconfig")
181 {
182 continue;
183 }
184
185 if (pos + 1 < entry.size())
186 {
187 fitConfigValue = entry.substr(pos + 1);
188 }
189 }
190
191 return fitConfigValue;
192}
193
194bool Worker::isSystemVPDOnDBus() const
195{
196 const std::string& mboardPath =
197 m_parsedJson["frus"][SYSTEM_VPD_FILE_PATH].at(0).value(
198 "inventoryPath", "");
199
200 if (mboardPath.empty())
201 {
202 throw JsonException("System vpd file path missing in JSON",
203 INVENTORY_JSON_SYM_LINK);
204 }
205
206 std::array<const char*, 1> interfaces = {
207 "xyz.openbmc_project.Inventory.Item.Board.Motherboard"};
208
209 const types::MapperGetObject& objectMap =
210 dbusUtility::getObjectMap(mboardPath, interfaces);
211
212 if (objectMap.empty())
213 {
214 return false;
215 }
216 return true;
217}
218
219std::string Worker::getIMValue(const types::IPZVpdMap& parsedVpd) const
220{
221 if (parsedVpd.empty())
222 {
223 throw std::runtime_error("Empty VPD map. Can't Extract IM value");
224 }
225
226 const auto& itrToVSBP = parsedVpd.find("VSBP");
227 if (itrToVSBP == parsedVpd.end())
228 {
229 throw DataException("VSBP record missing.");
230 }
231
232 const auto& itrToIM = (itrToVSBP->second).find("IM");
233 if (itrToIM == (itrToVSBP->second).end())
234 {
235 throw DataException("IM keyword missing.");
236 }
237
238 types::BinaryVector imVal;
239 std::copy(itrToIM->second.begin(), itrToIM->second.end(),
240 back_inserter(imVal));
241
242 std::ostringstream imData;
243 for (auto& aByte : imVal)
244 {
245 imData << std::setw(2) << std::setfill('0') << std::hex
246 << static_cast<int>(aByte);
247 }
248
249 return imData.str();
250}
251
252std::string Worker::getHWVersion(const types::IPZVpdMap& parsedVpd) const
253{
254 if (parsedVpd.empty())
255 {
256 throw std::runtime_error("Empty VPD map. Can't Extract HW value");
257 }
258
259 const auto& itrToVINI = parsedVpd.find("VINI");
260 if (itrToVINI == parsedVpd.end())
261 {
262 throw DataException("VINI record missing.");
263 }
264
265 const auto& itrToHW = (itrToVINI->second).find("HW");
266 if (itrToHW == (itrToVINI->second).end())
267 {
268 throw DataException("HW keyword missing.");
269 }
270
271 types::BinaryVector hwVal;
272 std::copy(itrToHW->second.begin(), itrToHW->second.end(),
273 back_inserter(hwVal));
274
275 // The planar pass only comes from the LSB of the HW keyword,
276 // where as the MSB is used for other purposes such as signifying clock
277 // termination.
278 hwVal[0] = 0x00;
279
280 std::ostringstream hwString;
281 for (auto& aByte : hwVal)
282 {
283 hwString << std::setw(2) << std::setfill('0') << std::hex
284 << static_cast<int>(aByte);
285 }
286
287 return hwString.str();
288}
289
290void Worker::fillVPDMap(const std::string& vpdFilePath,
291 types::VPDMapVariant& vpdMap)
292{
293 logging::logMessage(std::string("Parsing file = ") + vpdFilePath);
294
295 if (vpdFilePath.empty())
296 {
297 throw std::runtime_error("Invalid file path passed to fillVPDMap API.");
298 }
299
300 if (!std::filesystem::exists(vpdFilePath))
301 {
302 throw std::runtime_error("Can't Find physical file");
303 }
304
305 try
306 {
307 std::shared_ptr<Parser> vpdParser =
308 std::make_shared<Parser>(vpdFilePath, m_parsedJson);
309 vpdMap = vpdParser->parse();
310 }
311 catch (const std::exception& ex)
312 {
313 if (typeid(ex) == std::type_index(typeid(DataException)))
314 {
315 // TODO: Do what needs to be done in case of Data exception.
316 // Uncomment when PEL implementation goes in.
317 /* string errorMsg =
318 "VPD file is either empty or invalid. Parser failed for [";
319 errorMsg += m_vpdFilePath;
320 errorMsg += "], with error = " + std::string(ex.what());
321
322 additionalData.emplace("DESCRIPTION", errorMsg);
323 additionalData.emplace("CALLOUT_INVENTORY_PATH",
324 INVENTORY_PATH + baseFruInventoryPath);
325 createPEL(additionalData, pelSeverity, errIntfForInvalidVPD,
326 nullptr);*/
327
328 // throw generic error from here to inform main caller about
329 // failure.
330 logging::logMessage(ex.what());
331 throw std::runtime_error(
332 "Data Exception occurred for file path = " + vpdFilePath);
333 }
334
335 if (typeid(ex) == std::type_index(typeid(EccException)))
336 {
337 // TODO: Do what needs to be done in case of ECC exception.
338 // Uncomment when PEL implementation goes in.
339 /* additionalData.emplace("DESCRIPTION", "ECC check failed");
340 additionalData.emplace("CALLOUT_INVENTORY_PATH",
341 INVENTORY_PATH + baseFruInventoryPath);
342 createPEL(additionalData, pelSeverity, errIntfForEccCheckFail,
343 nullptr);
344 */
345
346 logging::logMessage(ex.what());
347 // Need to decide once all error handling is implemented.
348 // vpdSpecificUtility::dumpBadVpd(vpdFilePath,vpdVector);
349
350 // throw generic error from here to inform main caller about
351 // failure.
352 throw std::runtime_error(
353 "Ecc Exception occurred for file path = " + vpdFilePath);
354 }
355 }
356}
357
358void Worker::getSystemJson(std::string& systemJson,
359 const types::VPDMapVariant& parsedVpdMap)
360{
361 if (auto pVal = std::get_if<types::IPZVpdMap>(&parsedVpdMap))
362 {
363 std::string hwKWdValue = getHWVersion(*pVal);
364 if (hwKWdValue.empty())
365 {
366 throw DataException("HW value fetched is empty.");
367 }
368
369 const std::string& imKwdValue = getIMValue(*pVal);
370 if (imKwdValue.empty())
371 {
372 throw DataException("IM value fetched is empty.");
373 }
374
375 auto itrToIM = config::systemType.find(imKwdValue);
376 if (itrToIM == config::systemType.end())
377 {
378 throw DataException("IM keyword does not map to any system type");
379 }
380
381 const types::HWVerList hwVersionList = itrToIM->second.second;
382 if (!hwVersionList.empty())
383 {
384 transform(hwKWdValue.begin(), hwKWdValue.end(), hwKWdValue.begin(),
385 ::toupper);
386
387 auto itrToHW =
388 std::find_if(hwVersionList.begin(), hwVersionList.end(),
389 [&hwKWdValue](const auto& aPair) {
390 return aPair.first == hwKWdValue;
391 });
392
393 if (itrToHW != hwVersionList.end())
394 {
395 if (!(*itrToHW).second.empty())
396 {
397 systemJson += (*itrToIM).first + "_" + (*itrToHW).second +
398 ".json";
399 }
400 else
401 {
402 systemJson += (*itrToIM).first + ".json";
403 }
404 return;
405 }
406 }
407 systemJson += itrToIM->second.first + ".json";
408 return;
409 }
410
411 throw DataException("Invalid VPD type returned from Parser");
412}
413
414static void setEnvAndReboot(const std::string& key, const std::string& value)
415{
416 // set env and reboot and break.
417 commonUtility::executeCmd("/sbin/fw_setenv", key, value);
418 logging::logMessage("Rebooting BMC to pick up new device tree");
419
420 // make dbus call to reboot
421 auto bus = sdbusplus::bus::new_default_system();
422 auto method = bus.new_method_call(
423 "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
424 "org.freedesktop.systemd1.Manager", "Reboot");
425 bus.call_noreply(method);
426}
427
428void Worker::setJsonSymbolicLink(const std::string& i_systemJson)
429{
430 std::error_code l_ec;
431 l_ec.clear();
432 if (!std::filesystem::exists(VPD_SYMLIMK_PATH, l_ec))
433 {
434 if (l_ec)
435 {
436 throw std::runtime_error(
437 "File system call to exist failed with error = " +
438 l_ec.message());
439 }
440
441 // implies it is a fresh boot/factory reset.
442 // Create the directory for hosting the symlink
443 if (!std::filesystem::create_directories(VPD_SYMLIMK_PATH, l_ec))
444 {
445 if (l_ec)
446 {
447 throw std::runtime_error(
448 "File system call to create directory failed with error = " +
449 l_ec.message());
450 }
451 }
452 }
453
454 // create a new symlink based on the system
455 std::filesystem::create_symlink(i_systemJson, INVENTORY_JSON_SYM_LINK,
456 l_ec);
457
458 if (l_ec)
459 {
460 throw std::runtime_error(
461 "create_symlink system call failed with error: " + l_ec.message());
462 }
463
464 // If the flow is at this point implies the symlink was not present there.
465 // Considering this as factory reset.
466 m_isFactoryResetDone = true;
467}
468
469void Worker::setDeviceTreeAndJson()
470{
471 // JSON is madatory for processing of this API.
472 if (m_parsedJson.empty())
473 {
474 throw std::runtime_error("JSON is empty");
475 }
476
477 types::VPDMapVariant parsedVpdMap;
478 fillVPDMap(SYSTEM_VPD_FILE_PATH, parsedVpdMap);
479
480 // Implies it is default JSON.
481 std::string systemJson{JSON_ABSOLUTE_PATH_PREFIX};
482
483 // ToDo: Need to check if INVENTORY_JSON_SYM_LINK pointing to correct system
484 // This is required to support movement from rainier to Blue Ridge on the
485 // fly.
486
487 // Do we have the entry for device tree in parsed JSON?
488 if (m_parsedJson.find("devTree") == m_parsedJson.end())
489 {
490 getSystemJson(systemJson, parsedVpdMap);
491
492 if (!systemJson.compare(JSON_ABSOLUTE_PATH_PREFIX))
493 {
494 // TODO: Log a PEL saying that "System type not supported"
495 throw DataException("Error in getting system JSON.");
496 }
497
498 // re-parse the JSON once appropriate JSON has been selected.
499 try
500 {
501 m_parsedJson = jsonUtility::getParsedJson(systemJson);
502 }
503 catch (const nlohmann::json::parse_error& ex)
504 {
505 throw(JsonException("Json parsing failed", systemJson));
506 }
507 }
508
509 std::string devTreeFromJson;
510 if (m_parsedJson.contains("devTree"))
511 {
512 devTreeFromJson = m_parsedJson["devTree"];
513
514 if (devTreeFromJson.empty())
515 {
516 // TODO:: Log a predictive PEL
517 logging::logMessage(
518 "Mandatory value for device tree missing from JSON[" +
519 std::string(INVENTORY_JSON_SYM_LINK) + "]");
520 }
521 }
522
523 auto fitConfigVal = readFitConfigValue();
524
525 if (devTreeFromJson.empty() ||
526 fitConfigVal.find(devTreeFromJson) != std::string::npos)
527 { // Skipping setting device tree as either devtree info is missing from
528 // Json or it is rightly set.
529
530 // avoid setting symlink on every reboot.
531 if (!m_isSymlinkPresent)
532 {
533 setJsonSymbolicLink(systemJson);
534 }
535
536 if (isSystemVPDOnDBus() &&
537 jsonUtility::isBackupAndRestoreRequired(m_parsedJson))
538 {
539 performBackupAndRestore(parsedVpdMap);
540 }
541
542 // proceed to publish system VPD.
543 publishSystemVPD(parsedVpdMap);
544 return;
545 }
546
547 setEnvAndReboot("fitconfig", devTreeFromJson);
548 exit(EXIT_SUCCESS);
549}
550
551void Worker::populateIPZVPDpropertyMap(
552 types::InterfaceMap& interfacePropMap,
553 const types::IPZKwdValueMap& keyordValueMap,
554 const std::string& interfaceName)
555{
556 types::PropertyMap propertyValueMap;
557 for (const auto& kwdVal : keyordValueMap)
558 {
559 auto kwd = kwdVal.first;
560
561 if (kwd[0] == '#')
562 {
563 kwd = std::string("PD_") + kwd[1];
564 }
565 else if (isdigit(kwd[0]))
566 {
567 kwd = std::string("N_") + kwd;
568 }
569
570 types::BinaryVector value(kwdVal.second.begin(), kwdVal.second.end());
571 propertyValueMap.emplace(move(kwd), move(value));
572 }
573
574 if (!propertyValueMap.empty())
575 {
576 interfacePropMap.emplace(interfaceName, propertyValueMap);
577 }
578}
579
580void Worker::populateKwdVPDpropertyMap(const types::KeywordVpdMap& keyordVPDMap,
581 types::InterfaceMap& interfaceMap)
582{
583 for (const auto& kwdValMap : keyordVPDMap)
584 {
585 types::PropertyMap propertyValueMap;
586 auto kwd = kwdValMap.first;
587
588 if (kwd[0] == '#')
589 {
590 kwd = std::string("PD_") + kwd[1];
591 }
592 else if (isdigit(kwd[0]))
593 {
594 kwd = std::string("N_") + kwd;
595 }
596
597 if (auto keywordValue = get_if<types::BinaryVector>(&kwdValMap.second))
598 {
599 types::BinaryVector value((*keywordValue).begin(),
600 (*keywordValue).end());
601 propertyValueMap.emplace(move(kwd), move(value));
602 }
603 else if (auto keywordValue = get_if<std::string>(&kwdValMap.second))
604 {
605 types::BinaryVector value((*keywordValue).begin(),
606 (*keywordValue).end());
607 propertyValueMap.emplace(move(kwd), move(value));
608 }
609 else if (auto keywordValue = get_if<size_t>(&kwdValMap.second))
610 {
611 if (kwd == "MemorySizeInKB")
612 {
613 types::PropertyMap memProp;
614 memProp.emplace(move(kwd), ((*keywordValue)));
615 interfaceMap.emplace("xyz.openbmc_project.Inventory.Item.Dimm",
616 move(memProp));
617 continue;
618 }
619 else
620 {
621 logging::logMessage(
622 "Unknown Keyword =" + kwd + " found in keyword VPD map");
623 continue;
624 }
625 }
626 else
627 {
628 logging::logMessage(
629 "Unknown variant type found in keyword VPD map.");
630 continue;
631 }
632
633 if (!propertyValueMap.empty())
634 {
635 vpdSpecificUtility::insertOrMerge(
636 interfaceMap, constants::kwdVpdInf, move(propertyValueMap));
637 }
638 }
639}
640
641void Worker::populateInterfaces(const nlohmann::json& interfaceJson,
642 types::InterfaceMap& interfaceMap,
643 const types::VPDMapVariant& parsedVpdMap)
644{
645 for (const auto& interfacesPropPair : interfaceJson.items())
646 {
647 const std::string& interface = interfacesPropPair.key();
648 types::PropertyMap propertyMap;
649
650 for (const auto& propValuePair : interfacesPropPair.value().items())
651 {
652 const std::string property = propValuePair.key();
653
654 if (propValuePair.value().is_boolean())
655 {
656 propertyMap.emplace(property,
657 propValuePair.value().get<bool>());
658 }
659 else if (propValuePair.value().is_string())
660 {
661 if (property.compare("LocationCode") == 0 &&
662 interface.compare("com.ibm.ipzvpd.Location") == 0)
663 {
664 std::string value =
665 vpdSpecificUtility::getExpandedLocationCode(
666 propValuePair.value().get<std::string>(),
667 parsedVpdMap);
668 propertyMap.emplace(property, value);
669
670 auto l_locCodeProperty = propertyMap;
671 vpdSpecificUtility::insertOrMerge(
672 interfaceMap,
673 std::string(constants::xyzLocationCodeInf),
674 move(l_locCodeProperty));
675 }
676 else
677 {
678 propertyMap.emplace(
679 property, propValuePair.value().get<std::string>());
680 }
681 }
682 else if (propValuePair.value().is_array())
683 {
684 try
685 {
686 propertyMap.emplace(
687 property,
688 propValuePair.value().get<types::BinaryVector>());
689 }
690 catch (const nlohmann::detail::type_error& e)
691 {
692 std::cerr << "Type exception: " << e.what() << "\n";
693 }
694 }
695 else if (propValuePair.value().is_number())
696 {
697 // For now assume the value is a size_t. In the future it would
698 // be nice to come up with a way to get the type from the JSON.
699 propertyMap.emplace(property,
700 propValuePair.value().get<size_t>());
701 }
702 else if (propValuePair.value().is_object())
703 {
704 const std::string& record =
705 propValuePair.value().value("recordName", "");
706 const std::string& keyword =
707 propValuePair.value().value("keywordName", "");
708 const std::string& encoding =
709 propValuePair.value().value("encoding", "");
710
711 if (auto ipzVpdMap =
712 std::get_if<types::IPZVpdMap>(&parsedVpdMap))
713 {
714 if (!record.empty() && !keyword.empty() &&
715 (*ipzVpdMap).count(record) &&
716 (*ipzVpdMap).at(record).count(keyword))
717 {
718 auto encoded = vpdSpecificUtility::encodeKeyword(
719 ((*ipzVpdMap).at(record).at(keyword)), encoding);
720 propertyMap.emplace(property, encoded);
721 }
722 }
723 else if (auto kwdVpdMap =
724 std::get_if<types::KeywordVpdMap>(&parsedVpdMap))
725 {
726 if (!keyword.empty() && (*kwdVpdMap).count(keyword))
727 {
728 if (auto kwValue = std::get_if<types::BinaryVector>(
729 &(*kwdVpdMap).at(keyword)))
730 {
731 auto encodedValue =
732 vpdSpecificUtility::encodeKeyword(
733 std::string((*kwValue).begin(),
734 (*kwValue).end()),
735 encoding);
736
737 propertyMap.emplace(property, encodedValue);
738 }
739 else if (auto kwValue = std::get_if<std::string>(
740 &(*kwdVpdMap).at(keyword)))
741 {
742 auto encodedValue =
743 vpdSpecificUtility::encodeKeyword(
744 std::string((*kwValue).begin(),
745 (*kwValue).end()),
746 encoding);
747
748 propertyMap.emplace(property, encodedValue);
749 }
750 else if (auto uintValue = std::get_if<size_t>(
751 &(*kwdVpdMap).at(keyword)))
752 {
753 propertyMap.emplace(property, *uintValue);
754 }
755 else
756 {
757 logging::logMessage(
758 "Unknown keyword found, Keywrod = " + keyword);
759 }
760 }
761 }
762 }
763 }
764 vpdSpecificUtility::insertOrMerge(interfaceMap, interface,
765 move(propertyMap));
766 }
767}
768
769bool Worker::isCPUIOGoodOnly(const std::string& i_pgKeyword)
770{
771 const unsigned char l_io[] = {
772 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF,
773 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF, 0xE7, 0xF9, 0xFF};
774
775 // EQ0 index (in PG keyword) starts at 97 (with offset starting from 0).
776 // Each EQ carries 3 bytes of data. Totally there are 8 EQs. If all EQs'
777 // value equals 0xE7F9FF, then the cpu has no good cores and its treated as
778 // IO.
779 if (memcmp(l_io, i_pgKeyword.data() + constants::INDEX_OF_EQ0_IN_PG,
780 constants::SIZE_OF_8EQ_IN_PG) == 0)
781 {
782 return true;
783 }
784
785 // The CPU is not an IO
786 return false;
787}
788
789bool Worker::primeInventory(const std::string& i_vpdFilePath)
790{
791 if (i_vpdFilePath.empty())
792 {
793 logging::logMessage("Empty VPD file path given");
794 return false;
795 }
796
797 if (m_parsedJson.empty())
798 {
799 logging::logMessage("Empty JSON detected for " + i_vpdFilePath);
800 return false;
801 }
802 else if (!m_parsedJson["frus"].contains(i_vpdFilePath))
803 {
804 logging::logMessage("File " + i_vpdFilePath +
805 ", is not found in the system config JSON file.");
806 return false;
807 }
808
809 types::ObjectMap l_objectInterfaceMap;
810 for (const auto& l_Fru : m_parsedJson["frus"][i_vpdFilePath])
811 {
812 types::InterfaceMap l_interfaces;
813 sdbusplus::message::object_path l_fruObjectPath(l_Fru["inventoryPath"]);
814
815 if (l_Fru.contains("ccin"))
816 {
817 continue;
818 }
819
820 if (l_Fru.contains("noprime") && l_Fru.value("noprime", false))
821 {
822 continue;
823 }
824
825 // Clear data under PIM if already exists.
826 vpdSpecificUtility::resetDataUnderPIM(
827 std::string(l_Fru["inventoryPath"]), l_interfaces);
828
829 // Add extra interfaces mentioned in the Json config file
830 if (l_Fru.contains("extraInterfaces"))
831 {
832 populateInterfaces(l_Fru["extraInterfaces"], l_interfaces,
833 std::monostate{});
834 }
835
836 types::PropertyMap l_propertyValueMap;
837 l_propertyValueMap.emplace("Present", false);
838 if (std::filesystem::exists(i_vpdFilePath))
839 {
840 l_propertyValueMap["Present"] = true;
841 }
842
843 vpdSpecificUtility::insertOrMerge(l_interfaces,
844 "xyz.openbmc_project.Inventory.Item",
845 move(l_propertyValueMap));
846
847 if (l_Fru.value("inherit", true) &&
848 m_parsedJson.contains("commonInterfaces"))
849 {
850 populateInterfaces(m_parsedJson["commonInterfaces"], l_interfaces,
851 std::monostate{});
852 }
853
854 processFunctionalProperty(l_Fru["inventoryPath"], l_interfaces);
855 processEnabledProperty(l_Fru["inventoryPath"], l_interfaces);
856
857 l_objectInterfaceMap.emplace(std::move(l_fruObjectPath),
858 std::move(l_interfaces));
859 }
860
861 // Notify PIM
862 if (!dbusUtility::callPIM(move(l_objectInterfaceMap)))
863 {
864 logging::logMessage("Call to PIM failed for VPD file " + i_vpdFilePath);
865 return false;
866 }
867
868 return true;
869}
870
871void Worker::processEmbeddedAndSynthesizedFrus(const nlohmann::json& singleFru,
872 types::InterfaceMap& interfaces)
873{
874 // embedded property(true or false) says whether the subfru is embedded
875 // into the parent fru (or) not. VPD sets Present property only for
876 // embedded frus. If the subfru is not an embedded FRU, the subfru may
877 // or may not be physically present. Those non embedded frus will always
878 // have Present=false irrespective of its physical presence or absence.
879 // Eg: nvme drive in nvme slot is not an embedded FRU. So don't set
880 // Present to true for such sub frus.
881 // Eg: ethernet port is embedded into bmc card. So set Present to true
882 // for such sub frus. Also donot populate present property for embedded
883 // subfru which is synthesized. Currently there is no subfru which are
884 // both embedded and synthesized. But still the case is handled here.
885
886 // Check if its required to handle presence for this FRU.
887 if (singleFru.value("handlePresence", true))
888 {
889 types::PropertyMap presProp;
890 presProp.emplace("Present", true);
891 vpdSpecificUtility::insertOrMerge(
892 interfaces, "xyz.openbmc_project.Inventory.Item", move(presProp));
893 }
894}
895
896void Worker::processExtraInterfaces(const nlohmann::json& singleFru,
897 types::InterfaceMap& interfaces,
898 const types::VPDMapVariant& parsedVpdMap)
899{
900 populateInterfaces(singleFru["extraInterfaces"], interfaces, parsedVpdMap);
901 if (auto ipzVpdMap = std::get_if<types::IPZVpdMap>(&parsedVpdMap))
902 {
903 if (singleFru["extraInterfaces"].contains(
904 "xyz.openbmc_project.Inventory.Item.Cpu"))
905 {
906 auto itrToRec = (*ipzVpdMap).find("CP00");
907 if (itrToRec == (*ipzVpdMap).end())
908 {
909 return;
910 }
911
912 std::string pgKeywordValue;
913 vpdSpecificUtility::getKwVal(itrToRec->second, "PG",
914 pgKeywordValue);
915 if (!pgKeywordValue.empty())
916 {
917 if (isCPUIOGoodOnly(pgKeywordValue))
918 {
919 interfaces["xyz.openbmc_project.Inventory.Item"]
920 ["PrettyName"] = "IO Module";
921 }
922 }
923 }
924 }
925}
926
927void Worker::processCopyRecordFlag(const nlohmann::json& singleFru,
928 const types::VPDMapVariant& parsedVpdMap,
929 types::InterfaceMap& interfaces)
930{
931 if (auto ipzVpdMap = std::get_if<types::IPZVpdMap>(&parsedVpdMap))
932 {
933 for (const auto& record : singleFru["copyRecords"])
934 {
935 const std::string& recordName = record;
936 if ((*ipzVpdMap).find(recordName) != (*ipzVpdMap).end())
937 {
938 populateIPZVPDpropertyMap(interfaces,
939 (*ipzVpdMap).at(recordName),
940 constants::ipzVpdInf + recordName);
941 }
942 }
943 }
944}
945
946void Worker::processInheritFlag(const types::VPDMapVariant& parsedVpdMap,
947 types::InterfaceMap& interfaces)
948{
949 if (auto ipzVpdMap = std::get_if<types::IPZVpdMap>(&parsedVpdMap))
950 {
951 for (const auto& [recordName, kwdValueMap] : *ipzVpdMap)
952 {
953 populateIPZVPDpropertyMap(interfaces, kwdValueMap,
954 constants::ipzVpdInf + recordName);
955 }
956 }
957 else if (auto kwdVpdMap = std::get_if<types::KeywordVpdMap>(&parsedVpdMap))
958 {
959 populateKwdVPDpropertyMap(*kwdVpdMap, interfaces);
960 }
961
962 if (m_parsedJson.contains("commonInterfaces"))
963 {
964 populateInterfaces(m_parsedJson["commonInterfaces"], interfaces,
965 parsedVpdMap);
966 }
967}
968
969bool Worker::processFruWithCCIN(const nlohmann::json& singleFru,
970 const types::VPDMapVariant& parsedVpdMap)
971{
972 if (auto ipzVPDMap = std::get_if<types::IPZVpdMap>(&parsedVpdMap))
973 {
974 auto itrToRec = (*ipzVPDMap).find("VINI");
975 if (itrToRec == (*ipzVPDMap).end())
976 {
977 return false;
978 }
979
980 std::string ccinFromVpd;
981 vpdSpecificUtility::getKwVal(itrToRec->second, "CC", ccinFromVpd);
982 if (ccinFromVpd.empty())
983 {
984 return false;
985 }
986
987 transform(ccinFromVpd.begin(), ccinFromVpd.end(), ccinFromVpd.begin(),
988 ::toupper);
989
990 std::vector<std::string> ccinList;
991 for (std::string ccin : singleFru["ccin"])
992 {
993 transform(ccin.begin(), ccin.end(), ccin.begin(), ::toupper);
994 ccinList.push_back(ccin);
995 }
996
997 if (ccinList.empty())
998 {
999 return false;
1000 }
1001
1002 if (find(ccinList.begin(), ccinList.end(), ccinFromVpd) ==
1003 ccinList.end())
1004 {
1005 return false;
1006 }
1007 }
1008 return true;
1009}
1010
1011void Worker::processFunctionalProperty(const std::string& i_inventoryObjPath,
1012 types::InterfaceMap& io_interfaces)
1013{
1014 if (!dbusUtility::isChassisPowerOn())
1015 {
1016 std::array<const char*, 1> l_operationalStatusInf = {
1017 constants::operationalStatusInf};
1018
1019 auto mapperObjectMap = dbusUtility::getObjectMap(
1020 i_inventoryObjPath, l_operationalStatusInf);
1021
1022 // If the object has been found. Check if it is under PIM.
1023 if (mapperObjectMap.size() != 0)
1024 {
1025 for (const auto& [l_serviceName, l_interfaceLsit] : mapperObjectMap)
1026 {
1027 if (l_serviceName == constants::pimServiceName)
1028 {
1029 // The object is already under PIM. No need to process
1030 // again. Retain the old value.
1031 return;
1032 }
1033 }
1034 }
1035
1036 // Implies value is not there in D-Bus. Populate it with default
1037 // value "true".
1038 types::PropertyMap l_functionalProp;
1039 l_functionalProp.emplace("Functional", true);
1040 vpdSpecificUtility::insertOrMerge(io_interfaces,
1041 constants::operationalStatusInf,
1042 move(l_functionalProp));
1043 }
1044
1045 // if chassis is power on. Functional property should be there on D-Bus.
1046 // Don't process.
1047 return;
1048}
1049
1050void Worker::processEnabledProperty(const std::string& i_inventoryObjPath,
1051 types::InterfaceMap& io_interfaces)
1052{
1053 if (!dbusUtility::isChassisPowerOn())
1054 {
1055 std::array<const char*, 1> l_enableInf = {constants::enableInf};
1056
1057 auto mapperObjectMap =
1058 dbusUtility::getObjectMap(i_inventoryObjPath, l_enableInf);
1059
1060 // If the object has been found. Check if it is under PIM.
1061 if (mapperObjectMap.size() != 0)
1062 {
1063 for (const auto& [l_serviceName, l_interfaceLsit] : mapperObjectMap)
1064 {
1065 if (l_serviceName == constants::pimServiceName)
1066 {
1067 // The object is already under PIM. No need to process
1068 // again. Retain the old value.
1069 return;
1070 }
1071 }
1072 }
1073
1074 // Implies value is not there in D-Bus. Populate it with default
1075 // value "true".
1076 types::PropertyMap l_enabledProp;
1077 l_enabledProp.emplace("Enabled", true);
1078 vpdSpecificUtility::insertOrMerge(io_interfaces, constants::enableInf,
1079 move(l_enabledProp));
1080 }
1081
1082 // if chassis is power on. Enabled property should be there on D-Bus.
1083 // Don't process.
1084 return;
1085}
1086
1087void Worker::populateDbus(const types::VPDMapVariant& parsedVpdMap,
1088 types::ObjectMap& objectInterfaceMap,
1089 const std::string& vpdFilePath)
1090{
1091 if (vpdFilePath.empty())
1092 {
1093 throw std::runtime_error(
1094 "Invalid parameter passed to populateDbus API.");
1095 }
1096
1097 // JSON config is mandatory for processing of "if". Add "else" for any
1098 // processing without config JSON.
1099 if (!m_parsedJson.empty())
1100 {
1101 types::InterfaceMap interfaces;
1102
1103 for (const auto& aFru : m_parsedJson["frus"][vpdFilePath])
1104 {
1105 const auto& inventoryPath = aFru["inventoryPath"];
1106 sdbusplus::message::object_path fruObjectPath(inventoryPath);
1107 if (aFru.contains("ccin"))
1108 {
1109 if (!processFruWithCCIN(aFru, parsedVpdMap))
1110 {
1111 continue;
1112 }
1113 }
1114
1115 if (aFru.value("inherit", true))
1116 {
1117 processInheritFlag(parsedVpdMap, interfaces);
1118 }
1119
1120 // If specific record needs to be copied.
1121 if (aFru.contains("copyRecords"))
1122 {
1123 processCopyRecordFlag(aFru, parsedVpdMap, interfaces);
1124 }
1125
1126 if (aFru.contains("extraInterfaces"))
1127 {
1128 // Process extra interfaces w.r.t a FRU.
1129 processExtraInterfaces(aFru, interfaces, parsedVpdMap);
1130 }
1131
1132 // Process FRUS which are embedded in the parent FRU and whose VPD
1133 // will be synthesized.
1134 if ((aFru.value("embedded", true)) &&
1135 (!aFru.value("synthesized", false)))
1136 {
1137 processEmbeddedAndSynthesizedFrus(aFru, interfaces);
1138 }
1139
1140 processFunctionalProperty(inventoryPath, interfaces);
1141 processEnabledProperty(inventoryPath, interfaces);
1142
1143 objectInterfaceMap.emplace(std::move(fruObjectPath),
1144 std::move(interfaces));
1145 }
1146 }
1147}
1148
1149std::string
1150 Worker::createAssetTagString(const types::VPDMapVariant& i_parsedVpdMap)
1151{
1152 std::string l_assetTag;
1153
1154 // system VPD will be in IPZ format.
1155 if (auto l_parsedVpdMap = std::get_if<types::IPZVpdMap>(&i_parsedVpdMap))
1156 {
1157 auto l_itrToVsys = (*l_parsedVpdMap).find(constants::recVSYS);
1158 if (l_itrToVsys != (*l_parsedVpdMap).end())
1159 {
1160 std::string l_tmKwdValue;
1161 vpdSpecificUtility::getKwVal(l_itrToVsys->second, constants::kwdTM,
1162 l_tmKwdValue);
1163
1164 std::string l_seKwdValue;
1165 vpdSpecificUtility::getKwVal(l_itrToVsys->second, constants::kwdSE,
1166 l_seKwdValue);
1167
1168 l_assetTag = std::string{"Server-"} + l_tmKwdValue +
1169 std::string{"-"} + l_seKwdValue;
1170 }
1171 else
1172 {
1173 throw std::runtime_error(
1174 "VSYS record not found in parsed VPD map to create Asset tag.");
1175 }
1176 }
1177 else
1178 {
1179 throw std::runtime_error(
1180 "Invalid VPD type recieved to create Asset tag.");
1181 }
1182
1183 return l_assetTag;
1184}
1185
1186void Worker::publishSystemVPD(const types::VPDMapVariant& parsedVpdMap)
1187{
1188 types::ObjectMap objectInterfaceMap;
1189
1190 if (std::get_if<types::IPZVpdMap>(&parsedVpdMap))
1191 {
1192 populateDbus(parsedVpdMap, objectInterfaceMap, SYSTEM_VPD_FILE_PATH);
1193
1194 try
1195 {
1196 if (m_isFactoryResetDone)
1197 {
1198 const auto& l_assetTag = createAssetTagString(parsedVpdMap);
1199
1200 auto l_itrToSystemPath = objectInterfaceMap.find(
1201 sdbusplus::message::object_path(constants::systemInvPath));
1202 if (l_itrToSystemPath == objectInterfaceMap.end())
1203 {
1204 throw std::runtime_error(
1205 "System Path not found in object map.");
1206 }
1207
1208 types::PropertyMap l_assetTagProperty;
1209 l_assetTagProperty.emplace("AssetTag", l_assetTag);
1210
1211 (l_itrToSystemPath->second)
1212 .emplace(constants::assetTagInf,
1213 std::move(l_assetTagProperty));
1214 }
1215 }
1216 catch (const std::exception& l_ex)
1217 {
1218 EventLogger::createSyncPel(
1219 types::ErrorType::InvalidVpdMessage,
1220 types::SeverityType::Informational, __FILE__, __FUNCTION__, 0,
1221 "Asset tag update failed with following error: " +
1222 std::string(l_ex.what()),
1223 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
1224 }
1225
1226 // Notify PIM
1227 if (!dbusUtility::callPIM(move(objectInterfaceMap)))
1228 {
1229 throw std::runtime_error("Call to PIM failed for system VPD");
1230 }
1231 }
1232 else
1233 {
1234 throw DataException("Invalid format of parsed VPD map.");
1235 }
1236}
1237
1238bool Worker::processPreAction(const std::string& i_vpdFilePath,
1239 const std::string& i_flagToProcess)
1240{
1241 if (i_vpdFilePath.empty() || i_flagToProcess.empty())
1242 {
1243 logging::logMessage(
1244 "Invalid input parameter. Abort processing pre action");
1245 return false;
1246 }
1247
1248 if ((!jsonUtility::executeBaseAction(m_parsedJson, "preAction",
1249 i_vpdFilePath, i_flagToProcess)) &&
1250 (i_flagToProcess.compare("collection") == constants::STR_CMP_SUCCESS))
1251 {
1252 // TODO: Need a way to delete inventory object from Dbus and persisted
1253 // data section in case any FRU is not present or there is any
1254 // problem in collecting it. Once it has been deleted, it can be
1255 // re-created in the flow of priming the inventory. This needs to be
1256 // done either here or in the exception section of "parseAndPublishVPD"
1257 // API. Any failure in the process of collecting FRU will land up in the
1258 // excpetion of "parseAndPublishVPD".
1259
1260 // If the FRU is not there, clear the VINI/CCIN data.
1261 // Enity manager probes for this keyword to look for this
1262 // FRU, now if the data is persistent on BMC and FRU is
1263 // removed this can lead to ambiguity. Hence clearing this
1264 // Keyword if FRU is absent.
1265 const auto& inventoryPath =
1266 m_parsedJson["frus"][i_vpdFilePath].at(0).value("inventoryPath",
1267 "");
1268
1269 if (!inventoryPath.empty())
1270 {
1271 types::ObjectMap l_pimObjMap{
1272 {inventoryPath,
1273 {{constants::kwdVpdInf,
1274 {{constants::kwdCCIN, types::BinaryVector{}}}}}}};
1275
1276 if (!dbusUtility::callPIM(std::move(l_pimObjMap)))
1277 {
1278 logging::logMessage(
1279 "Call to PIM failed for file " + i_vpdFilePath);
1280 }
1281 }
1282 else
1283 {
1284 logging::logMessage(
1285 "Inventory path is empty in Json for file " + i_vpdFilePath);
1286 }
1287
1288 return false;
1289 }
1290 return true;
1291}
1292
1293bool Worker::processPostAction(
1294 const std::string& i_vpdFruPath, const std::string& i_flagToProcess,
1295 const std::optional<types::VPDMapVariant> i_parsedVpd)
1296{
1297 if (i_vpdFruPath.empty() || i_flagToProcess.empty())
1298 {
1299 logging::logMessage(
1300 "Invalid input parameter. Abort processing post action");
1301 return false;
1302 }
1303
1304 // Check if post action tag is to be triggered in the flow of collection
1305 // based on some CCIN value?
1306 if (m_parsedJson["frus"][i_vpdFruPath]
1307 .at(0)["postAction"][i_flagToProcess]
1308 .contains("ccin"))
1309 {
1310 if (!i_parsedVpd.has_value())
1311 {
1312 logging::logMessage("Empty VPD Map");
1313 return false;
1314 }
1315
1316 // CCIN match is required to process post action for this FRU as it
1317 // contains the flag.
1318 if (!vpdSpecificUtility::findCcinInVpd(
1319 m_parsedJson["frus"][i_vpdFruPath].at(
1320 0)["postAction"]["collection"],
1321 i_parsedVpd.value()))
1322 {
1323 // If CCIN is not found, implies post action processing is not
1324 // required for this FRU. Let the flow continue.
1325 return true;
1326 }
1327 }
1328
1329 if (!jsonUtility::executeBaseAction(m_parsedJson, "postAction",
1330 i_vpdFruPath, i_flagToProcess))
1331 {
1332 logging::logMessage(
1333 "Execution of post action failed for path: " + i_vpdFruPath);
1334
1335 // If post action was required and failed only in that case return
1336 // false. In all other case post action is considered passed.
1337 return false;
1338 }
1339
1340 return true;
1341}
1342
1343types::VPDMapVariant Worker::parseVpdFile(const std::string& i_vpdFilePath)
1344{
1345 if (i_vpdFilePath.empty())
1346 {
1347 throw std::runtime_error(
1348 "Empty VPD file path passed to Worker::parseVpdFile. Abort processing");
1349 }
1350
1351 try
1352 {
1353 if (jsonUtility::isActionRequired(m_parsedJson, i_vpdFilePath,
1354 "preAction", "collection"))
1355 {
1356 if (!processPreAction(i_vpdFilePath, "collection"))
1357 {
1358 throw std::runtime_error("Pre-Action failed");
1359 }
1360 }
1361
1362 if (!std::filesystem::exists(i_vpdFilePath))
1363 {
1364 throw std::runtime_error(
1365 "Could not find file path " + i_vpdFilePath +
1366 "Skipping parser trigger for the EEPROM");
1367 }
1368
1369 std::shared_ptr<Parser> vpdParser =
1370 std::make_shared<Parser>(i_vpdFilePath, m_parsedJson);
1371
1372 types::VPDMapVariant l_parsedVpd = vpdParser->parse();
1373
1374 // Before returning, as collection is over, check if FRU qualifies for
1375 // any post action in the flow of collection.
1376 // Note: Don't change the order, post action needs to be processed only
1377 // after collection for FRU is successfully done.
1378 if (jsonUtility::isActionRequired(m_parsedJson, i_vpdFilePath,
1379 "postAction", "collection"))
1380 {
1381 if (!processPostAction(i_vpdFilePath, "collection", l_parsedVpd))
1382 {
1383 // TODO: Log PEL
1384 logging::logMessage("Required post action failed for path [" +
1385 i_vpdFilePath + "]");
1386 }
1387 }
1388
1389 return l_parsedVpd;
1390 }
1391 catch (std::exception& l_ex)
1392 {
1393 // If post fail action is required, execute it.
1394 if (jsonUtility::isActionRequired(m_parsedJson, i_vpdFilePath,
1395 "PostFailAction", "collection"))
1396 {
1397 if (!jsonUtility::executePostFailAction(m_parsedJson, i_vpdFilePath,
1398 "collection"))
1399 {
1400 // TODO: Log PEL
1401 throw std::runtime_error(
1402 "VPD parsing failed for " + i_vpdFilePath +
1403 " due to error: " + l_ex.what() +
1404 ". Post Fail Action also failed, aborting collection for this FRU");
1405 }
1406 }
1407
1408 // TODO: Log PEL
1409 throw std::runtime_error("VPD parsing failed for " + i_vpdFilePath +
1410 " due to error: " + l_ex.what());
1411 }
1412}
1413
1414std::tuple<bool, std::string>
1415 Worker::parseAndPublishVPD(const std::string& i_vpdFilePath)
1416{
1417 try
1418 {
1419 m_semaphore.acquire();
1420
1421 // Thread launched.
1422 m_mutex.lock();
1423 m_activeCollectionThreadCount++;
1424 m_mutex.unlock();
1425
1426 const types::VPDMapVariant& parsedVpdMap = parseVpdFile(i_vpdFilePath);
1427
1428 types::ObjectMap objectInterfaceMap;
1429 populateDbus(parsedVpdMap, objectInterfaceMap, i_vpdFilePath);
1430
1431 // logging::logMessage("Dbus sucessfully populated for FRU " +
1432 // i_vpdFilePath);
1433
1434 // Notify PIM
1435 if (!dbusUtility::callPIM(move(objectInterfaceMap)))
1436 {
1437 throw std::runtime_error(
1438 "Call to PIM failed while publishing VPD.");
1439 }
1440 }
1441 catch (const std::exception& ex)
1442 {
1443 // handle all the exceptions internally. Return only true/false
1444 // based on status of execution.
1445 if (typeid(ex) == std::type_index(typeid(DataException)))
1446 {
1447 // TODO: Add custom handling
1448 logging::logMessage(ex.what());
1449 }
1450 else if (typeid(ex) == std::type_index(typeid(EccException)))
1451 {
1452 // TODO: Add custom handling
1453 logging::logMessage(ex.what());
1454 }
1455 else if (typeid(ex) == std::type_index(typeid(JsonException)))
1456 {
1457 // TODO: Add custom handling
1458 logging::logMessage(ex.what());
1459 }
1460 else
1461 {
1462 logging::logMessage(ex.what());
1463 }
1464
1465 // TODO: Figure out a way to clear data in case of any failure at
1466 // runtime.
1467 // Prime the inventry for FRUs which
1468 // are not present/processing had some error.
1469 /* if (!primeInventory(i_vpdFilePath))
1470 {
1471 logging::logMessage("Priming of inventory failed for FRU " +
1472 i_vpdFilePath);
1473 }*/
1474 m_semaphore.release();
1475 return std::make_tuple(false, i_vpdFilePath);
1476 }
1477 m_semaphore.release();
1478 return std::make_tuple(true, i_vpdFilePath);
1479}
1480
1481void Worker::collectFrusFromJson()
1482{
1483 // A parsed JSON file should be present to pick FRUs EEPROM paths
1484 if (m_parsedJson.empty())
1485 {
1486 throw std::runtime_error(
1487 "A config JSON is required for processing of FRUs");
1488 }
1489
1490 const nlohmann::json& listOfFrus =
1491 m_parsedJson["frus"].get_ref<const nlohmann::json::object_t&>();
1492
1493 for (const auto& itemFRUS : listOfFrus.items())
1494 {
1495 const std::string& vpdFilePath = itemFRUS.key();
1496
1497 // skip processing of system VPD again as it has been already collected.
1498 // Also, if chassis is powered on, skip collecting FRUs which are
1499 // powerOffOnly.
1500 // TODO: Need to revisit for P-Future to reduce code update time.
1501 if (vpdFilePath == SYSTEM_VPD_FILE_PATH ||
1502 (jsonUtility::isFruPowerOffOnly(m_parsedJson, vpdFilePath) &&
1503 dbusUtility::isChassisPowerOn()))
1504 {
1505 continue;
1506 }
1507
1508 std::thread{[vpdFilePath, this]() {
1509 auto l_futureObject =
1510 std::async(&Worker::parseAndPublishVPD, this, vpdFilePath);
1511
1512 std::tuple<bool, std::string> l_threadInfo = l_futureObject.get();
1513
1514 // thread returned.
1515 m_mutex.lock();
1516 m_activeCollectionThreadCount--;
1517 m_mutex.unlock();
1518
1519 if (!m_activeCollectionThreadCount)
1520 {
1521 m_isAllFruCollected = true;
1522 }
1523 }}.detach();
1524 }
1525}
1526
1527// ToDo: Move the API under IBM_SYSTEM
1528void Worker::performBackupAndRestore(types::VPDMapVariant& io_srcVpdMap)
1529{
1530 try
1531 {
1532 std::string l_backupAndRestoreCfgFilePath =
1533 m_parsedJson.value("backupRestoreConfigPath", "");
1534
1535 nlohmann::json l_backupAndRestoreCfgJsonObj =
1536 jsonUtility::getParsedJson(l_backupAndRestoreCfgFilePath);
1537
1538 // check if either of "source" or "destination" has inventory path.
1539 // this indicates that this sytem has System VPD on hardware
1540 // and other copy on D-Bus (BMC cache).
1541 if (!l_backupAndRestoreCfgJsonObj.empty() &&
1542 ((l_backupAndRestoreCfgJsonObj.contains("source") &&
1543 l_backupAndRestoreCfgJsonObj["source"].contains(
1544 "inventoryPath")) ||
1545 (l_backupAndRestoreCfgJsonObj.contains("destination") &&
1546 l_backupAndRestoreCfgJsonObj["destination"].contains(
1547 "inventoryPath"))))
1548 {
1549 BackupAndRestore l_backupAndRestoreObj(m_parsedJson);
1550 auto [l_srcVpdVariant,
1551 l_dstVpdVariant] = l_backupAndRestoreObj.backupAndRestore();
1552
1553 // ToDo: Revisit is this check is required or not.
1554 if (auto l_srcVpdMap =
1555 std::get_if<types::IPZVpdMap>(&l_srcVpdVariant);
1556 l_srcVpdMap && !(*l_srcVpdMap).empty())
1557 {
1558 io_srcVpdMap = std::move(l_srcVpdVariant);
1559 }
1560 }
1561 }
1562 catch (const std::exception& l_ex)
1563 {
1564 EventLogger::createSyncPel(
1565 types::ErrorType::InvalidVpdMessage,
1566 types::SeverityType::Informational, __FILE__, __FUNCTION__, 0,
1567 std::string(
1568 "Exception caught while backup and restore VPD keyword's.") +
1569 l_ex.what(),
1570 std::nullopt, std::nullopt, std::nullopt, std::nullopt);
1571 }
1572}
1573
1574void Worker::deleteFruVpd(const std::string& i_dbusObjPath)
1575{
1576 if (i_dbusObjPath.empty())
1577 {
1578 throw std::runtime_error("Given DBus object path is empty.");
1579 }
1580
1581 const std::string& l_fruPath =
1582 jsonUtility::getFruPathFromJson(m_parsedJson, i_dbusObjPath);
1583
1584 try
1585 {
1586 auto l_presentPropValue = dbusUtility::readDbusProperty(
1587 constants::pimServiceName, i_dbusObjPath,
1588 constants::inventoryItemInf, "Present");
1589
1590 if (auto l_value = std::get_if<bool>(&l_presentPropValue))
1591 {
1592 if (!(*l_value))
1593 {
1594 throw std::runtime_error("Given FRU is not present");
1595 }
1596 else
1597 {
1598 if (jsonUtility::isActionRequired(m_parsedJson, l_fruPath,
1599 "preAction", "deletion"))
1600 {
1601 if (!processPreAction(l_fruPath, "deletion"))
1602 {
1603 throw std::runtime_error("Pre action failed");
1604 }
1605 }
1606
1607 std::vector<std::string> l_interfaceList{
1608 constants::operationalStatusInf};
1609
1610 types::MapperGetSubTree l_subTreeMap =
1611 dbusUtility::getObjectSubTree(i_dbusObjPath, 0,
1612 l_interfaceList);
1613
1614 types::ObjectMap l_objectMap;
1615
1616 // Updates VPD specific interfaces property value under PIM for
1617 // sub FRUs.
1618 for (const auto& [l_objectPath, l_serviceInterfaceMap] :
1619 l_subTreeMap)
1620 {
1621 types::InterfaceMap l_interfaceMap;
1622 vpdSpecificUtility::resetDataUnderPIM(l_objectPath,
1623 l_interfaceMap);
1624 l_objectMap.emplace(l_objectPath,
1625 std::move(l_interfaceMap));
1626 }
1627
1628 types::InterfaceMap l_interfaceMap;
1629 vpdSpecificUtility::resetDataUnderPIM(i_dbusObjPath,
1630 l_interfaceMap);
1631
1632 l_objectMap.emplace(i_dbusObjPath, std::move(l_interfaceMap));
1633
1634 if (!dbusUtility::callPIM(std::move(l_objectMap)))
1635 {
1636 throw std::runtime_error("Call to PIM failed.");
1637 }
1638
1639 if (jsonUtility::isActionRequired(m_parsedJson, l_fruPath,
1640 "postAction", "deletion"))
1641 {
1642 if (!processPostAction(l_fruPath, "deletion"))
1643 {
1644 throw std::runtime_error("Post action failed");
1645 }
1646 }
1647 }
1648 }
1649 else
1650 {
1651 logging::logMessage(
1652 "Can't process delete VPD for FRU [" + i_dbusObjPath +
1653 "] as unable to read present property");
1654 return;
1655 }
1656
1657 logging::logMessage(
1658 "Successfully completed deletion of FRU VPD for " + i_dbusObjPath);
1659 }
1660 catch (const std::exception& l_ex)
1661 {
1662 if (jsonUtility::isActionRequired(m_parsedJson, l_fruPath,
1663 "postFailAction", "deletion"))
1664 {
1665 if (!jsonUtility::executePostFailAction(m_parsedJson, l_fruPath,
1666 "deletion"))
1667 {
1668 logging::logMessage(
1669 "Post fail action failed for: " + i_dbusObjPath);
1670 }
1671 }
1672
1673 logging::logMessage("Failed to delete VPD for FRU : " + i_dbusObjPath +
1674 " error: " + std::string(l_ex.what()));
1675 }
1676}
1677} // namespace vpd