vpd-tool:Option to fixSystemVPD keywords

This commit has an added option in vpd-tool that fixes system VPD
restorable keywords in an interactive way.
This option is required in a field usecase.

In the field when there is a fault in BMC and BMC gets replaced,
the replaced BMC VPD will now have all blank data. Now the Product
engineer can use vpd-tool fixSystemVPD option to update the BMC
critical keywords by chosing the corresponding keyword data from
system backplane.

Similarly when the system backplane is replaced,
using the option, the PEs' can copy the keyword data from BMC.

When both system backplane and BMC are replaced, the PEs' will have
option to update new value on both.

This interactive tool option eases keyword data updation and avoids
manual updation for each and every mismatching critical keyword.

Test: Tested on everest

// Create a mismatch.
root@ever8bmc:/tmp# ./vpd-tool-writeHardwareFix -w -H -O /sys/bus/i2c/drivers/at24/8-0050/eeprom -R VCEN -K FC -V 0x64560204
Disabled reboot
Sleep started
Enabled reboot
root@ever8bmc:/tmp#
root@ever8bmc:/tmp# busctl set-property xyz.openbmc_project.Inventory.Manager /xyz/openbmc_project/inventory/system/chassis/motherboard com.ibm.ipzvpd.LXR0 LX ay 2 0x04 0x64
root@ever8bmc:/tmp#
root@ever8bmc:/tmp# busctl set-property xyz.openbmc_project.Inventory.Manager /xyz/openbmc_project/inventory/system/chassis/motherboard com.ibm.ipzvpd.VSYS WN ay 3 0x74 0x85 0x69
root@ever8bmc:/tmp# ./vpd-tool-writeHardwareFix -w -H -O /sys/bus/i2c/drivers/at24/8-0050/eeprom -R VSYS -K WN -V 0x64560204077675
Disabled reboot
Sleep started
Enabled reboot

=========

(Trimmed the output)
root@ever8bmc:/tmp# ./vpd-tool --fixSystemVPD

Restorable record-keyword pairs and their data on cache & hardware.

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
|======================================================================================================|
1     UTIL    D0       0x69                          0x69                          NO
|------------------------------------------------------------------------------------------------------|
2     LXR0    LX       0x0464                        0x3100080100300074            YES
|------------------------------------------------------------------------------------------------------|
3     VCEN    FC       0x373830432d303031            0x645602042d303031            YES
|------------------------------------------------------------------------------------------------------|
4     VCEN    SE       RCH0014                       RCH0014                       NO
|------------------------------------------------------------------------------------------------------|
5     VSYS    BR       0x5330                        0x5330                        NO
|------------------------------------------------------------------------------------------------------|
6     VSYS    TM       0x646534302d4d5258            0x646534302d4d5258            NO
|------------------------------------------------------------------------------------------------------|
7     VSYS    SE       13E8CEX                       13E8CEX                       NO
|------------------------------------------------------------------------------------------------------|
8     VSYS    SU       0x0004ac1e9fd4                0x0004ac1e9fd4                NO
|------------------------------------------------------------------------------------------------------|
9     VSYS    RB       0x31000000                    0x31000000                    NO
|------------------------------------------------------------------------------------------------------|
10    VSYS    WN       0x748569                      0x645602040776754243453432    YES
|------------------------------------------------------------------------------------------------------|
11    VSYS    RG       0x00000000                    0x00000000                    NO
|------------------------------------------------------------------------------------------------------|

Enter 1 => If you choose cache data of all mismatching record-keyword pairs
Enter 2 => If you choose hardware data of all mismatching record-keyword pairs
Enter 3 => If you wish to explore more options
Enter 0 to exit  3

|======================================================================================================|

Iterate through all restorable record-keyword pairs

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
1     UTIL    D0       0x69                          0x69                          NO
|======================================================================================================|

No mismatch found.

Enter 6 => If you wish to enter a new value to update both on BMC and System Backplane
Enter 7 => If you wish to skip the above record-keyword pair
Enter 0 => To exit successfully : 6

|======================================================================================================|

Enter the new value to update both on BMC & System Backplane (Value should be in ASCII or in HEX(prefixed with 0x)) : 0x02

|======================================================================================================|

Data updated successfully.

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
2     LXR0    LX       0x0464                        0x3100080100300074            YES
|======================================================================================================|

Enter 4 => If you choose the cache value as the right value
Enter 5 => If you choose hardware value as the right value
Enter 6 => If you wish to enter a new value to update both cache and hardware
Enter 7 => If you wish to skip the above record-keyword pair
Enter 0 => To exit successfully  5

|=======================================================================|
Disabled reboot
Sleep started, try to reboot
Sleep end
Sleep started
Enabled reboot

Data updated successfully.

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
3     VCEN    FC       0x373830432d303031            0x645602042d303031            YES
|======================================================================================================|

Enter 4 => If you choose the cache value as the right value
Enter 5 => If you choose hardware value as the right value
Enter 6 => If you wish to enter a new value to update both cache and hardware
Enter 7 => If you wish to skip the above record-keyword pair
Enter 0 => To exit successfully  4

|=======================================================================|
Disabled reboot
Sleep started, try to reboot
Sleep end
Sleep started
Enabled reboot

Data updated successfully.

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
4     VCEN    SE       RCH0014                       RCH0014                       NO
|======================================================================================================|

No mismatch found.

Enter 6 => If you wish to enter a new value to update both on BMC and System Backplane
Enter 7 => If you wish to skip the above record-keyword pair
Enter 0 => To exit successfully : 7

|======================================================================================================|

Skipped the above record-keyword pair. Continueing to the next pair if available.

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
10    VSYS    WN       0x748569                      0x645602040776754243453432    YES
|======================================================================================================|

Enter 4 => If you choose the cache value as the right value
Enter 5 => If you choose hardware value as the right value
Enter 6 => If you wish to enter a new value to update both cache and hardware
Enter 7 => If you wish to skip the above record-keyword pair
Enter 0 => To exit successfully  6

|=======================================================================|

Enter the new value to update both in cache & hardware (Value should be in ASCII or in HEX(prefixed with 0x)) : 0x433035303736304243453432

|=======================================================================|

Data updated successfully.

|======================================================================================================|
S.No  Record  Keyword  Data On Cache                 Data On Hardware              Data Mismatch
11    VSYS    RG       0x00000000                    0x00000000                    NO
|======================================================================================================|
No mismatch found. Skip this record-keyword pair.

Signed-off-by: Priyanga Ramasamy <priyanga24@in.ibm.com>
Change-Id: Ifb32efd1174360409b795b162282673a4f73df1b
diff --git a/vpd_tool_impl.cpp b/vpd_tool_impl.cpp
index 0d57351..10eba2e 100644
--- a/vpd_tool_impl.cpp
+++ b/vpd_tool_impl.cpp
@@ -1,6 +1,7 @@
 #include "vpd_tool_impl.hpp"
 
 #include "impl.hpp"
+#include "parser_factory.hpp"
 #include "vpd_exceptions.hpp"
 
 #include <cstdlib>
@@ -18,6 +19,8 @@
 using json = nlohmann::json;
 using namespace openpower::vpd::exceptions;
 using namespace openpower::vpd::parser;
+using namespace openpower::vpd::parser::factory;
+using namespace openpower::vpd::parser::interface;
 
 Binary VpdTool::toBinary(const std::string& value)
 {
@@ -548,3 +551,420 @@
                   << fruPath << std::endl;
     }
 }
+
+void VpdTool::printFixSystemVPDOption(UserOption option)
+{
+    switch (option)
+    {
+        case VpdTool::EXIT:
+            cout << "\nEnter 0 => To exit successfully : ";
+            break;
+        case VpdTool::BMC_DATA_FOR_ALL:
+            cout << "\n\nEnter 1 => If you choose the data on BMC for all "
+                    "mismatching record-keyword pairs";
+            break;
+        case VpdTool::SYSTEM_BACKPLANE_DATA_FOR_ALL:
+            cout << "\nEnter 2 => If you choose the data on System "
+                    "Backplane for all mismatching record-keyword pairs";
+            break;
+        case VpdTool::MORE_OPTIONS:
+            cout << "\nEnter 3 => If you wish to explore more options";
+            break;
+        case VpdTool::BMC_DATA_FOR_CURRENT:
+            cout << "\nEnter 4 => If you choose the data on BMC as the "
+                    "right value";
+            break;
+        case VpdTool::SYSTEM_BACKPLANE_DATA_FOR_CURRENT:
+            cout << "\nEnter 5 => If you choose the data on System "
+                    "Backplane as the right value";
+            break;
+        case VpdTool::NEW_VALUE_ON_BOTH:
+            cout << "\nEnter 6 => If you wish to enter a new value to "
+                    "update both on BMC and System Backplane";
+            break;
+        case VpdTool::SKIP_CURRENT:
+            cout << "\nEnter 7 => If you wish to skip the above "
+                    "record-keyword pair";
+            break;
+    }
+}
+
+int VpdTool::fixSystemVPD()
+{
+    cout << "\nRestorable record-keyword pairs and their data on BMC & "
+            "System Backplane.\n ";
+
+    cout << "\n|==============================================================="
+            "=======================================|"
+         << endl;
+
+    cout << left << setw(6) << "S.No" << left << setw(8) << "Record" << left
+         << setw(9) << "Keyword" << left << setw(30) << "Data On BMC" << left
+         << setw(30) << "Data On System Backplane" << left << setw(14)
+         << "Data Mismatch";
+
+    cout << "\n|==============================================================="
+            "=======================================|"
+         << endl;
+
+    int num = 0;
+
+    // Get system VPD data in map
+    Binary vpdVector{};
+    json js{};
+
+    auto jsonToParse = INVENTORY_JSON_DEFAULT;
+    if (fs::exists(INVENTORY_JSON_SYM_LINK))
+    {
+        jsonToParse = INVENTORY_JSON_SYM_LINK;
+    }
+
+    ifstream inventoryJson(jsonToParse);
+    if (!inventoryJson)
+    {
+        throw runtime_error("VPD JSON file not found");
+    }
+    js = json::parse(inventoryJson);
+
+    vpdVector = getVpdDataInVector(js, constants::systemVpdFilePath);
+    ParserInterface* parser = ParserFactory::getParser(vpdVector);
+    auto parseResult = parser->parse();
+    ParserFactory::freeParser(parser);
+
+    unordered_map<string, DbusPropertyMap> vpdMap;
+
+    if (auto pVal = get_if<Store>(&parseResult))
+    {
+        vpdMap = pVal->getVpdMap();
+    }
+    else
+    {
+        std::cerr << "\n System backplane VPD is not of type IPZ. Unable to "
+                     "parse the VPD "
+                  << constants::systemVpdFilePath << " . Exit with error."
+                  << std::endl;
+        exit(1);
+    }
+
+    // Get system VPD D-Bus Data and store it in a map
+    using GetAllResultType =
+        std::vector<std::pair<std::string, std::variant<Binary>>>;
+    using IntfPropMap = std::map<std::string, GetAllResultType>;
+
+    IntfPropMap svpdBusData;
+
+    const auto vsys = getAllDBusProperty<GetAllResultType>(
+        constants::pimIntf,
+        "/xyz/openbmc_project/inventory/system/chassis/motherboard",
+        "com.ibm.ipzvpd.VSYS");
+    svpdBusData.emplace("VSYS", vsys);
+
+    const auto vcen = getAllDBusProperty<GetAllResultType>(
+        constants::pimIntf,
+        "/xyz/openbmc_project/inventory/system/chassis/motherboard",
+        "com.ibm.ipzvpd.VCEN");
+    svpdBusData.emplace("VCEN", vcen);
+
+    const auto lxr0 = getAllDBusProperty<GetAllResultType>(
+        constants::pimIntf,
+        "/xyz/openbmc_project/inventory/system/chassis/motherboard",
+        "com.ibm.ipzvpd.LXR0");
+    svpdBusData.emplace("LXR0", lxr0);
+
+    const auto util = getAllDBusProperty<GetAllResultType>(
+        constants::pimIntf,
+        "/xyz/openbmc_project/inventory/system/chassis/motherboard",
+        "com.ibm.ipzvpd.UTIL");
+    svpdBusData.emplace("UTIL", util);
+
+    for (const auto& recordKw : svpdKwdMap)
+    {
+        string record = recordKw.first;
+
+        // Extract specific record data from the svpdBusData map.
+        const auto& rec = svpdBusData.find(record);
+
+        if (rec == svpdBusData.end())
+        {
+            std::cerr << record << " not a part of critical system VPD records."
+                      << std::endl;
+            continue;
+        }
+
+        const auto& recData = svpdBusData.find(record)->second;
+
+        string busStr{}, hwValStr{};
+        string mismatch = "NO"; // no mismatch
+
+        for (const auto& keyword : recordKw.second)
+        {
+            string hardwareValue{};
+            auto recItr = vpdMap.find(record);
+
+            if (recItr != vpdMap.end())
+            {
+                DbusPropertyMap& kwValMap = recItr->second;
+                auto kwItr = kwValMap.find(keyword);
+                if (kwItr != kwValMap.end())
+                {
+                    hardwareValue = kwItr->second;
+                }
+            }
+
+            std::variant<Binary> kwValue;
+            for (auto& kwData : recData)
+            {
+                if (kwData.first == keyword)
+                {
+                    kwValue = kwData.second;
+                    break;
+                }
+            }
+
+            if (keyword != "SE")
+            {
+                ostringstream hwValStream;
+                hwValStream << "0x";
+                hwValStr = hwValStream.str();
+
+                for (uint16_t byte : hardwareValue)
+                {
+                    hwValStream << setfill('0') << setw(2) << hex << byte;
+                    hwValStr = hwValStream.str();
+                }
+
+                if (const auto value = get_if<Binary>(&kwValue))
+                {
+                    busStr = byteArrayToHexString(*value);
+                }
+                if (busStr != hwValStr)
+                {
+                    mismatch = "YES";
+                }
+            }
+            else
+            {
+                if (const auto value = get_if<Binary>(&kwValue))
+                {
+                    busStr = getPrintableValue(*value);
+                }
+                if (busStr != hardwareValue)
+                {
+                    mismatch = "YES";
+                }
+                hwValStr = hardwareValue;
+            }
+            recKwData.push_back(
+                make_tuple(++num, record, keyword, busStr, hwValStr, mismatch));
+            cout << left << setw(6) << num << left << setw(8) << record << left
+                 << setw(9) << keyword << left << setw(30) << setfill(' ')
+                 << busStr << left << setw(30) << setfill(' ') << hwValStr
+                 << left << setw(14) << mismatch;
+
+            cout << "\n|--------------------------------------------------"
+                    "----------------------------------------------------|"
+                 << endl;
+        }
+    }
+    parseSVPDOptions(js);
+    return 0;
+}
+
+void VpdTool::parseSVPDOptions(const nlohmann::json& json)
+{
+    do
+    {
+        printFixSystemVPDOption(VpdTool::BMC_DATA_FOR_ALL);
+        printFixSystemVPDOption(VpdTool::SYSTEM_BACKPLANE_DATA_FOR_ALL);
+        printFixSystemVPDOption(VpdTool::MORE_OPTIONS);
+        printFixSystemVPDOption(VpdTool::EXIT);
+
+        int option = 0;
+        cin >> option;
+        cout << "\n|==========================================================="
+                "===========================================|"
+             << endl;
+
+        if (json.find("frus") == json.end())
+        {
+            throw runtime_error("Frus not found in json");
+        }
+
+        bool mismatchFound = false;
+
+        if (option == VpdTool::BMC_DATA_FOR_ALL)
+        {
+            for (const auto& data : recKwData)
+            {
+                if (get<5>(data) == "YES")
+                {
+                    EditorImpl edit(constants::systemVpdFilePath, json,
+                                    get<1>(data), get<2>(data));
+                    edit.updateKeyword(toBinary(get<3>(data)), 0, true);
+                    mismatchFound = true;
+                }
+            }
+
+            if (mismatchFound)
+            {
+                cout << "\nData updated successfully for all mismatching "
+                        "record-keyword pairs by choosing their corresponding "
+                        "data on BMC. Exit successfully.\n"
+                     << endl;
+            }
+            else
+            {
+                cout << "\nNo mismatch found for any of the above mentioned "
+                        "record-keyword pair. Exit successfully.\n";
+            }
+
+            exit(0);
+        }
+        else if (option == VpdTool::SYSTEM_BACKPLANE_DATA_FOR_ALL)
+        {
+            for (const auto& data : recKwData)
+            {
+                if (get<5>(data) == "YES")
+                {
+                    EditorImpl edit(constants::systemVpdFilePath, json,
+                                    get<1>(data), get<2>(data));
+                    edit.updateKeyword(toBinary(get<4>(data)), 0, true);
+                    mismatchFound = true;
+                }
+            }
+
+            if (mismatchFound)
+            {
+                cout << "\nData updated successfully for all mismatching "
+                        "record-keyword pairs by choosing their corresponding "
+                        "data on System Backplane.\n"
+                     << endl;
+            }
+            else
+            {
+                cout << "\nNo mismatch found for any of the above mentioned "
+                        "record-keyword pair. Exit successfully.\n";
+            }
+
+            exit(0);
+        }
+        else if (option == VpdTool::MORE_OPTIONS)
+        {
+            cout << "\nIterate through all restorable record-keyword pairs\n";
+
+            for (const auto& data : recKwData)
+            {
+                do
+                {
+                    cout << "\n|==============================================="
+                            "=================================================="
+                            "=====|"
+                         << endl;
+
+                    cout << left << setw(6) << "S.No" << left << setw(8)
+                         << "Record" << left << setw(9) << "Keyword" << left
+                         << setw(30) << setfill(' ') << "Data On BMC" << left
+                         << setw(30) << setfill(' ')
+                         << "Data On System Backplane" << left << setw(14)
+                         << "Data Mismatch" << endl;
+
+                    cout << left << setw(6) << get<0>(data) << left << setw(8)
+                         << get<1>(data) << left << setw(9) << get<2>(data)
+                         << left << setw(30) << setfill(' ') << get<3>(data)
+                         << left << setw(30) << setfill(' ') << get<4>(data)
+                         << left << setw(14) << get<5>(data);
+
+                    cout << "\n|==============================================="
+                            "=================================================="
+                            "=====|"
+                         << endl;
+
+                    if (get<5>(data) == "NO")
+                    {
+                        cout << "\nNo mismatch found.\n";
+                        printFixSystemVPDOption(VpdTool::NEW_VALUE_ON_BOTH);
+                        printFixSystemVPDOption(VpdTool::SKIP_CURRENT);
+                        printFixSystemVPDOption(VpdTool::EXIT);
+                    }
+                    else
+                    {
+                        printFixSystemVPDOption(VpdTool::BMC_DATA_FOR_CURRENT);
+                        printFixSystemVPDOption(
+                            VpdTool::SYSTEM_BACKPLANE_DATA_FOR_CURRENT);
+                        printFixSystemVPDOption(VpdTool::NEW_VALUE_ON_BOTH);
+                        printFixSystemVPDOption(VpdTool::SKIP_CURRENT);
+                        printFixSystemVPDOption(VpdTool::EXIT);
+                    }
+
+                    cin >> option;
+
+                    cout << "\n|==============================================="
+                            "=================================================="
+                            "=====|"
+                         << endl;
+
+                    EditorImpl edit(constants::systemVpdFilePath, json,
+                                    get<1>(data), get<2>(data));
+
+                    if (option == VpdTool::BMC_DATA_FOR_CURRENT)
+                    {
+                        edit.updateKeyword(toBinary(get<3>(data)), 0, true);
+                        cout << "\nData updated successfully.\n";
+                        break;
+                    }
+                    else if (option ==
+                             VpdTool::SYSTEM_BACKPLANE_DATA_FOR_CURRENT)
+                    {
+                        edit.updateKeyword(toBinary(get<4>(data)), 0, true);
+                        cout << "\nData updated successfully.\n";
+                        break;
+                    }
+                    else if (option == VpdTool::NEW_VALUE_ON_BOTH)
+                    {
+                        string value;
+                        cout << "\nEnter the new value to update both on BMC & "
+                                "System Backplane (Value should be in ASCII or "
+                                "in HEX(prefixed with 0x)) : ";
+                        cin >> value;
+                        cout << "\n|==========================================="
+                                "=============================================="
+                                "=============|"
+                             << endl;
+
+                        edit.updateKeyword(toBinary(value), 0, true);
+                        cout << "\nData updated successfully.\n";
+                        break;
+                    }
+                    else if (option == VpdTool::SKIP_CURRENT)
+                    {
+                        cout << "\nSkipped the above record-keyword pair. "
+                                "Continue to the next available pair.\n";
+                        break;
+                    }
+                    else if (option == VpdTool::EXIT)
+                    {
+                        cout << "\nExit successfully\n";
+                        exit(0);
+                    }
+                    else
+                    {
+                        cout << "\nProvide a valid option. Retrying for the "
+                                "current record-keyword pair\n";
+                    }
+                } while (1);
+            }
+            exit(0);
+        }
+        else if (option == VpdTool::EXIT)
+        {
+            cout << "\nExit successfully";
+            exit(0);
+        }
+        else
+        {
+            cout << "\nProvide a valid option. Retry.";
+            continue;
+        }
+
+    } while (true);
+}