blob: da829320246d1b56ed9c2b008c5830341a4a9a17 [file] [log] [blame]
Matt Spinler711d51d2019-11-06 09:36:51 -06001/**
2 * Copyright © 2019 IBM Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Aatir7b291ec2019-11-19 10:37:37 -060016#include "config.h"
17
18#include "../bcd_time.hpp"
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +080019#include "../json_utils.hpp"
Harisuddin Mohamed Isa0f717e12020-01-15 20:05:33 +080020#include "../paths.hpp"
Aatir186ce8c2019-10-20 15:13:39 -050021#include "../pel.hpp"
Aatir7b291ec2019-11-19 10:37:37 -060022#include "../pel_types.hpp"
23#include "../pel_values.hpp"
Aatir186ce8c2019-10-20 15:13:39 -050024
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +080025#include <Python.h>
26
Aatir186ce8c2019-10-20 15:13:39 -050027#include <CLI/CLI.hpp>
Aatir7b291ec2019-11-19 10:37:37 -060028#include <bitset>
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +080029#include <fstream>
Aatir186ce8c2019-10-20 15:13:39 -050030#include <iostream>
Aatir7b291ec2019-11-19 10:37:37 -060031#include <phosphor-logging/log.hpp>
32#include <regex>
Aatir186ce8c2019-10-20 15:13:39 -050033#include <string>
Aatir7b291ec2019-11-19 10:37:37 -060034#include <xyz/openbmc_project/Common/File/error.hpp>
Aatir186ce8c2019-10-20 15:13:39 -050035
Aatir7b291ec2019-11-19 10:37:37 -060036namespace fs = std::filesystem;
Aatir186ce8c2019-10-20 15:13:39 -050037using namespace phosphor::logging;
38using namespace openpower::pels;
Matt Spinler27de6f32020-02-21 08:35:57 -060039using sdbusplus::exception::SdBusError;
Aatir7b291ec2019-11-19 10:37:37 -060040namespace file_error = sdbusplus::xyz::openbmc_project::Common::File::Error;
41namespace message = openpower::pels::message;
42namespace pv = openpower::pels::pel_values;
Aatir186ce8c2019-10-20 15:13:39 -050043
Matt Spinler27de6f32020-02-21 08:35:57 -060044using PELFunc = std::function<void(const PEL&)>;
Matt Spinler0d804ef2020-05-12 16:16:26 -050045message::Registry registry(getPELReadOnlyDataPath() / message::registryFileName,
Matt Spinlerd8e29002020-04-09 09:11:22 -050046 false);
Matt Spinler27de6f32020-02-21 08:35:57 -060047namespace service
48{
49constexpr auto logging = "xyz.openbmc_project.Logging";
50} // namespace service
51
52namespace interface
53{
54constexpr auto deleteObj = "xyz.openbmc_project.Object.Delete";
55constexpr auto deleteAll = "xyz.openbmc_project.Collection.DeleteAll";
56} // namespace interface
57
58namespace object_path
59{
60constexpr auto logEntry = "/xyz/openbmc_project/logging/entry/";
61constexpr auto logging = "/xyz/openbmc_project/logging";
62} // namespace object_path
63
Aatire340c132019-12-09 14:19:29 -060064/**
Aatir37822f62019-12-10 14:40:27 -060065 * @brief helper function to get PEL commit timestamp from file name
66 * @retrun BCDTime - PEL commit timestamp
67 * @param[in] std::string - file name
68 */
69BCDTime fileNameToTimestamp(const std::string& fileName)
70{
71 std::string token = fileName.substr(0, fileName.find("_"));
72 int i = 0;
73 BCDTime tmp;
74 if (token.length() >= 14)
75 {
76 try
77 {
78 tmp.yearMSB = std::stoi(token.substr(i, 2), 0, 16);
79 }
80 catch (std::exception& err)
81 {
82 std::cout << "Conversion failure: " << err.what() << std::endl;
83 }
84 i += 2;
85 try
86 {
87 tmp.yearLSB = std::stoi(token.substr(i, 2), 0, 16);
88 }
89 catch (std::exception& err)
90 {
91 std::cout << "Conversion failure: " << err.what() << std::endl;
92 }
93 i += 2;
94 try
95 {
96 tmp.month = std::stoi(token.substr(i, 2), 0, 16);
97 }
98 catch (std::exception& err)
99 {
100 std::cout << "Conversion failure: " << err.what() << std::endl;
101 }
102 i += 2;
103 try
104 {
105 tmp.day = std::stoi(token.substr(i, 2), 0, 16);
106 }
107 catch (std::exception& err)
108 {
109 std::cout << "Conversion failure: " << err.what() << std::endl;
110 }
111 i += 2;
112 try
113 {
114 tmp.hour = std::stoi(token.substr(i, 2), 0, 16);
115 }
116 catch (std::exception& err)
117 {
118 std::cout << "Conversion failure: " << err.what() << std::endl;
119 }
120 i += 2;
121 try
122 {
123 tmp.minutes = std::stoi(token.substr(i, 2), 0, 16);
124 }
125 catch (std::exception& err)
126 {
127 std::cout << "Conversion failure: " << err.what() << std::endl;
128 }
129 i += 2;
130 try
131 {
132 tmp.seconds = std::stoi(token.substr(i, 2), 0, 16);
133 }
134 catch (std::exception& err)
135 {
136 std::cout << "Conversion failure: " << err.what() << std::endl;
137 }
138 i += 2;
139 try
140 {
141 tmp.hundredths = std::stoi(token.substr(i, 2), 0, 16);
142 }
143 catch (std::exception& err)
144 {
145 std::cout << "Conversion failure: " << err.what() << std::endl;
146 }
147 }
148 return tmp;
149}
150
151/**
152 * @brief helper function to get PEL id from file name
153 * @retrun uint32_t - PEL id
154 * @param[in] std::string - file name
155 */
156uint32_t fileNameToPELId(const std::string& fileName)
157{
158 uint32_t num = 0;
159 try
160 {
161 num = std::stoi(fileName.substr(fileName.find("_") + 1), 0, 16);
162 }
163 catch (std::exception& err)
164 {
165 std::cout << "Conversion failure: " << err.what() << std::endl;
166 }
167 return num;
168}
169
170/**
Aatire340c132019-12-09 14:19:29 -0600171 * @brief helper function to check string suffix
172 * @retrun bool - true with suffix matches
173 * @param[in] std::string - string to check for suffix
174 * @param[in] std::string - suffix string
175 */
176bool ends_with(const std::string& str, const std::string& end)
177{
178 size_t slen = str.size(), elen = end.size();
179 if (slen < elen)
180 return false;
181 while (elen)
182 {
183 if (str[--slen] != end[--elen])
184 return false;
185 }
186 return true;
187}
188
Aatir37822f62019-12-10 14:40:27 -0600189/**
190 * @brief get data form raw PEL file.
191 * @param[in] std::string Name of file with raw PEL
192 * @return std::vector<uint8_t> char vector read from raw PEL file.
193 */
Aatirbad5f8a2019-12-10 15:27:16 -0600194std::vector<uint8_t> getFileData(const std::string& name)
Aatir37822f62019-12-10 14:40:27 -0600195{
196 std::ifstream file(name, std::ifstream::in);
197 if (file.good())
198 {
199 std::vector<uint8_t> data{std::istreambuf_iterator<char>(file),
200 std::istreambuf_iterator<char>()};
201 return data;
202 }
203 else
204 {
Aatir37822f62019-12-10 14:40:27 -0600205 return {};
206 }
207}
208
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800209/**
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800210 * @brief Initialize Python interpreter and gather all UD parser modules under
211 * the paths found in Python sys.path and the current user directory.
212 * This is to prevent calling a non-existant module which causes Python
213 * to print an import error message and breaking JSON output.
214 *
215 * @return std::vector<std::string> Vector of plugins found in filesystem
216 */
217std::vector<std::string> getPlugins()
218{
219 Py_Initialize();
220 std::vector<std::string> plugins;
221 std::vector<std::string> siteDirs;
Harisuddin Mohamed Isac8d6cc62020-08-19 22:47:19 +0800222 std::array<std::string, 2> parserDirs = {"udparsers", "srcparsers"};
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800223 PyObject* pName = PyUnicode_FromString("sys");
224 PyObject* pModule = PyImport_Import(pName);
225 Py_XDECREF(pName);
226 PyObject* pDict = PyModule_GetDict(pModule);
227 Py_XDECREF(pModule);
228 PyObject* pResult = PyDict_GetItemString(pDict, "path");
229 PyObject* pValue = PyUnicode_FromString(".");
230 PyList_Append(pResult, pValue);
231 Py_XDECREF(pValue);
232 auto list_size = PyList_Size(pResult);
233 for (auto i = 0; i < list_size; i++)
234 {
235 PyObject* item = PyList_GetItem(pResult, i);
236 PyObject* pBytes = PyUnicode_AsEncodedString(item, "utf-8", "~E~");
237 const char* output = PyBytes_AS_STRING(pBytes);
238 Py_XDECREF(pBytes);
239 std::string tmpStr(output);
240 siteDirs.push_back(tmpStr);
241 }
242 for (const auto& dir : siteDirs)
243 {
Harisuddin Mohamed Isac8d6cc62020-08-19 22:47:19 +0800244 for (const auto& parserDir : parserDirs)
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800245 {
Harisuddin Mohamed Isac8d6cc62020-08-19 22:47:19 +0800246 if (fs::exists(dir + "/" + parserDir))
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800247 {
Harisuddin Mohamed Isac8d6cc62020-08-19 22:47:19 +0800248 for (const auto& entry :
249 fs::directory_iterator(dir + "/" + parserDir))
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800250 {
Harisuddin Mohamed Isac8d6cc62020-08-19 22:47:19 +0800251 if (entry.is_directory() and
252 fs::exists(entry.path().string() + "/" +
253 entry.path().stem().string() + ".py"))
254 {
255 plugins.push_back(entry.path().stem());
256 }
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800257 }
258 }
259 }
260 }
261 return plugins;
262}
263
264/**
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800265 * @brief Creates JSON string of a PEL entry if fullPEL is false or prints to
266 * stdout the full PEL in JSON if fullPEL is true
267 * @param[in] itr - std::map iterator of <uint32_t, BCDTime>
268 * @param[in] hidden - Boolean to include hidden PELs
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800269 * @param[in] includeInfo - Boolean to include informational PELs
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800270 * @param[in] fullPEL - Boolean to print full JSON representation of PEL
271 * @param[in] foundPEL - Boolean to check if any PEL is present
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800272 * @param[in] scrubRegex - SRC regex object
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800273 * @param[in] plugins - Vector of strings of plugins found in filesystem
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800274 * @return std::string - JSON string of PEL entry (empty if fullPEL is true)
275 */
Aatir7b291ec2019-11-19 10:37:37 -0600276template <typename T>
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800277std::string genPELJSON(T itr, bool hidden, bool includeInfo, bool fullPEL,
278 bool& foundPEL,
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800279 const std::optional<std::regex>& scrubRegex,
280 const std::vector<std::string>& plugins)
Aatir7b291ec2019-11-19 10:37:37 -0600281{
282 std::size_t found;
283 std::string val;
284 char tmpValStr[50];
285 std::string listStr;
286 char name[50];
287 sprintf(name, "%.2X%.2X%.2X%.2X%.2X%.2X%.2X%.2X_%.8X", itr.second.yearMSB,
288 itr.second.yearLSB, itr.second.month, itr.second.day,
289 itr.second.hour, itr.second.minutes, itr.second.seconds,
290 itr.second.hundredths, itr.first);
291 std::string fileName(name);
292 fileName = EXTENSION_PERSIST_DIR "/pels/logs/" + fileName;
293 try
294 {
Aatir37822f62019-12-10 14:40:27 -0600295 std::vector<uint8_t> data = getFileData(fileName);
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800296 if (data.empty())
Aatir37822f62019-12-10 14:40:27 -0600297 {
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800298 log<level::ERR>("Empty PEL file",
299 entry("FILENAME=%s", fileName.c_str()));
300 return listStr;
301 }
302 PEL pel{data};
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800303 if (!pel.valid())
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800304 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800305 return listStr;
306 }
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800307 if (!includeInfo && pel.userHeader().severity() == 0)
308 {
309 return listStr;
310 }
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800311 std::bitset<16> actionFlags{pel.userHeader().actionFlags()};
312 if (!hidden && actionFlags.test(hiddenFlagBit))
313 {
314 return listStr;
315 }
316 if (pel.primarySRC() && scrubRegex)
317 {
318 val = pel.primarySRC().value()->asciiString();
319 if (std::regex_search(trimEnd(val), scrubRegex.value(),
320 std::regex_constants::match_not_null))
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800321 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800322 return listStr;
323 }
324 }
325 if (fullPEL)
326 {
327 if (!foundPEL)
328 {
329 std::cout << "[\n";
330 foundPEL = true;
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800331 }
332 else
Aatir7b291ec2019-11-19 10:37:37 -0600333 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800334 std::cout << ",\n\n";
335 }
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800336 pel.toJSON(registry, plugins);
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800337 }
338 else
339 {
340 // id
341 listStr += "\t\"" +
342 getNumberString("0x%X", pel.privateHeader().id()) +
343 "\": {\n";
344 // ASCII
345 if (pel.primarySRC())
346 {
347 val = pel.primarySRC().value()->asciiString();
348 listStr += "\t\t\"SRC\": \"" + trimEnd(val) + "\",\n";
349 // Registry message
350 auto regVal = pel.primarySRC().value()->getErrorDetails(
351 registry, DetailLevel::message, true);
352 if (regVal)
Harisuddin Mohamed Isa0f717e12020-01-15 20:05:33 +0800353 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800354 val = regVal.value();
355 listStr += "\t\t\"Message\": \"" + val + "\",\n";
Aatir37822f62019-12-10 14:40:27 -0600356 }
Aatir7b291ec2019-11-19 10:37:37 -0600357 }
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800358 else
359 {
360 listStr += "\t\t\"SRC\": \"No SRC\",\n";
361 }
362 // platformid
363 listStr += "\t\t\"PLID\": \"" +
364 getNumberString("0x%X", pel.privateHeader().plid()) +
365 "\",\n";
366 // creatorid
367 std::string creatorID =
368 getNumberString("%c", pel.privateHeader().creatorID());
369 val = pv::creatorIDs.count(creatorID) ? pv::creatorIDs.at(creatorID)
370 : "Unknown Creator ID";
371 listStr += "\t\t\"CreatorID\": \"" + val + "\",\n";
372 // subsytem
373 std::string subsystem = pv::getValue(pel.userHeader().subsystem(),
374 pel_values::subsystemValues);
375 listStr += "\t\t\"Subsystem\": \"" + subsystem + "\",\n";
376 // commit time
377 sprintf(tmpValStr, "%02X/%02X/%02X%02X %02X:%02X:%02X",
378 pel.privateHeader().commitTimestamp().month,
379 pel.privateHeader().commitTimestamp().day,
380 pel.privateHeader().commitTimestamp().yearMSB,
381 pel.privateHeader().commitTimestamp().yearLSB,
382 pel.privateHeader().commitTimestamp().hour,
383 pel.privateHeader().commitTimestamp().minutes,
384 pel.privateHeader().commitTimestamp().seconds);
385 val = std::string(tmpValStr);
386 listStr += "\t\t\"Commit Time\": \"" + val + "\",\n";
387 // severity
388 std::string severity = pv::getValue(pel.userHeader().severity(),
389 pel_values::severityValues);
390 listStr += "\t\t\"Sev\": \"" + severity + "\",\n ";
391 // compID
392 listStr += "\t\t\"CompID\": \"" +
393 getNumberString(
394 "0x%X", pel.privateHeader().header().componentID) +
395 "\",\n ";
396 found = listStr.rfind(",");
397 if (found != std::string::npos)
398 {
399 listStr.replace(found, 1, "");
400 listStr += "\t},\n";
401 }
402 foundPEL = true;
Aatir7b291ec2019-11-19 10:37:37 -0600403 }
404 }
405 catch (std::exception& e)
406 {
407 log<level::ERR>("Hit exception while reading PEL File",
408 entry("FILENAME=%s", fileName.c_str()),
409 entry("ERROR=%s", e.what()));
410 }
411 return listStr;
412}
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800413
Aatir7b291ec2019-11-19 10:37:37 -0600414/**
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800415 * @brief Print a list of PELs or a JSON array of PELs
416 * @param[in] order - Boolean to print in reverse orser
417 * @param[in] hidden - Boolean to include hidden PELs
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800418 * @param[in] includeInfo - Boolean to include informational PELs
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800419 * @param[in] fullPEL - Boolean to print full PEL into a JSON array
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800420 * @param[in] scrubRegex - SRC regex object
Aatir7b291ec2019-11-19 10:37:37 -0600421 */
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800422void printPELs(bool order, bool hidden, bool includeInfo, bool fullPEL,
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800423 const std::optional<std::regex>& scrubRegex)
Aatir7b291ec2019-11-19 10:37:37 -0600424{
425 std::string listStr;
426 std::map<uint32_t, BCDTime> PELs;
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800427 std::vector<std::string> plugins;
Aatir7b291ec2019-11-19 10:37:37 -0600428 listStr = "{\n";
429 for (auto it = fs::directory_iterator(EXTENSION_PERSIST_DIR "/pels/logs");
430 it != fs::directory_iterator(); ++it)
431 {
432 if (!fs::is_regular_file((*it).path()))
433 {
434 continue;
435 }
Aatir37822f62019-12-10 14:40:27 -0600436 else
Aatir7b291ec2019-11-19 10:37:37 -0600437 {
Aatir37822f62019-12-10 14:40:27 -0600438 PELs.emplace(fileNameToPELId((*it).path().filename()),
439 fileNameToTimestamp((*it).path().filename()));
Aatir7b291ec2019-11-19 10:37:37 -0600440 }
441 }
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800442 bool foundPEL = false;
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800443 if (fullPEL)
444 {
445 plugins = getPlugins();
446 }
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800447 auto buildJSON = [&listStr, &hidden, &includeInfo, &fullPEL, &foundPEL,
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800448 &scrubRegex, &plugins](const auto& i) {
449 listStr += genPELJSON(i, hidden, includeInfo, fullPEL, foundPEL,
450 scrubRegex, plugins);
Aatir37822f62019-12-10 14:40:27 -0600451 };
Aatir7b291ec2019-11-19 10:37:37 -0600452 if (order)
453 {
454 std::for_each(PELs.rbegin(), PELs.rend(), buildJSON);
455 }
456 else
457 {
458 std::for_each(PELs.begin(), PELs.end(), buildJSON);
459 }
460
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800461 if (foundPEL)
Aatir7b291ec2019-11-19 10:37:37 -0600462 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800463 if (fullPEL)
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800464 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800465 std::cout << "]" << std::endl;
466 }
467 else
468 {
469 std::size_t found;
470 found = listStr.rfind(",");
471 if (found != std::string::npos)
472 {
473 listStr.replace(found, 1, "");
474 listStr += "}\n";
475 printf("%s", listStr.c_str());
476 }
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800477 }
478 }
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800479 else
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800480 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800481 std::string emptyJSON = fullPEL ? "[]" : "{}";
482 std::cout << emptyJSON << std::endl;
Aatir7b291ec2019-11-19 10:37:37 -0600483 }
484}
Aatir186ce8c2019-10-20 15:13:39 -0500485
Matt Spinler27de6f32020-02-21 08:35:57 -0600486/**
487 * @brief Calls the function passed in on the PEL with the ID
488 * passed in.
489 *
490 * @param[in] id - The string version of the PEL ID, either with or
491 * without the 0x prefix.
492 * @param[in] func - The std::function<void(const PEL&)> function to run.
493 */
494void callFunctionOnPEL(const std::string& id, const PELFunc& func)
495{
496 std::string pelID{id};
497 std::transform(pelID.begin(), pelID.end(), pelID.begin(), toupper);
498
499 if (pelID.find("0X") == 0)
500 {
501 pelID.erase(0, 2);
502 }
503
504 bool found = false;
505
506 for (auto it = fs::directory_iterator(EXTENSION_PERSIST_DIR "/pels/logs");
507 it != fs::directory_iterator(); ++it)
508 {
509 // The PEL ID is part of the filename, so use that to find the PEL.
510
511 if (!fs::is_regular_file((*it).path()))
512 {
513 continue;
514 }
515
516 if (ends_with((*it).path(), pelID))
517 {
518 found = true;
519
520 auto data = getFileData((*it).path());
521 if (!data.empty())
522 {
523 PEL pel{data};
524
525 try
526 {
527 func(pel);
528 }
529 catch (std::exception& e)
530 {
531 std::cerr
532 << " Internal function threw an exception: " << e.what()
533 << "\n";
534 exit(1);
535 }
536 }
537 else
538 {
539 std::cerr << "Could not read PEL file\n";
540 exit(1);
541 }
542 break;
543 }
544 }
545
546 if (!found)
547 {
548 std::cerr << "PEL not found\n";
549 exit(1);
550 }
551}
552
553/**
554 * @brief Delete a PEL by deleting its corresponding event log.
555 *
556 * @param[in] pel - The PEL to delete
557 */
558void deletePEL(const PEL& pel)
559{
560 std::string path{object_path::logEntry};
561 path += std::to_string(pel.obmcLogID());
562
563 try
564 {
565 auto bus = sdbusplus::bus::new_default();
566 auto method = bus.new_method_call(service::logging, path.c_str(),
567 interface::deleteObj, "Delete");
568 auto reply = bus.call(method);
569 }
570 catch (const SdBusError& e)
571 {
572 std::cerr << "D-Bus call to delete event log " << pel.obmcLogID()
573 << " failed: " << e.what() << "\n";
574 exit(1);
575 }
576}
577
578/**
579 * @brief Delete all PELs by deleting all event logs.
580 */
581void deleteAllPELs()
582{
583 try
584 {
585 // This may move to an audit log some day
586 log<level::INFO>("peltool deleting all event logs");
587
588 auto bus = sdbusplus::bus::new_default();
589 auto method =
590 bus.new_method_call(service::logging, object_path::logging,
591 interface::deleteAll, "DeleteAll");
592 auto reply = bus.call(method);
593 }
594 catch (const SdBusError& e)
595 {
596 std::cerr << "D-Bus call to delete all event logs failed: " << e.what()
597 << "\n";
598 exit(1);
599 }
600}
601
Matt Spinler1b420bc2020-02-21 08:54:25 -0600602/**
603 * @brief Display a single PEL
604 *
605 * @param[in] pel - the PEL to display
606 */
607void displayPEL(const PEL& pel)
608{
609 if (pel.valid())
610 {
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800611 auto plugins = getPlugins();
612 pel.toJSON(registry, plugins);
Matt Spinler1b420bc2020-02-21 08:54:25 -0600613 }
614 else
615 {
616 std::cerr << "PEL was malformed\n";
617 exit(1);
618 }
619}
620
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800621/**
622 * @brief Print number of PELs
623 * @param[in] hidden - Bool to include hidden logs
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800624 * @param[in] includeInfo - Bool to include informational logs
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800625 * @param[in] scrubRegex - SRC regex object
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800626 */
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800627void printPELCount(bool hidden, bool includeInfo,
628 const std::optional<std::regex>& scrubRegex)
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800629{
630 std::size_t count = 0;
631 for (auto it = fs::directory_iterator(EXTENSION_PERSIST_DIR "/pels/logs");
632 it != fs::directory_iterator(); ++it)
633 {
634 if (!fs::is_regular_file((*it).path()))
635 {
636 continue;
637 }
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800638 std::vector<uint8_t> data = getFileData((*it).path());
639 if (data.empty())
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800640 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800641 continue;
642 }
643 PEL pel{data};
644 if (!pel.valid())
645 {
646 continue;
647 }
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800648 if (!includeInfo && pel.userHeader().severity() == 0)
649 {
650 continue;
651 }
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800652 std::bitset<16> actionFlags{pel.userHeader().actionFlags()};
653 if (!hidden && actionFlags.test(hiddenFlagBit))
654 {
655 continue;
656 }
657 if (pel.primarySRC() && scrubRegex)
658 {
659 std::string val = pel.primarySRC().value()->asciiString();
660 if (std::regex_search(trimEnd(val), scrubRegex.value(),
661 std::regex_constants::match_not_null))
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800662 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800663 continue;
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800664 }
665 }
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800666 count++;
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800667 }
668 std::cout << "{\n"
669 << " \"Number of PELs found\": "
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800670 << getNumberString("%d", count) << "\n}\n";
671}
672
673/**
674 * @brief Generate regex pattern object from file contents
675 * @param[in] scrubFile - File containing regex pattern
676 * @return std::regex - SRC regex object
677 */
678std::regex genRegex(std::string& scrubFile)
679{
680 std::string pattern;
681 std::ifstream contents(scrubFile);
682 if (contents.fail())
683 {
684 std::cerr << "Can't open \"" << scrubFile << "\"\n";
685 exit(1);
686 }
687 std::string line;
688 while (std::getline(contents, line))
689 {
690 if (!line.empty())
691 {
692 pattern.append(line + "|");
693 }
694 }
695 try
696 {
697 std::regex scrubRegex(pattern, std::regex::icase);
698 return scrubRegex;
699 }
700 catch (std::regex_error& e)
701 {
702 if (e.code() == std::regex_constants::error_collate)
703 std::cerr << "Invalid collating element request\n";
704 else if (e.code() == std::regex_constants::error_ctype)
705 std::cerr << "Invalid character class\n";
706 else if (e.code() == std::regex_constants::error_escape)
707 std::cerr << "Invalid escape character or trailing escape\n";
708 else if (e.code() == std::regex_constants::error_backref)
709 std::cerr << "Invalid back reference\n";
710 else if (e.code() == std::regex_constants::error_brack)
711 std::cerr << "Mismatched bracket ([ or ])\n";
712 else if (e.code() == std::regex_constants::error_paren)
713 {
714 // to catch return code error_badrepeat when error_paren is retured
715 // instead
716 size_t pos = pattern.find_first_of("*+?{");
717 while (pos != std::string::npos)
718 {
719 if (pos == 0 || pattern.substr(pos - 1, 1) == "|")
720 {
721 std::cerr
722 << "A repetition character (*, ?, +, or {) was not "
723 "preceded by a valid regular expression\n";
724 exit(1);
725 }
726 pos = pattern.find_first_of("*+?{", pos + 1);
727 }
728 std::cerr << "Mismatched parentheses (( or ))\n";
729 }
730 else if (e.code() == std::regex_constants::error_brace)
731 std::cerr << "Mismatched brace ({ or })\n";
732 else if (e.code() == std::regex_constants::error_badbrace)
733 std::cerr << "Invalid range inside a { }\n";
734 else if (e.code() == std::regex_constants::error_range)
735 std::cerr << "Invalid character range (e.g., [z-a])\n";
736 else if (e.code() == std::regex_constants::error_space)
737 std::cerr << "Insufficient memory to handle regular expression\n";
738 else if (e.code() == std::regex_constants::error_badrepeat)
739 std::cerr << "A repetition character (*, ?, +, or {) was not "
740 "preceded by a valid regular expression\n";
741 else if (e.code() == std::regex_constants::error_complexity)
742 std::cerr << "The requested match is too complex\n";
743 else if (e.code() == std::regex_constants::error_stack)
744 std::cerr << "Insufficient memory to evaluate a match\n";
745 exit(1);
746 }
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800747}
748
Aatir186ce8c2019-10-20 15:13:39 -0500749static void exitWithError(const std::string& help, const char* err)
750{
751 std::cerr << "ERROR: " << err << std::endl << help << std::endl;
752 exit(-1);
753}
754
755int main(int argc, char** argv)
756{
757 CLI::App app{"OpenBMC PEL Tool"};
758 std::string fileName;
Aatire340c132019-12-09 14:19:29 -0600759 std::string idPEL;
Matt Spinler27de6f32020-02-21 08:35:57 -0600760 std::string idToDelete;
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800761 std::string scrubFile;
762 std::optional<std::regex> scrubRegex;
Aatire340c132019-12-09 14:19:29 -0600763 bool listPEL = false;
764 bool listPELDescOrd = false;
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800765 bool hidden = false;
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800766 bool includeInfo = false;
Matt Spinler27de6f32020-02-21 08:35:57 -0600767 bool deleteAll = false;
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800768 bool showPELCount = false;
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800769 bool fullPEL = false;
Matt Spinler27de6f32020-02-21 08:35:57 -0600770
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800771 app.set_help_flag("--help", "Print this help message and exit");
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800772 app.add_option("--file", fileName, "Display a PEL using its Raw PEL file");
Aatire340c132019-12-09 14:19:29 -0600773 app.add_option("-i, --id", idPEL, "Display a PEL based on its ID");
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800774 app.add_flag("-a", fullPEL, "Display all PELs");
Aatirbad5f8a2019-12-10 15:27:16 -0600775 app.add_flag("-l", listPEL, "List PELs");
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800776 app.add_flag("-n", showPELCount, "Show number of PELs");
Aatir7b291ec2019-11-19 10:37:37 -0600777 app.add_flag("-r", listPELDescOrd, "Reverse order of output");
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800778 app.add_flag("-h", hidden, "Include hidden PELs");
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800779 app.add_flag("-f,--info", includeInfo, "Include informational PELs");
Matt Spinler27de6f32020-02-21 08:35:57 -0600780 app.add_option("-d, --delete", idToDelete, "Delete a PEL based on its ID");
781 app.add_flag("-D, --delete-all", deleteAll, "Delete all PELs");
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800782 app.add_option("-s, --scrub", scrubFile,
783 "File containing SRC regular expressions to ignore");
Matt Spinler27de6f32020-02-21 08:35:57 -0600784
Aatir186ce8c2019-10-20 15:13:39 -0500785 CLI11_PARSE(app, argc, argv);
786
787 if (!fileName.empty())
788 {
789 std::vector<uint8_t> data = getFileData(fileName);
790 if (!data.empty())
791 {
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800792 auto plugins = getPlugins();
Aatir186ce8c2019-10-20 15:13:39 -0500793 PEL pel{data};
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800794 pel.toJSON(registry, plugins);
Aatir186ce8c2019-10-20 15:13:39 -0500795 }
796 else
797 {
798 exitWithError(app.help("", CLI::AppFormatMode::All),
799 "Raw PEL file can't be read.");
800 }
801 }
Aatire340c132019-12-09 14:19:29 -0600802 else if (!idPEL.empty())
803 {
Matt Spinler1b420bc2020-02-21 08:54:25 -0600804 callFunctionOnPEL(idPEL, displayPEL);
Aatire340c132019-12-09 14:19:29 -0600805 }
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800806 else if (fullPEL || listPEL)
Aatir7b291ec2019-11-19 10:37:37 -0600807 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800808 if (!scrubFile.empty())
809 {
810 scrubRegex = genRegex(scrubFile);
811 }
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800812 printPELs(listPELDescOrd, hidden, includeInfo, fullPEL, scrubRegex);
Harisuddin Mohamed Isad4002f32020-02-26 16:19:58 +0800813 }
814 else if (showPELCount)
815 {
Harisuddin Mohamed Isa6f005192020-03-10 17:39:53 +0800816 if (!scrubFile.empty())
817 {
818 scrubRegex = genRegex(scrubFile);
819 }
Harisuddin Mohamed Isa0c57a672020-03-27 14:16:28 +0800820 printPELCount(hidden, includeInfo, scrubRegex);
Aatir7b291ec2019-11-19 10:37:37 -0600821 }
Matt Spinler27de6f32020-02-21 08:35:57 -0600822 else if (!idToDelete.empty())
823 {
824 callFunctionOnPEL(idToDelete, deletePEL);
825 }
826 else if (deleteAll)
827 {
828 deleteAllPELs();
829 }
Aatir186ce8c2019-10-20 15:13:39 -0500830 else
831 {
Harisuddin Mohamed Isaa214ed32020-02-28 15:58:23 +0800832 std::cout << app.help("", CLI::AppFormatMode::All) << std::endl;
Aatir186ce8c2019-10-20 15:13:39 -0500833 }
Harisuddin Mohamed Isaf67bafd2020-07-06 17:51:21 +0800834 Py_Finalize();
Aatir186ce8c2019-10-20 15:13:39 -0500835 return 0;
836}