summaryrefslogtreecommitdiffstats
path: root/extensions/openpower-pels/tools/peltool.cpp
blob: ed6daa255128e7425d209e739010288c26d2fdf4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
 * Copyright © 2019 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "config.h"

#include "../bcd_time.hpp"
#include "../paths.hpp"
#include "../pel.hpp"
#include "../pel_types.hpp"
#include "../pel_values.hpp"

#include <CLI/CLI.hpp>
#include <bitset>
#include <iostream>
#include <phosphor-logging/log.hpp>
#include <regex>
#include <string>
#include <xyz/openbmc_project/Common/File/error.hpp>

namespace fs = std::filesystem;
using namespace phosphor::logging;
using namespace openpower::pels;
namespace file_error = sdbusplus::xyz::openbmc_project::Common::File::Error;
namespace message = openpower::pels::message;
namespace pv = openpower::pels::pel_values;

/**
 * @brief helper function to get PEL commit timestamp from file name
 * @retrun BCDTime - PEL commit timestamp
 * @param[in] std::string - file name
 */
BCDTime fileNameToTimestamp(const std::string& fileName)
{
    std::string token = fileName.substr(0, fileName.find("_"));
    int i = 0;
    BCDTime tmp;
    if (token.length() >= 14)
    {
        try
        {
            tmp.yearMSB = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.yearLSB = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.month = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.day = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.hour = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.minutes = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.seconds = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
        i += 2;
        try
        {
            tmp.hundredths = std::stoi(token.substr(i, 2), 0, 16);
        }
        catch (std::exception& err)
        {
            std::cout << "Conversion failure: " << err.what() << std::endl;
        }
    }
    return tmp;
}

/**
 * @brief helper function to get PEL id from file name
 * @retrun uint32_t - PEL id
 * @param[in] std::string - file name
 */
uint32_t fileNameToPELId(const std::string& fileName)
{
    uint32_t num = 0;
    try
    {
        num = std::stoi(fileName.substr(fileName.find("_") + 1), 0, 16);
    }
    catch (std::exception& err)
    {
        std::cout << "Conversion failure: " << err.what() << std::endl;
    }
    return num;
}

/**
 * @brief helper function to check string suffix
 * @retrun bool - true with suffix matches
 * @param[in] std::string - string to check for suffix
 * @param[in] std::string - suffix string
 */
bool ends_with(const std::string& str, const std::string& end)
{
    size_t slen = str.size(), elen = end.size();
    if (slen < elen)
        return false;
    while (elen)
    {
        if (str[--slen] != end[--elen])
            return false;
    }
    return true;
}

/**
 * @brief get data form raw PEL file.
 * @param[in] std::string Name of file with raw PEL
 * @return std::vector<uint8_t> char vector read from raw PEL file.
 */
std::vector<uint8_t> getFileData(const std::string& name)
{
    std::ifstream file(name, std::ifstream::in);
    if (file.good())
    {
        std::vector<uint8_t> data{std::istreambuf_iterator<char>(file),
                                  std::istreambuf_iterator<char>()};
        return data;
    }
    else
    {
        printf("Can't open raw PEL file");
        return {};
    }
}

template <typename T>
std::string genPELJSON(T itr, bool hidden, message::Registry& registry)
{
    std::size_t found;
    std::string val;
    char tmpValStr[50];
    std::string listStr;
    char name[50];
    sprintf(name, "%.2X%.2X%.2X%.2X%.2X%.2X%.2X%.2X_%.8X", itr.second.yearMSB,
            itr.second.yearLSB, itr.second.month, itr.second.day,
            itr.second.hour, itr.second.minutes, itr.second.seconds,
            itr.second.hundredths, itr.first);
    std::string fileName(name);
    fileName = EXTENSION_PERSIST_DIR "/pels/logs/" + fileName;
    try
    {
        std::vector<uint8_t> data = getFileData(fileName);
        if (!data.empty())
        {
            PEL pel{data};
            std::bitset<16> actionFlags{pel.userHeader().actionFlags()};
            if (pel.valid() && (hidden || !actionFlags.test(hiddenFlagBit)))
            {
                // id
                sprintf(tmpValStr, "0x%X", pel.privateHeader().id());
                val = std::string(tmpValStr);
                listStr += "\t\"" + val + "\": {\n";
                // ASCII
                if (pel.primarySRC())
                {
                    val = pel.primarySRC().value()->asciiString();
                    listStr += "\t\t\"SRC\": \"" +
                               val.substr(0, val.find(0x20)) + "\",\n";
                    // Registry message
                    auto regVal = pel.primarySRC().value()->getErrorDetails(
                        registry, DetailLevel::message, true);
                    if (regVal)
                    {
                        val = regVal.value();
                        listStr += "\t\t\"Message\": \"" + val + "\",\n";
                    }
                }
                else
                {
                    listStr += "\t\t\"SRC\": \"No SRC\",\n";
                }
                // platformid
                sprintf(tmpValStr, "0x%X", pel.privateHeader().plid());
                val = std::string(tmpValStr);
                listStr += "\t\t\"PLID\": \"" + val + "\",\n";
                // creatorid
                sprintf(tmpValStr, "%c", pel.privateHeader().creatorID());
                std::string creatorID(tmpValStr);
                val = pv::creatorIDs.count(creatorID)
                          ? pv::creatorIDs.at(creatorID)
                          : "Unknown Creator ID";
                listStr += "\t\t\"CreatorID\": \"" + val + "\",\n";
                // subsytem
                std::string subsystem = pv::getValue(
                    pel.userHeader().subsystem(), pel_values::subsystemValues);
                listStr += "\t\t\"Subsystem\": \"" + subsystem + "\",\n";
                // commit time
                sprintf(tmpValStr, "%02X/%02X/%02X%02X  %02X:%02X:%02X",
                        pel.privateHeader().commitTimestamp().month,
                        pel.privateHeader().commitTimestamp().day,
                        pel.privateHeader().commitTimestamp().yearMSB,
                        pel.privateHeader().commitTimestamp().yearLSB,
                        pel.privateHeader().commitTimestamp().hour,
                        pel.privateHeader().commitTimestamp().minutes,
                        pel.privateHeader().commitTimestamp().seconds);
                val = std::string(tmpValStr);
                listStr += "\t\t\"Commit Time\": \"" + val + "\",\n";
                // severity
                std::string severity = pv::getValue(pel.userHeader().severity(),
                                                    pel_values::severityValues);
                listStr += "\t\t\"Sev\": \"" + severity + "\",\n ";
                // compID
                sprintf(tmpValStr, "0x%X",
                        pel.privateHeader().header().componentID);
                val = std::string(tmpValStr);
                listStr += "\t\t\"CompID\": \"" + val + "\",\n ";

                found = listStr.rfind(",");
                if (found != std::string::npos)
                {
                    listStr.replace(found, 1, "");
                    listStr += "\t}, \n";
                }
            }
        }
        else
        {
            log<level::ERR>("Empty PEL file",
                            entry("FILENAME=%s", fileName.c_str()),
                            entry("ERROR=%s", "Empty PEL file"));
        }
    }
    catch (std::exception& e)
    {
        log<level::ERR>("Hit exception while reading PEL File",
                        entry("FILENAME=%s", fileName.c_str()),
                        entry("ERROR=%s", e.what()));
    }
    return listStr;
}
/**
 * @brief Print a list of PELs
 */
void printList(bool order, bool hidden)
{
    std::string listStr;
    std::map<uint32_t, BCDTime> PELs;
    std::size_t found;
    listStr = "{\n";
    for (auto it = fs::directory_iterator(EXTENSION_PERSIST_DIR "/pels/logs");
         it != fs::directory_iterator(); ++it)
    {
        if (!fs::is_regular_file((*it).path()))
        {
            continue;
        }
        else
        {
            PELs.emplace(fileNameToPELId((*it).path().filename()),
                         fileNameToTimestamp((*it).path().filename()));
        }
    }
    message::Registry registry(getMessageRegistryPath() /
                               message::registryFileName);
    auto buildJSON = [&listStr, &hidden, &registry](const auto& i) {
        listStr += genPELJSON(i, hidden, registry);
    };
    if (order)
    {
        std::for_each(PELs.rbegin(), PELs.rend(), buildJSON);
    }
    else
    {
        std::for_each(PELs.begin(), PELs.end(), buildJSON);
    }

    found = listStr.rfind(",");
    if (found != std::string::npos)
    {
        listStr.replace(found, 1, "");
        listStr += "\n}\n";
        printf("%s", listStr.c_str());
    }
}

static void exitWithError(const std::string& help, const char* err)
{
    std::cerr << "ERROR: " << err << std::endl << help << std::endl;
    exit(-1);
}

int main(int argc, char** argv)
{
    CLI::App app{"OpenBMC PEL Tool"};
    std::string fileName;
    std::string idPEL;
    bool listPEL = false;
    bool listPELDescOrd = false;
    bool listPELShowHidden = false;
    app.add_option("-f,--file", fileName,
                   "Display a PEL using its Raw PEL file");
    app.add_option("-i, --id", idPEL, "Display a PEL based on its ID");
    app.add_flag("-l", listPEL, "List PELs");
    app.add_flag("-r", listPELDescOrd, "Reverse order of output");
    app.add_flag("-s", listPELShowHidden, "Show hidden PELs");
    CLI11_PARSE(app, argc, argv);

    if (!fileName.empty())
    {
        std::vector<uint8_t> data = getFileData(fileName);
        if (!data.empty())
        {
            PEL pel{data};
            pel.toJSON();
        }
        else
        {
            exitWithError(app.help("", CLI::AppFormatMode::All),
                          "Raw PEL file can't be read.");
        }
    }

    else if (!idPEL.empty())
    {
        for (auto it =
                 fs::directory_iterator(EXTENSION_PERSIST_DIR "/pels/logs");
             it != fs::directory_iterator(); ++it)
        {
            if (!fs::is_regular_file((*it).path()))
            {
                continue;
            }
            try
            {
                for (auto& c : idPEL)
                    c = toupper(c);
                size_t found = idPEL.find("0X");
                if (found == 0)
                {
                    idPEL.erase(0, 2);
                }
                if (ends_with((*it).path(), idPEL))
                {
                    std::vector<uint8_t> data = getFileData((*it).path());
                    if (!data.empty())
                    {
                        PEL pel{data};
                        if (pel.valid())
                        {
                            pel.toJSON();
                        }
                        else
                        {
                            log<level::ERR>(
                                "PEL File contains invalid PEL",
                                entry("FILENAME=%s", (*it).path().c_str()),
                                entry("ERROR=%s", "file contains invalid PEL"));
                        }
                    }
                    break;
                }
            }
            catch (std::exception& e)
            {
                log<level::ERR>("Hit exception while reading PEL File",
                                entry("FILENAME=%s", (*it).path().c_str()),
                                entry("ERROR=%s", e.what()));
            }
        }
    }
    else if (listPEL)
    {

        printList(listPELDescOrd, listPELShowHidden);
    }
    else
    {
        exitWithError(app.help("", CLI::AppFormatMode::All),
                      "Raw PEL file path not specified.");
    }
    return 0;
}
OpenPOWER on IntegriCloud