1 #include "config.h"
2
3 #include "vpd_tool.hpp"
4
5 #include "tool_constants.hpp"
6 #include "tool_types.hpp"
7 #include "tool_utils.hpp"
8
9 #include <iostream>
10 #include <regex>
11 #include <tuple>
12 namespace vpd
13 {
readKeyword(const std::string & i_vpdPath,const std::string & i_recordName,const std::string & i_keywordName,const bool i_onHardware,const std::string & i_fileToSave)14 int VpdTool::readKeyword(
15 const std::string& i_vpdPath, const std::string& i_recordName,
16 const std::string& i_keywordName, const bool i_onHardware,
17 const std::string& i_fileToSave)
18 {
19 int l_rc = constants::FAILURE;
20 try
21 {
22 types::DbusVariantType l_keywordValue;
23 if (i_onHardware)
24 {
25 l_keywordValue = utils::readKeywordFromHardware(
26 i_vpdPath, std::make_tuple(i_recordName, i_keywordName));
27 }
28 else
29 {
30 std::string l_inventoryObjectPath(
31 constants::baseInventoryPath + i_vpdPath);
32
33 l_keywordValue = utils::readDbusProperty(
34 constants::inventoryManagerService, l_inventoryObjectPath,
35 constants::ipzVpdInfPrefix + i_recordName, i_keywordName);
36 }
37
38 if (const auto l_value =
39 std::get_if<types::BinaryVector>(&l_keywordValue);
40 l_value && !l_value->empty())
41 {
42 // ToDo: Print value in both ASCII and hex formats
43 const std::string& l_keywordStrValue =
44 utils::getPrintableValue(*l_value);
45
46 if (i_fileToSave.empty())
47 {
48 utils::displayOnConsole(i_vpdPath, i_keywordName,
49 l_keywordStrValue);
50 l_rc = constants::SUCCESS;
51 }
52 else
53 {
54 if (utils::saveToFile(i_fileToSave, l_keywordStrValue))
55 {
56 std::cout
57 << "Value read is saved on the file: " << i_fileToSave
58 << std::endl;
59 l_rc = constants::SUCCESS;
60 }
61 else
62 {
63 std::cerr
64 << "Error while saving the read value on the file: "
65 << i_fileToSave
66 << "\nDisplaying the read value on console"
67 << std::endl;
68 utils::displayOnConsole(i_vpdPath, i_keywordName,
69 l_keywordStrValue);
70 }
71 }
72 }
73 else
74 {
75 // TODO: Enable logging when verbose is enabled.
76 // std::cout << "Invalid data type or empty data received." <<
77 // std::endl;
78 }
79 }
80 catch (const std::exception& l_ex)
81 {
82 // TODO: Enable logging when verbose is enabled.
83 /*std::cerr << "Read keyword's value for path: " << i_vpdPath
84 << ", Record: " << i_recordName
85 << ", Keyword: " << i_keywordName
86 << " is failed, exception: " << l_ex.what() << std::endl;*/
87 }
88 return l_rc;
89 }
90
dumpObject(std::string i_fruPath) const91 int VpdTool::dumpObject(std::string i_fruPath) const noexcept
92 {
93 int l_rc{constants::FAILURE};
94 try
95 {
96 // ToDo: For PFuture system take only full path from the user.
97 i_fruPath = constants::baseInventoryPath + i_fruPath;
98
99 nlohmann::json l_resultJsonArray = nlohmann::json::array({});
100 const nlohmann::json l_fruJson = getFruProperties(i_fruPath);
101 if (!l_fruJson.empty())
102 {
103 l_resultJsonArray += l_fruJson;
104
105 utils::printJson(l_resultJsonArray);
106 }
107 else
108 {
109 std::cout << "FRU [" << i_fruPath
110 << "] is not present in the system" << std::endl;
111 }
112 l_rc = constants::SUCCESS;
113 }
114 catch (std::exception& l_ex)
115 {
116 // TODO: Enable logging when verbose is enabled.
117 std::cerr << "Dump Object failed for FRU [" << i_fruPath
118 << "], Error: " << l_ex.what() << std::endl;
119 }
120 return l_rc;
121 }
122
getFruProperties(const std::string & i_objectPath) const123 nlohmann::json VpdTool::getFruProperties(const std::string& i_objectPath) const
124 {
125 // check if FRU is present in the system
126 if (!isFruPresent(i_objectPath))
127 {
128 return nlohmann::json::object_t();
129 }
130
131 nlohmann::json l_fruJson = nlohmann::json::object_t({});
132
133 // need to trim out the base inventory path in the FRU JSON.
134 const std::string l_displayObjectPath =
135 (i_objectPath.find(constants::baseInventoryPath) == std::string::npos)
136 ? i_objectPath
137 : i_objectPath.substr(strlen(constants::baseInventoryPath));
138
139 l_fruJson.emplace(l_displayObjectPath, nlohmann::json::object_t({}));
140
141 auto& l_fruObject = l_fruJson[l_displayObjectPath];
142
143 const auto l_prettyNameInJson = getInventoryPropertyJson<std::string>(
144 i_objectPath, constants::inventoryItemInf, "PrettyName");
145 if (!l_prettyNameInJson.empty())
146 {
147 l_fruObject.insert(l_prettyNameInJson.cbegin(),
148 l_prettyNameInJson.cend());
149 }
150
151 const auto l_locationCodeInJson = getInventoryPropertyJson<std::string>(
152 i_objectPath, constants::locationCodeInf, "LocationCode");
153 if (!l_locationCodeInJson.empty())
154 {
155 l_fruObject.insert(l_locationCodeInJson.cbegin(),
156 l_locationCodeInJson.cend());
157 }
158
159 // Get the properties under VINI interface.
160
161 nlohmann::json l_viniPropertiesInJson = nlohmann::json::object({});
162
163 auto l_readViniKeyWord = [i_objectPath, &l_viniPropertiesInJson,
164 this](const std::string& i_keyWord) {
165 const nlohmann::json l_keyWordJson =
166 getInventoryPropertyJson<vpd::types::BinaryVector>(
167 i_objectPath, constants::kwdVpdInf, i_keyWord);
168 l_viniPropertiesInJson.insert(l_keyWordJson.cbegin(),
169 l_keyWordJson.cend());
170 };
171
172 const std::vector<std::string> l_viniKeywords = {"SN", "PN", "CC", "FN",
173 "DR"};
174
175 std::for_each(l_viniKeywords.cbegin(), l_viniKeywords.cend(),
176 l_readViniKeyWord);
177
178 if (!l_viniPropertiesInJson.empty())
179 {
180 l_fruObject.insert(l_viniPropertiesInJson.cbegin(),
181 l_viniPropertiesInJson.cend());
182 }
183 // if a FRU doesn't have VINI properties, we need to get the properties from
184 // Decorator.Asset interface
185 else
186 {
187 // Get properties under Decorator.Asset interface
188 const auto l_decoratorAssetPropertiesMap =
189 utils::getPropertyMap(constants::inventoryManagerService,
190 i_objectPath, constants::assetInf);
191
192 for (const auto& l_aProperty : l_decoratorAssetPropertiesMap)
193 {
194 if (const auto l_propertyValueStr =
195 std::get_if<std::string>(&l_aProperty.second))
196 {
197 l_fruObject.emplace(l_aProperty.first, *l_propertyValueStr);
198 }
199 }
200 }
201
202 const auto l_typePropertyJson = getFruTypeProperty(i_objectPath);
203 if (!l_typePropertyJson.empty())
204 {
205 l_fruObject.insert(l_typePropertyJson.cbegin(),
206 l_typePropertyJson.cend());
207 }
208
209 // insert FRU "TYPE"
210 l_fruObject.emplace("TYPE", "FRU");
211
212 return l_fruJson;
213 }
214
215 template <typename PropertyType>
getInventoryPropertyJson(const std::string & i_objectPath,const std::string & i_interface,const std::string & i_propertyName) const216 nlohmann::json VpdTool::getInventoryPropertyJson(
217 const std::string& i_objectPath, const std::string& i_interface,
218 const std::string& i_propertyName) const noexcept
219 {
220 nlohmann::json l_resultInJson = nlohmann::json::object({});
221 try
222 {
223 types::DbusVariantType l_keyWordValue;
224
225 l_keyWordValue =
226 utils::readDbusProperty(constants::inventoryManagerService,
227 i_objectPath, i_interface, i_propertyName);
228
229 if (const auto l_value = std::get_if<PropertyType>(&l_keyWordValue))
230 {
231 if constexpr (std::is_same<PropertyType, std::string>::value)
232 {
233 l_resultInJson.emplace(i_propertyName, *l_value);
234 }
235 else if constexpr (std::is_same<PropertyType, bool>::value)
236 {
237 l_resultInJson.emplace(i_propertyName,
238 *l_value ? "true" : "false");
239 }
240 else if constexpr (std::is_same<PropertyType,
241 types::BinaryVector>::value)
242 {
243 const std::string& l_keywordStrValue =
244 vpd::utils::getPrintableValue(*l_value);
245
246 l_resultInJson.emplace(i_propertyName, l_keywordStrValue);
247 }
248 }
249 else
250 {
251 // TODO: Enable logging when verbose is enabled.
252 // std::cout << "Invalid data type received." << std::endl;
253 }
254 }
255 catch (const std::exception& l_ex)
256 {
257 // TODO: Enable logging when verbose is enabled.
258 /*std::cerr << "Read " << i_propertyName << " value for FRU path: " <<
259 i_objectPath
260 << ", failed with exception: " << l_ex.what() << std::endl;*/
261 }
262 return l_resultInJson;
263 }
264
fixSystemVpd() const265 int VpdTool::fixSystemVpd() const noexcept
266 {
267 int l_rc = constants::FAILURE;
268
269 nlohmann::json l_backupRestoreCfgJsonObj = getBackupRestoreCfgJsonObj();
270 if (!fetchKeywordInfo(l_backupRestoreCfgJsonObj))
271 {
272 return l_rc;
273 }
274
275 printSystemVpd(l_backupRestoreCfgJsonObj);
276
277 do
278 {
279 printFixSystemVpdOption(types::UserOption::UseBackupDataForAll);
280 printFixSystemVpdOption(
281 types::UserOption::UseSystemBackplaneDataForAll);
282 printFixSystemVpdOption(types::UserOption::MoreOptions);
283 printFixSystemVpdOption(types::UserOption::Exit);
284
285 int l_userSelectedOption = types::UserOption::Exit;
286 std::cin >> l_userSelectedOption;
287
288 std::cout << std::endl << std::string(191, '=') << std::endl;
289
290 if (types::UserOption::UseBackupDataForAll == l_userSelectedOption)
291 {
292 l_rc = updateAllKeywords(l_backupRestoreCfgJsonObj, true);
293 break;
294 }
295 else if (types::UserOption::UseSystemBackplaneDataForAll ==
296 l_userSelectedOption)
297 {
298 l_rc = updateAllKeywords(l_backupRestoreCfgJsonObj, false);
299 break;
300 }
301 else if (types::UserOption::MoreOptions == l_userSelectedOption)
302 {
303 l_rc = handleMoreOption(l_backupRestoreCfgJsonObj);
304 break;
305 }
306 else if (types::UserOption::Exit == l_userSelectedOption)
307 {
308 std::cout << "Exit successfully" << std::endl;
309 break;
310 }
311 else
312 {
313 std::cout << "Provide a valid option. Retry." << std::endl;
314 }
315 } while (true);
316
317 return l_rc;
318 }
319
writeKeyword(std::string i_vpdPath,const std::string & i_recordName,const std::string & i_keywordName,const std::string & i_keywordValue,const bool i_onHardware)320 int VpdTool::writeKeyword(
321 std::string i_vpdPath, const std::string& i_recordName,
322 const std::string& i_keywordName, const std::string& i_keywordValue,
323 const bool i_onHardware) noexcept
324 {
325 int l_rc = constants::FAILURE;
326 try
327 {
328 if (i_vpdPath.empty() || i_recordName.empty() ||
329 i_keywordName.empty() || i_keywordValue.empty())
330 {
331 throw std::runtime_error("Received input is empty.");
332 }
333
334 auto l_paramsToWrite =
335 std::make_tuple(i_recordName, i_keywordName,
336 utils::convertToBinary(i_keywordValue));
337
338 if (i_onHardware)
339 {
340 l_rc = utils::writeKeywordOnHardware(i_vpdPath, l_paramsToWrite);
341 }
342 else
343 {
344 i_vpdPath = constants::baseInventoryPath + i_vpdPath;
345 l_rc = utils::writeKeyword(i_vpdPath, l_paramsToWrite);
346 }
347
348 if (l_rc > 0)
349 {
350 std::cout << "Data updated successfully " << std::endl;
351 l_rc = constants::SUCCESS;
352 }
353 }
354 catch (const std::exception& l_ex)
355 {
356 // TODO: Enable log when verbose is enabled.
357 std::cerr << "Write keyword's value for path: " << i_vpdPath
358 << ", Record: " << i_recordName
359 << ", Keyword: " << i_keywordName
360 << " is failed. Exception: " << l_ex.what() << std::endl;
361 }
362 return l_rc;
363 }
364
getBackupRestoreCfgJsonObj() const365 nlohmann::json VpdTool::getBackupRestoreCfgJsonObj() const noexcept
366 {
367 nlohmann::json l_parsedBackupRestoreJson{};
368 try
369 {
370 nlohmann::json l_parsedSystemJson =
371 utils::getParsedJson(INVENTORY_JSON_SYM_LINK);
372
373 // check for mandatory fields at this point itself.
374 if (!l_parsedSystemJson.contains("backupRestoreConfigPath"))
375 {
376 throw std::runtime_error(
377 "backupRestoreConfigPath tag is missing from system config JSON : " +
378 std::string(INVENTORY_JSON_SYM_LINK));
379 }
380
381 l_parsedBackupRestoreJson =
382 utils::getParsedJson(l_parsedSystemJson["backupRestoreConfigPath"]);
383 }
384 catch (const std::exception& l_ex)
385 {
386 // TODO: Enable logging when verbose is enabled.
387 std::cerr << l_ex.what() << std::endl;
388 }
389
390 return l_parsedBackupRestoreJson;
391 }
392
cleanSystemVpd() const393 int VpdTool::cleanSystemVpd() const noexcept
394 {
395 try
396 {
397 // get the keyword map from backup_restore json
398 // iterate through the keyword map get default value of
399 // l_keywordName.
400 // use writeKeyword API to update default value on hardware,
401 // backup and D - Bus.
402 const nlohmann::json l_parsedBackupRestoreJson =
403 getBackupRestoreCfgJsonObj();
404
405 // check for mandatory tags
406 if (l_parsedBackupRestoreJson.contains("source") &&
407 l_parsedBackupRestoreJson.contains("backupMap") &&
408 l_parsedBackupRestoreJson["source"].contains("hardwarePath") &&
409 l_parsedBackupRestoreJson["backupMap"].is_array())
410 {
411 // get the source hardware path
412 const auto& l_hardwarePath =
413 l_parsedBackupRestoreJson["source"]["hardwarePath"];
414
415 // iterate through the backup map
416 for (const auto& l_aRecordKwInfo :
417 l_parsedBackupRestoreJson["backupMap"])
418 {
419 // check if Manufacturing Reset is required for this entry
420 const bool l_isMfgCleanRequired =
421 l_aRecordKwInfo.value("isManufactureResetRequired", false);
422
423 if (l_isMfgCleanRequired)
424 {
425 // get the Record name and Keyword name
426 const std::string& l_srcRecordName =
427 l_aRecordKwInfo.value("sourceRecord", "");
428 const std::string& l_srcKeywordName =
429 l_aRecordKwInfo.value("sourceKeyword", "");
430
431 // validate the Record name, Keyword name and the
432 // defaultValue
433 if (!l_srcRecordName.empty() && !l_srcKeywordName.empty() &&
434 l_aRecordKwInfo.contains("defaultValue") &&
435 l_aRecordKwInfo["defaultValue"].is_array())
436 {
437 const types::BinaryVector l_defaultBinaryValue =
438 l_aRecordKwInfo["defaultValue"]
439 .get<types::BinaryVector>();
440
441 // update the Keyword with default value, use D-Bus
442 // method UpdateKeyword exposed by vpd-manager.
443 // Note: writing to all paths (Primary EEPROM path,
444 // Secondary EEPROM path, D-Bus cache and Backup path)
445 // is the responsibility of vpd-manager's UpdateKeyword
446 // API
447 if (constants::FAILURE ==
448 utils::writeKeyword(
449 l_hardwarePath,
450 std::make_tuple(l_srcRecordName,
451 l_srcKeywordName,
452 l_defaultBinaryValue)))
453 {
454 // TODO: Enable logging when verbose
455 // is enabled.
456 std::cerr << "Failed to update " << l_srcRecordName
457 << ":" << l_srcKeywordName << std::endl;
458 }
459 }
460 else
461 {
462 std::cerr
463 << "Unrecognized Entry Record [" << l_srcRecordName
464 << "] Keyword [" << l_srcKeywordName
465 << "] in Backup Restore JSON backup map"
466 << std::endl;
467 }
468 } // mfgClean required check
469 } // keyword list loop
470 }
471 else // backupRestoreJson is not valid
472 {
473 std::cerr << "Backup Restore JSON is not valid" << std::endl;
474 }
475
476 // success/failure message
477 std::cout << "The critical keywords from system backplane VPD has "
478 "been reset successfully."
479 << std::endl;
480
481 } // try block end
482 catch (const std::exception& l_ex)
483 {
484 // TODO: Enable logging when verbose is enabled.
485 std::cerr
486 << "Manufacturing reset on system vpd keywords is unsuccessful. Error : "
487 << l_ex.what() << std::endl;
488 }
489 return constants::SUCCESS;
490 }
491
fetchKeywordInfo(nlohmann::json & io_parsedJsonObj) const492 bool VpdTool::fetchKeywordInfo(nlohmann::json& io_parsedJsonObj) const noexcept
493 {
494 bool l_returnValue = false;
495 try
496 {
497 if (io_parsedJsonObj.empty() || !io_parsedJsonObj.contains("source") ||
498 !io_parsedJsonObj.contains("destination") ||
499 !io_parsedJsonObj.contains("backupMap"))
500 {
501 throw std::runtime_error("Invalid JSON");
502 }
503
504 std::string l_srcVpdPath;
505 std::string l_dstVpdPath;
506
507 bool l_isSourceOnHardware = false;
508 if (l_srcVpdPath = io_parsedJsonObj["source"].value("hardwarePath", "");
509 !l_srcVpdPath.empty())
510 {
511 l_isSourceOnHardware = true;
512 }
513 else if (l_srcVpdPath =
514 io_parsedJsonObj["source"].value("inventoryPath", "");
515 l_srcVpdPath.empty())
516 {
517 throw std::runtime_error("Source path is empty in JSON");
518 }
519
520 bool l_isDestinationOnHardware = false;
521 if (l_dstVpdPath =
522 io_parsedJsonObj["destination"].value("hardwarePath", "");
523 !l_dstVpdPath.empty())
524 {
525 l_isDestinationOnHardware = true;
526 }
527 else if (l_dstVpdPath =
528 io_parsedJsonObj["destination"].value("inventoryPath", "");
529 l_dstVpdPath.empty())
530 {
531 throw std::runtime_error("Destination path is empty in JSON");
532 }
533
534 for (auto& l_aRecordKwInfo : io_parsedJsonObj["backupMap"])
535 {
536 const std::string& l_srcRecordName =
537 l_aRecordKwInfo.value("sourceRecord", "");
538 const std::string& l_srcKeywordName =
539 l_aRecordKwInfo.value("sourceKeyword", "");
540 const std::string& l_dstRecordName =
541 l_aRecordKwInfo.value("destinationRecord", "");
542 const std::string& l_dstKeywordName =
543 l_aRecordKwInfo.value("destinationKeyword", "");
544
545 if (l_srcRecordName.empty() || l_dstRecordName.empty() ||
546 l_srcKeywordName.empty() || l_dstKeywordName.empty())
547 {
548 // TODO: Enable logging when verbose is enabled.
549 std::cout << "Record or keyword not found in the JSON."
550 << std::endl;
551 continue;
552 }
553
554 types::DbusVariantType l_srcKeywordVariant;
555 if (l_isSourceOnHardware)
556 {
557 l_srcKeywordVariant = utils::readKeywordFromHardware(
558 l_srcVpdPath,
559 std::make_tuple(l_srcRecordName, l_srcKeywordName));
560 }
561 else
562 {
563 l_srcKeywordVariant = utils::readDbusProperty(
564 constants::inventoryManagerService, l_srcVpdPath,
565 constants::ipzVpdInfPrefix + l_srcRecordName,
566 l_srcKeywordName);
567 }
568
569 if (auto l_srcKeywordValue =
570 std::get_if<types::BinaryVector>(&l_srcKeywordVariant);
571 l_srcKeywordValue && !l_srcKeywordValue->empty())
572 {
573 l_aRecordKwInfo["sourcekeywordValue"] = *l_srcKeywordValue;
574 }
575 else
576 {
577 // TODO: Enable logging when verbose is enabled.
578 std::cout
579 << "Invalid data type or empty data received, for source record: "
580 << l_srcRecordName << ", keyword: " << l_srcKeywordName
581 << std::endl;
582 continue;
583 }
584
585 types::DbusVariantType l_dstKeywordVariant;
586 if (l_isDestinationOnHardware)
587 {
588 l_dstKeywordVariant = utils::readKeywordFromHardware(
589 l_dstVpdPath,
590 std::make_tuple(l_dstRecordName, l_dstKeywordName));
591 }
592 else
593 {
594 l_dstKeywordVariant = utils::readDbusProperty(
595 constants::inventoryManagerService, l_dstVpdPath,
596 constants::ipzVpdInfPrefix + l_dstRecordName,
597 l_dstKeywordName);
598 }
599
600 if (auto l_dstKeywordValue =
601 std::get_if<types::BinaryVector>(&l_dstKeywordVariant);
602 l_dstKeywordValue && !l_dstKeywordValue->empty())
603 {
604 l_aRecordKwInfo["destinationkeywordValue"] = *l_dstKeywordValue;
605 }
606 else
607 {
608 // TODO: Enable logging when verbose is enabled.
609 std::cout
610 << "Invalid data type or empty data received, for destination record: "
611 << l_dstRecordName << ", keyword: " << l_dstKeywordName
612 << std::endl;
613 continue;
614 }
615 }
616
617 l_returnValue = true;
618 }
619 catch (const std::exception& l_ex)
620 {
621 // TODO: Enable logging when verbose is enabled.
622 std::cerr << l_ex.what() << std::endl;
623 }
624
625 return l_returnValue;
626 }
627
628 nlohmann::json
getFruTypeProperty(const std::string & i_objectPath) const629 VpdTool::getFruTypeProperty(const std::string& i_objectPath) const noexcept
630 {
631 nlohmann::json l_resultInJson = nlohmann::json::object({});
632 std::vector<std::string> l_pimInfList;
633
634 auto l_serviceInfMap = utils::GetServiceInterfacesForObject(
635 i_objectPath, std::vector<std::string>{constants::inventoryItemInf});
636 if (l_serviceInfMap.contains(constants::inventoryManagerService))
637 {
638 l_pimInfList = l_serviceInfMap[constants::inventoryManagerService];
639
640 // iterate through the list and find
641 // "xyz.openbmc_project.Inventory.Item.*"
642 for (const auto& l_interface : l_pimInfList)
643 {
644 if (l_interface.find(constants::inventoryItemInf) !=
645 std::string::npos &&
646 l_interface.length() >
647 std::string(constants::inventoryItemInf).length())
648 {
649 l_resultInJson.emplace("type", l_interface);
650 }
651 }
652 }
653 return l_resultInJson;
654 }
655
isFruPresent(const std::string & i_objectPath) const656 bool VpdTool::isFruPresent(const std::string& i_objectPath) const noexcept
657 {
658 bool l_returnValue{false};
659 try
660 {
661 types::DbusVariantType l_keyWordValue;
662
663 l_keyWordValue = utils::readDbusProperty(
664 constants::inventoryManagerService, i_objectPath,
665 constants::inventoryItemInf, "Present");
666
667 if (const auto l_value = std::get_if<bool>(&l_keyWordValue))
668 {
669 l_returnValue = *l_value;
670 }
671 }
672 catch (const std::runtime_error& l_ex)
673 {
674 // TODO: Enable logging when verbose is enabled.
675 // std::cerr << "Failed to check \"Present\" property for FRU "
676 // << i_objectPath << " Error: " << l_ex.what() <<
677 // std::endl;
678 }
679 return l_returnValue;
680 }
681
printFixSystemVpdOption(const types::UserOption & i_option) const682 void VpdTool::printFixSystemVpdOption(
683 const types::UserOption& i_option) const noexcept
684 {
685 switch (i_option)
686 {
687 case types::UserOption::Exit:
688 std::cout << "Enter 0 => To exit successfully : ";
689 break;
690 case types::UserOption::UseBackupDataForAll:
691 std::cout << "Enter 1 => If you choose the data on backup for all "
692 "mismatching record-keyword pairs"
693 << std::endl;
694 break;
695 case types::UserOption::UseSystemBackplaneDataForAll:
696 std::cout << "Enter 2 => If you choose the data on primary for all "
697 "mismatching record-keyword pairs"
698 << std::endl;
699 break;
700 case types::UserOption::MoreOptions:
701 std::cout << "Enter 3 => If you wish to explore more options"
702 << std::endl;
703 break;
704 case types::UserOption::UseBackupDataForCurrent:
705 std::cout << "Enter 4 => If you choose the data on backup as the "
706 "right value"
707 << std::endl;
708 break;
709 case types::UserOption::UseSystemBackplaneDataForCurrent:
710 std::cout << "Enter 5 => If you choose the data on primary as the "
711 "right value"
712 << std::endl;
713 break;
714 case types::UserOption::NewValueOnBoth:
715 std::cout
716 << "Enter 6 => If you wish to enter a new value to update "
717 "both on backup and primary"
718 << std::endl;
719 break;
720 case types::UserOption::SkipCurrent:
721 std::cout << "Enter 7 => If you wish to skip the above "
722 "record-keyword pair"
723 << std::endl;
724 break;
725 }
726 }
727
dumpInventory(bool i_dumpTable) const728 int VpdTool::dumpInventory(bool i_dumpTable) const noexcept
729 {
730 int l_rc{constants::FAILURE};
731
732 try
733 {
734 // get all object paths under PIM
735 const auto l_objectPaths = utils::GetSubTreePaths(
736 constants::baseInventoryPath, 0,
737 std::vector<std::string>{constants::inventoryItemInf});
738
739 if (!l_objectPaths.empty())
740 {
741 nlohmann::json l_resultInJson = nlohmann::json::array({});
742
743 std::for_each(l_objectPaths.begin(), l_objectPaths.end(),
744 [&](const auto& l_objectPath) {
745 const auto l_fruJson =
746 getFruProperties(l_objectPath);
747 if (!l_fruJson.empty())
748 {
749 if (l_resultInJson.empty())
750 {
751 l_resultInJson += l_fruJson;
752 }
753 else
754 {
755 l_resultInJson.at(0).insert(
756 l_fruJson.cbegin(), l_fruJson.cend());
757 }
758 }
759 });
760
761 if (i_dumpTable)
762 {
763 // create Table object
764 utils::Table l_inventoryTable{};
765
766 // columns to be populated in the Inventory table
767 const std::vector<types::TableColumnNameSizePair>
768 l_tableColumns = {
769 {"FRU", 100}, {"CC", 6}, {"DR", 20},
770 {"LocationCode", 32}, {"PN", 8}, {"PrettyName", 80},
771 {"SubModel", 10}, {"SN", 15}, {"type", 60}};
772
773 types::TableInputData l_tableData;
774
775 // First prepare the Table Columns
776 for (const auto& l_column : l_tableColumns)
777 {
778 if (constants::FAILURE ==
779 l_inventoryTable.AddColumn(l_column.first,
780 l_column.second))
781 {
782 // TODO: Enable logging when verbose is enabled.
783 std::cerr << "Failed to add column " << l_column.first
784 << " in Inventory Table." << std::endl;
785 }
786 }
787
788 // iterate through the json array
789 for (const auto& l_fruEntry : l_resultInJson[0].items())
790 {
791 // if object path ends in "unit([0-9][0-9]?)", skip adding
792 // the object path in the table
793 if (std::regex_search(l_fruEntry.key(),
794 std::regex("unit([0-9][0-9]?)")))
795 {
796 continue;
797 }
798
799 std::vector<std::string> l_row;
800 for (const auto& l_column : l_tableColumns)
801 {
802 const auto& l_fruJson = l_fruEntry.value();
803
804 if (l_column.first == "FRU")
805 {
806 l_row.push_back(l_fruEntry.key());
807 }
808 else
809 {
810 if (l_fruJson.contains(l_column.first))
811 {
812 l_row.push_back(l_fruJson[l_column.first]);
813 }
814 else
815 {
816 l_row.push_back("");
817 }
818 }
819 }
820
821 l_tableData.push_back(l_row);
822 }
823
824 l_rc = l_inventoryTable.Print(l_tableData);
825 }
826 else
827 {
828 // print JSON to console
829 utils::printJson(l_resultInJson);
830 l_rc = constants::SUCCESS;
831 }
832 }
833 }
834 catch (const std::exception& l_ex)
835 {
836 // TODO: Enable logging when verbose is enabled.
837 std::cerr << "Dump inventory failed. Error: " << l_ex.what()
838 << std::endl;
839 }
840 return l_rc;
841 }
842
printSystemVpd(const nlohmann::json & i_parsedJsonObj) const843 void VpdTool::printSystemVpd(
844 const nlohmann::json& i_parsedJsonObj) const noexcept
845 {
846 if (i_parsedJsonObj.empty() || !i_parsedJsonObj.contains("backupMap"))
847 {
848 // TODO: Enable logging when verbose is enabled.
849 std::cerr << "Invalid JSON to print system VPD" << std::endl;
850 }
851
852 std::string l_outline(191, '=');
853 std::cout << "\nRestorable record-keyword pairs and their data on backup & "
854 "primary.\n\n"
855 << l_outline << std::endl;
856
857 std::cout << std::left << std::setw(6) << "S.No" << std::left
858 << std::setw(8) << "Record" << std::left << std::setw(9)
859 << "Keyword" << std::left << std::setw(75) << "Data On Backup"
860 << std::left << std::setw(75) << "Data On Primary" << std::left
861 << std::setw(14) << "Data Mismatch\n"
862 << l_outline << std::endl;
863
864 uint8_t l_slNum = 0;
865
866 for (const auto& l_aRecordKwInfo : i_parsedJsonObj["backupMap"])
867 {
868 if (l_aRecordKwInfo.contains("sourceRecord") ||
869 l_aRecordKwInfo.contains("sourceKeyword") ||
870 l_aRecordKwInfo.contains("destinationkeywordValue") ||
871 l_aRecordKwInfo.contains("sourcekeywordValue"))
872 {
873 std::string l_mismatchFound{
874 (l_aRecordKwInfo["destinationkeywordValue"] !=
875 l_aRecordKwInfo["sourcekeywordValue"])
876 ? "YES"
877 : "NO"};
878
879 std::string l_splitLine(191, '-');
880
881 try
882 {
883 std::cout << std::left << std::setw(6)
884 << static_cast<int>(++l_slNum) << std::left
885 << std::setw(8)
886 << l_aRecordKwInfo.value("sourceRecord", "")
887 << std::left << std::setw(9)
888 << l_aRecordKwInfo.value("sourceKeyword", "")
889 << std::left << std::setw(75) << std::setfill(' ')
890 << utils::getPrintableValue(
891 l_aRecordKwInfo["destinationkeywordValue"])
892 << std::left << std::setw(75) << std::setfill(' ')
893 << utils::getPrintableValue(
894 l_aRecordKwInfo["sourcekeywordValue"])
895 << std::left << std::setw(14) << l_mismatchFound
896 << '\n'
897 << l_splitLine << std::endl;
898 }
899 catch (const std::exception& l_ex)
900 {
901 // TODO: Enable logging when verbose is enabled.
902 std::cerr << l_ex.what() << std::endl;
903 }
904 }
905 }
906 }
907
updateAllKeywords(const nlohmann::json & i_parsedJsonObj,bool i_useBackupData) const908 int VpdTool::updateAllKeywords(const nlohmann::json& i_parsedJsonObj,
909 bool i_useBackupData) const noexcept
910 {
911 int l_rc = constants::FAILURE;
912
913 if (i_parsedJsonObj.empty() || !i_parsedJsonObj.contains("source") ||
914 !i_parsedJsonObj.contains("backupMap"))
915 {
916 // TODO: Enable logging when verbose is enabled.
917 std::cerr << "Invalid JSON" << std::endl;
918 return l_rc;
919 }
920
921 std::string l_srcVpdPath;
922 if (auto l_vpdPath = i_parsedJsonObj["source"].value("hardwarePath", "");
923 !l_vpdPath.empty())
924 {
925 l_srcVpdPath = l_vpdPath;
926 }
927 else if (auto l_vpdPath =
928 i_parsedJsonObj["source"].value("inventoryPath", "");
929 !l_vpdPath.empty())
930 {
931 l_srcVpdPath = l_vpdPath;
932 }
933 else
934 {
935 // TODO: Enable logging when verbose is enabled.
936 std::cerr << "source path information is missing in JSON" << std::endl;
937 return l_rc;
938 }
939
940 bool l_anyMismatchFound = false;
941 for (const auto& l_aRecordKwInfo : i_parsedJsonObj["backupMap"])
942 {
943 if (!l_aRecordKwInfo.contains("sourceRecord") ||
944 !l_aRecordKwInfo.contains("sourceKeyword") ||
945 !l_aRecordKwInfo.contains("destinationkeywordValue") ||
946 !l_aRecordKwInfo.contains("sourcekeywordValue"))
947 {
948 // TODO: Enable logging when verbose is enabled.
949 std::cerr << "Missing required information in the JSON"
950 << std::endl;
951 continue;
952 }
953
954 if (l_aRecordKwInfo["sourcekeywordValue"] !=
955 l_aRecordKwInfo["destinationkeywordValue"])
956 {
957 l_anyMismatchFound = true;
958
959 auto l_keywordValue =
960 i_useBackupData ? l_aRecordKwInfo["destinationkeywordValue"]
961 : l_aRecordKwInfo["sourcekeywordValue"];
962
963 auto l_paramsToWrite = std::make_tuple(
964 l_aRecordKwInfo["sourceRecord"],
965 l_aRecordKwInfo["sourceKeyword"], l_keywordValue);
966
967 try
968 {
969 l_rc = utils::writeKeyword(l_srcVpdPath, l_paramsToWrite);
970 if (l_rc > 0)
971 {
972 l_rc = constants::SUCCESS;
973 }
974 }
975 catch (const std::exception& l_ex)
976 {
977 // TODO: Enable logging when verbose is enabled.
978 std::cerr << "write keyword failed for record: "
979 << l_aRecordKwInfo["sourceRecord"]
980 << ", keyword: " << l_aRecordKwInfo["sourceKeyword"]
981 << ", error: " << l_ex.what() << std::ends;
982 }
983 }
984 }
985
986 std::string l_dataUsed =
987 (i_useBackupData ? "data from backup" : "data from primary VPD");
988 if (l_anyMismatchFound)
989 {
990 std::cout << "Data updated successfully for all mismatching "
991 "record-keyword pairs by choosing their corresponding "
992 << l_dataUsed << ". Exit successfully." << std::endl;
993 }
994 else
995 {
996 std::cout << "No mismatch found for any of the above mentioned "
997 "record-keyword pair. Exit successfully."
998 << std::endl;
999 }
1000
1001 return l_rc;
1002 }
1003
handleMoreOption(const nlohmann::json & i_parsedJsonObj) const1004 int VpdTool::handleMoreOption(
1005 const nlohmann::json& i_parsedJsonObj) const noexcept
1006 {
1007 int l_rc = constants::FAILURE;
1008
1009 try
1010 {
1011 if (i_parsedJsonObj.empty() || !i_parsedJsonObj.contains("backupMap"))
1012 {
1013 throw std::runtime_error("Invalid JSON");
1014 }
1015
1016 std::string l_srcVpdPath;
1017
1018 if (auto l_vpdPath =
1019 i_parsedJsonObj["source"].value("hardwarePath", "");
1020 !l_vpdPath.empty())
1021 {
1022 l_srcVpdPath = l_vpdPath;
1023 }
1024 else if (auto l_vpdPath =
1025 i_parsedJsonObj["source"].value("inventoryPath", "");
1026 !l_vpdPath.empty())
1027 {
1028 l_srcVpdPath = l_vpdPath;
1029 }
1030 else
1031 {
1032 throw std::runtime_error(
1033 "source path information is missing in JSON");
1034 }
1035
1036 auto updateKeywordValue =
1037 [](std::string io_vpdPath, const std::string& i_recordName,
1038 const std::string& i_keywordName,
1039 const types::BinaryVector& i_keywordValue) -> int {
1040 int l_rc = constants::FAILURE;
1041
1042 try
1043 {
1044 auto l_paramsToWrite = std::make_tuple(
1045 i_recordName, i_keywordName, i_keywordValue);
1046 l_rc = utils::writeKeyword(io_vpdPath, l_paramsToWrite);
1047
1048 if (l_rc > 0)
1049 {
1050 std::cout << std::endl
1051 << "Data updated successfully." << std::endl;
1052 }
1053 }
1054 catch (const std::exception& l_ex)
1055 {
1056 // TODO: Enable log when verbose is enabled.
1057 std::cerr << l_ex.what() << std::endl;
1058 }
1059 return l_rc;
1060 };
1061
1062 do
1063 {
1064 int l_slNum = 0;
1065 bool l_exit = false;
1066
1067 for (const auto& l_aRecordKwInfo : i_parsedJsonObj["backupMap"])
1068 {
1069 if (!l_aRecordKwInfo.contains("sourceRecord") ||
1070 !l_aRecordKwInfo.contains("sourceKeyword") ||
1071 !l_aRecordKwInfo.contains("destinationkeywordValue") ||
1072 !l_aRecordKwInfo.contains("sourcekeywordValue"))
1073 {
1074 // TODO: Enable logging when verbose is enabled.
1075 std::cerr
1076 << "Source or destination information is missing in the JSON."
1077 << std::endl;
1078 continue;
1079 }
1080
1081 const std::string l_mismatchFound{
1082 (l_aRecordKwInfo["sourcekeywordValue"] !=
1083 l_aRecordKwInfo["destinationkeywordValue"])
1084 ? "YES"
1085 : "NO"};
1086
1087 std::cout << std::endl
1088 << std::left << std::setw(6) << "S.No" << std::left
1089 << std::setw(8) << "Record" << std::left
1090 << std::setw(9) << "Keyword" << std::left
1091 << std::setw(75) << std::setfill(' ') << "Backup Data"
1092 << std::left << std::setw(75) << std::setfill(' ')
1093 << "Primary Data" << std::left << std::setw(14)
1094 << "Data Mismatch" << std::endl;
1095
1096 std::cout << std::left << std::setw(6)
1097 << static_cast<int>(++l_slNum) << std::left
1098 << std::setw(8)
1099 << l_aRecordKwInfo.value("sourceRecord", "")
1100 << std::left << std::setw(9)
1101 << l_aRecordKwInfo.value("sourceKeyword", "")
1102 << std::left << std::setw(75) << std::setfill(' ')
1103 << utils::getPrintableValue(
1104 l_aRecordKwInfo["destinationkeywordValue"])
1105 << std::left << std::setw(75) << std::setfill(' ')
1106 << utils::getPrintableValue(
1107 l_aRecordKwInfo["sourcekeywordValue"])
1108 << std::left << std::setw(14) << l_mismatchFound
1109 << std::endl;
1110
1111 std::cout << std::string(191, '=') << std::endl;
1112
1113 if (constants::STR_CMP_SUCCESS ==
1114 l_mismatchFound.compare("YES"))
1115 {
1116 printFixSystemVpdOption(
1117 types::UserOption::UseBackupDataForCurrent);
1118 printFixSystemVpdOption(
1119 types::UserOption::UseSystemBackplaneDataForCurrent);
1120 printFixSystemVpdOption(types::UserOption::NewValueOnBoth);
1121 printFixSystemVpdOption(types::UserOption::SkipCurrent);
1122 printFixSystemVpdOption(types::UserOption::Exit);
1123 }
1124 else
1125 {
1126 std::cout << "No mismatch found." << std::endl << std::endl;
1127 printFixSystemVpdOption(types::UserOption::NewValueOnBoth);
1128 printFixSystemVpdOption(types::UserOption::SkipCurrent);
1129 printFixSystemVpdOption(types::UserOption::Exit);
1130 }
1131
1132 int l_userSelectedOption = types::UserOption::Exit;
1133 std::cin >> l_userSelectedOption;
1134
1135 if (types::UserOption::UseBackupDataForCurrent ==
1136 l_userSelectedOption)
1137 {
1138 l_rc = updateKeywordValue(
1139 l_srcVpdPath, l_aRecordKwInfo["sourceRecord"],
1140 l_aRecordKwInfo["sourceKeyword"],
1141 l_aRecordKwInfo["destinationkeywordValue"]);
1142 }
1143 else if (types::UserOption::UseSystemBackplaneDataForCurrent ==
1144 l_userSelectedOption)
1145 {
1146 l_rc = updateKeywordValue(
1147 l_srcVpdPath, l_aRecordKwInfo["sourceRecord"],
1148 l_aRecordKwInfo["sourceKeyword"],
1149 l_aRecordKwInfo["sourcekeywordValue"]);
1150 }
1151 else if (types::UserOption::NewValueOnBoth ==
1152 l_userSelectedOption)
1153 {
1154 std::string l_newValue;
1155 std::cout
1156 << std::endl
1157 << "Enter the new value to update on both "
1158 "primary & backup. Value should be in ASCII or "
1159 "in HEX(prefixed with 0x) : ";
1160 std::cin >> l_newValue;
1161 std::cout << std::endl
1162 << std::string(191, '=') << std::endl;
1163
1164 try
1165 {
1166 l_rc = updateKeywordValue(
1167 l_srcVpdPath, l_aRecordKwInfo["sourceRecord"],
1168 l_aRecordKwInfo["sourceKeyword"],
1169 utils::convertToBinary(l_newValue));
1170 }
1171 catch (const std::exception& l_ex)
1172 {
1173 // TODO: Enable logging when verbose is enabled.
1174 std::cerr << l_ex.what() << std::endl;
1175 }
1176 }
1177 else if (types::UserOption::SkipCurrent == l_userSelectedOption)
1178 {
1179 std::cout << std::endl
1180 << "Skipped the above record-keyword pair. "
1181 "Continue to the next available pair."
1182 << std::endl;
1183 }
1184 else if (types::UserOption::Exit == l_userSelectedOption)
1185 {
1186 std::cout << "Exit successfully" << std::endl;
1187 l_exit = true;
1188 break;
1189 }
1190 else
1191 {
1192 std::cout << "Provide a valid option. Retrying for the "
1193 "current record-keyword pair"
1194 << std::endl;
1195 }
1196 }
1197 if (l_exit)
1198 {
1199 l_rc = constants::SUCCESS;
1200 break;
1201 }
1202 } while (true);
1203 }
1204 catch (const std::exception& l_ex)
1205 {
1206 // TODO: Enable logging when verbose is enabled.
1207 std::cerr << l_ex.what() << std::endl;
1208 }
1209
1210 return l_rc;
1211 }
1212
1213 } // namespace vpd
1214