xref: /openbmc/phosphor-logging/test/openpower-pels/pel_manager_test.cpp (revision 40fb54935ce7367636a7156039396ee91cc4d5e2)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright 2019 IBM Corporation
3 
4 #include "extensions/openpower-pels/manager.hpp"
5 #include "log_manager.hpp"
6 #include "mocks.hpp"
7 #include "pel_utils.hpp"
8 
9 #include <sdbusplus/test/sdbus_mock.hpp>
10 #include <xyz/openbmc_project/Common/error.hpp>
11 
12 #include <fstream>
13 #include <regex>
14 
15 #include <gtest/gtest.h>
16 
17 using namespace openpower::pels;
18 namespace fs = std::filesystem;
19 
20 using ::testing::NiceMock;
21 using ::testing::Return;
22 using json = nlohmann::json;
23 
24 class TestLogger
25 {
26   public:
log(const std::string & name,phosphor::logging::Entry::Level level,const EventLogger::ADMap & additionalData)27     void log(const std::string& name, phosphor::logging::Entry::Level level,
28              const EventLogger::ADMap& additionalData)
29     {
30         errName = name;
31         errLevel = level;
32         ad = additionalData;
33     }
34 
35     std::string errName;
36     phosphor::logging::Entry::Level errLevel;
37     EventLogger::ADMap ad;
38 };
39 
40 class ManagerTest : public CleanPELFiles
41 {
42   public:
ManagerTest()43     ManagerTest() :
44         bus(sdbusplus::get_mocked_new(&sdbusInterface)),
45         logManager(bus, "logging_path")
46     {
47         sd_event_default(&sdEvent);
48     }
49 
makeTempDir()50     fs::path makeTempDir()
51     {
52         char path[] = "/tmp/tempnameXXXXXX";
53         std::filesystem::path dir = mkdtemp(path);
54         dirsToRemove.push_back(dir);
55         return dir;
56     }
57 
~ManagerTest()58     ~ManagerTest()
59     {
60         for (const auto& d : dirsToRemove)
61         {
62             std::filesystem::remove_all(d);
63         }
64         sd_event_unref(sdEvent);
65     }
66 
67     NiceMock<sdbusplus::SdBusMock> sdbusInterface;
68     sdbusplus::bus_t bus;
69     phosphor::logging::internal::Manager logManager;
70     sd_event* sdEvent;
71     TestLogger logger;
72     std::vector<std::filesystem::path> dirsToRemove;
73 };
74 
findAnyPELInRepo()75 std::optional<fs::path> findAnyPELInRepo()
76 {
77     // PELs are named <timestamp>_<ID>
78     std::regex expr{"\\d+_\\d+"};
79 
80     for (auto& f : fs::directory_iterator(getPELRepoPath() / "logs"))
81     {
82         if (std::regex_search(f.path().string(), expr))
83         {
84             return f.path();
85         }
86     }
87     return std::nullopt;
88 }
89 
countPELsInRepo()90 size_t countPELsInRepo()
91 {
92     size_t count = 0;
93     std::regex expr{"\\d+_\\d+"};
94 
95     for (auto& f : fs::directory_iterator(getPELRepoPath() / "logs"))
96     {
97         if (std::regex_search(f.path().string(), expr))
98         {
99             count++;
100         }
101     }
102     return count;
103 }
104 
deletePELFile(uint32_t id)105 void deletePELFile(uint32_t id)
106 {
107     char search[20];
108 
109     sprintf(search, "\\d+_%.8X", id);
110     std::regex expr{search};
111 
112     for (auto& f : fs::directory_iterator(getPELRepoPath() / "logs"))
113     {
114         if (std::regex_search(f.path().string(), expr))
115         {
116             fs::remove(f.path());
117             break;
118         }
119     }
120 }
121 
122 // Test that using the RAWPEL=<file> with the Manager::create() call gets
123 // a PEL saved in the repository.
TEST_F(ManagerTest,TestCreateWithPEL)124 TEST_F(ManagerTest, TestCreateWithPEL)
125 {
126     std::unique_ptr<DataInterfaceBase> dataIface =
127         std::make_unique<MockDataInterface>();
128 
129     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
130 
131     openpower::pels::Manager manager{
132         logManager, std::move(dataIface),
133         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
134                   std::placeholders::_2, std::placeholders::_3),
135         std::move(journal)};
136 
137     // Create a PEL, write it to a file, and pass that filename into
138     // the create function.
139     auto data = pelDataFactory(TestPELType::pelSimple);
140 
141     fs::path pelFilename = makeTempDir() / "rawpel";
142     std::ofstream pelFile{pelFilename};
143     pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
144     pelFile.close();
145 
146     std::map<std::string, std::string> additionalData{
147         {"RAWPEL", pelFilename.string()}};
148     std::vector<std::string> associations;
149 
150     manager.create("error message", 42, 0,
151                    phosphor::logging::Entry::Level::Error, additionalData,
152                    associations);
153 
154     // Find the file in the PEL repository directory
155     auto pelPathInRepo = findAnyPELInRepo();
156 
157     EXPECT_TRUE(pelPathInRepo);
158 
159     // Now remove it based on its OpenBMC event log ID
160     manager.erase(42);
161 
162     pelPathInRepo = findAnyPELInRepo();
163 
164     EXPECT_FALSE(pelPathInRepo);
165 }
166 
TEST_F(ManagerTest,TestCreateWithInvalidPEL)167 TEST_F(ManagerTest, TestCreateWithInvalidPEL)
168 {
169     std::unique_ptr<DataInterfaceBase> dataIface =
170         std::make_unique<MockDataInterface>();
171 
172     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
173 
174     openpower::pels::Manager manager{
175         logManager, std::move(dataIface),
176         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
177                   std::placeholders::_2, std::placeholders::_3),
178         std::move(journal)};
179 
180     // Create a PEL, write it to a file, and pass that filename into
181     // the create function.
182     auto data = pelDataFactory(TestPELType::pelSimple);
183 
184     // Truncate it to make it invalid.
185     data.resize(200);
186 
187     fs::path pelFilename = makeTempDir() / "rawpel";
188     std::ofstream pelFile{pelFilename};
189     pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
190     pelFile.close();
191 
192     std::map<std::string, std::string> additionalData{
193         {"RAWPEL", pelFilename.string()}};
194     std::vector<std::string> associations;
195 
196     manager.create("error message", 42, 0,
197                    phosphor::logging::Entry::Level::Error, additionalData,
198                    associations);
199 
200     // Run the event loop to log the bad PEL event
201     sdeventplus::Event e{sdEvent};
202     e.run(std::chrono::milliseconds(1));
203 
204     PEL invalidPEL{data};
205     EXPECT_EQ(logger.errName, "org.open_power.Logging.Error.BadHostPEL");
206     EXPECT_EQ(logger.errLevel, phosphor::logging::Entry::Level::Error);
207     EXPECT_EQ(std::stoi(logger.ad["PLID"], nullptr, 16), invalidPEL.plid());
208     EXPECT_EQ(logger.ad["OBMC_LOG_ID"], "42");
209     EXPECT_EQ(logger.ad["SRC"], (*invalidPEL.primarySRC())->asciiString());
210     EXPECT_EQ(logger.ad["PEL_SIZE"], std::to_string(data.size()));
211 
212     // Check that the bad PEL data was saved to a file.
213     auto badPELData = readPELFile(getPELRepoPath() / "badPEL");
214     EXPECT_EQ(*badPELData, data);
215 }
216 
217 // Test that the message registry can be used to build a PEL.
TEST_F(ManagerTest,TestCreateWithMessageRegistry)218 TEST_F(ManagerTest, TestCreateWithMessageRegistry)
219 {
220     const auto registry = R"(
221 {
222     "PELs":
223     [
224         {
225             "Name": "xyz.openbmc_project.Error.Test",
226             "Subsystem": "power_supply",
227             "ActionFlags": ["service_action", "report"],
228             "SRC":
229             {
230                 "ReasonCode": "0x2030"
231             },
232             "Callouts": [
233                 {
234                     "CalloutList": [
235                         {"Priority": "high", "Procedure": "BMC0001"},
236                         {"Priority": "medium", "SymbolicFRU": "service_docs"}
237                     ]
238                 }
239             ],
240             "Documentation":
241             {
242                 "Description": "A PGOOD Fault",
243                 "Message": "PS had a PGOOD Fault"
244             }
245         },
246         {
247             "Name": "xyz.openbmc_project.Logging.Error.Default",
248             "Subsystem": "bmc_firmware",
249             "SRC":
250             {
251                 "ReasonCode": "0x2031"
252             },
253             "Documentation":
254             {
255                 "Description": "The entry used when no match found",
256                 "Message": "This is a generic SRC"
257             }
258         }
259     ]
260 }
261 )";
262 
263     auto path = getPELReadOnlyDataPath();
264     fs::create_directories(path);
265     path /= "message_registry.json";
266 
267     std::ofstream registryFile{path};
268     registryFile << registry;
269     registryFile.close();
270 
271     std::unique_ptr<DataInterfaceBase> dataIface =
272         std::make_unique<MockDataInterface>();
273 
274     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
275 
276     openpower::pels::Manager manager{
277         logManager, std::move(dataIface),
278         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
279                   std::placeholders::_2, std::placeholders::_3),
280         std::move(journal)};
281 
282     std::map<std::string, std::string> additionalData{{"FOO", "BAR"}};
283     std::vector<std::string> associations;
284 
285     // Create the event log to create the PEL from.
286     manager.create("xyz.openbmc_project.Error.Test", 33, 0,
287                    phosphor::logging::Entry::Level::Error, additionalData,
288                    associations);
289 
290     // Ensure a PEL was created in the repository
291     auto pelFile = findAnyPELInRepo();
292     ASSERT_TRUE(pelFile);
293 
294     auto data = readPELFile(*pelFile);
295     PEL pel(*data);
296 
297     // Spot check it.  Other testcases cover the details.
298     EXPECT_TRUE(pel.valid());
299     EXPECT_EQ(pel.obmcLogID(), 33);
300     EXPECT_EQ(pel.primarySRC().value()->asciiString(),
301               "BD612030                        ");
302     // Check if the eventId creation is good
303     EXPECT_EQ(manager.getEventId(pel),
304               "BD612030 00000055 00000010 00000000 00000000 00000000 00000000 "
305               "00000000 00000000");
306     // Check if resolution property creation is good
307     EXPECT_EQ(manager.getResolution(pel),
308               "1. Priority: High, Procedure: BMC0001\n2. Priority: Medium, PN: "
309               "SVCDOCS\n");
310 
311     // Remove it
312     manager.erase(33);
313     pelFile = findAnyPELInRepo();
314     EXPECT_FALSE(pelFile);
315 
316     // Create an event log that can't be found in the registry.
317     // In this case, xyz.openbmc_project.Logging.Error.Default will
318     // be used as the key instead to find a registry match.
319     manager.create("xyz.openbmc_project.Error.Foo", 42, 0,
320                    phosphor::logging::Entry::Level::Error, additionalData,
321                    associations);
322 
323     // Ensure a PEL was still created in the repository
324     pelFile = findAnyPELInRepo();
325     ASSERT_TRUE(pelFile);
326 
327     data = readPELFile(*pelFile);
328     PEL newPEL(*data);
329 
330     EXPECT_TRUE(newPEL.valid());
331     EXPECT_EQ(newPEL.obmcLogID(), 42);
332     EXPECT_EQ(newPEL.primarySRC().value()->asciiString(),
333               "BD8D2031                        ");
334 
335     // Check for both the original AdditionalData item as well as
336     // the ERROR_NAME item that should contain the error message
337     // property that wasn't found.
338     std::string errorName;
339     std::string adItem;
340 
341     for (const auto& section : newPEL.optionalSections())
342     {
343         if (SectionID::userData == static_cast<SectionID>(section->header().id))
344         {
345             if (UserDataFormat::json ==
346                 static_cast<UserDataFormat>(section->header().subType))
347             {
348                 auto ud = static_cast<UserData*>(section.get());
349 
350                 // Check that there was a UserData section added that
351                 // contains debug details about the device.
352                 const auto& d = ud->data();
353                 std::string jsonString{d.begin(), d.end()};
354                 auto json = nlohmann::json::parse(jsonString);
355 
356                 if (json.contains("ERROR_NAME"))
357                 {
358                     errorName = json["ERROR_NAME"].get<std::string>();
359                 }
360 
361                 if (json.contains("FOO"))
362                 {
363                     adItem = json["FOO"].get<std::string>();
364                 }
365             }
366         }
367         if (!errorName.empty())
368         {
369             break;
370         }
371     }
372 
373     EXPECT_EQ(errorName, "xyz.openbmc_project.Error.Foo");
374     EXPECT_EQ(adItem, "BAR");
375 }
376 
TEST_F(ManagerTest,TestDBusMethods)377 TEST_F(ManagerTest, TestDBusMethods)
378 {
379     std::unique_ptr<DataInterfaceBase> dataIface =
380         std::make_unique<MockDataInterface>();
381 
382     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
383 
384     Manager manager{
385         logManager, std::move(dataIface),
386         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
387                   std::placeholders::_2, std::placeholders::_3),
388         std::move(journal)};
389 
390     // Create a PEL, write it to a file, and pass that filename into
391     // the create function so there's one in the repo.
392     auto data = pelDataFactory(TestPELType::pelSimple);
393 
394     fs::path pelFilename = makeTempDir() / "rawpel";
395     std::ofstream pelFile{pelFilename};
396     pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
397     pelFile.close();
398 
399     std::map<std::string, std::string> additionalData{
400         {"RAWPEL", pelFilename.string()}};
401     std::vector<std::string> associations;
402 
403     manager.create("error message", 42, 0,
404                    phosphor::logging::Entry::Level::Error, additionalData,
405                    associations);
406 
407     // getPELFromOBMCID
408     auto newData = manager.getPELFromOBMCID(42);
409     EXPECT_EQ(newData.size(), data.size());
410 
411     // Read the PEL to get the ID for later
412     PEL pel{newData};
413     auto id = pel.id();
414 
415     EXPECT_THROW(
416         manager.getPELFromOBMCID(id + 1),
417         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
418 
419     // getPEL
420     auto unixfd = manager.getPEL(id);
421 
422     // Get the size
423     struct stat s;
424     int r = fstat(unixfd, &s);
425     ASSERT_EQ(r, 0);
426     auto size = s.st_size;
427 
428     // Open the FD and check the contents
429     FILE* fp = fdopen(unixfd, "r");
430     ASSERT_NE(fp, nullptr);
431 
432     std::vector<uint8_t> fdData;
433     fdData.resize(size);
434     r = fread(fdData.data(), 1, size, fp);
435     EXPECT_EQ(r, size);
436 
437     EXPECT_EQ(newData, fdData);
438 
439     fclose(fp);
440 
441     // Run the event loop to close the FD
442     sdeventplus::Event e{sdEvent};
443     e.run(std::chrono::milliseconds(1));
444 
445     EXPECT_THROW(
446         manager.getPEL(id + 1),
447         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
448 
449     // hostAck
450     manager.hostAck(id);
451 
452     EXPECT_THROW(
453         manager.hostAck(id + 1),
454         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
455 
456     // hostReject
457     manager.hostReject(id, Manager::RejectionReason::BadPEL);
458 
459     // Run the event loop to log the bad PEL event
460     e.run(std::chrono::milliseconds(1));
461 
462     EXPECT_EQ(logger.errName, "org.open_power.Logging.Error.SentBadPELToHost");
463     EXPECT_EQ(id, std::stoi(logger.ad["BAD_ID"], nullptr, 16));
464 
465     manager.hostReject(id, Manager::RejectionReason::HostFull);
466 
467     EXPECT_THROW(
468         manager.hostReject(id + 1, Manager::RejectionReason::BadPEL),
469         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
470 
471     // GetPELIdFromBMCLogId
472     EXPECT_EQ(pel.id(), manager.getPELIdFromBMCLogId(pel.obmcLogID()));
473     EXPECT_THROW(
474         manager.getPELIdFromBMCLogId(pel.obmcLogID() + 1),
475         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
476 
477     // GetBMCLogIdFromPELId
478     EXPECT_EQ(pel.obmcLogID(), manager.getBMCLogIdFromPELId(pel.id()));
479     EXPECT_THROW(
480         manager.getBMCLogIdFromPELId(pel.id() + 1),
481         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
482 }
483 
484 // An ESEL from the wild
485 const std::string esel{
486     "00 00 df 00 00 00 00 20 00 04 12 01 6f aa 00 00 "
487     "50 48 00 30 01 00 33 00 20 23 05 11 10 20 20 00 00 00 00 07 5c d5 50 db "
488     "42 00 00 10 00 00 00 00 00 00 00 00 00 00 00 00 90 00 00 4e 90 00 00 4e "
489     "55 48 00 18 01 00 09 00 8a 03 40 00 00 00 00 00 ff ff 00 00 00 00 00 00 "
490     "50 53 00 50 01 01 00 00 02 00 00 09 33 2d 00 48 00 00 00 e0 00 00 10 00 "
491     "00 00 00 00 00 20 00 00 00 0c 00 02 00 00 00 fa 00 00 0c e4 00 00 00 12 "
492     "42 43 38 41 33 33 32 44 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
493     "20 20 20 20 20 20 20 20 55 44 00 1c 01 06 01 00 02 54 41 4b 00 00 00 06 "
494     "00 00 00 55 00 01 f9 20 00 00 00 00 55 44 00 24 01 06 01 00 01 54 41 4b "
495     "00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 23 01 00 02 00 05 00 00 "
496     "55 44 00 0c 01 0b 01 00 0f 01 00 00 55 44 00 10 01 04 01 00 0f 9f de 6a "
497     "00 01 00 00 55 44 00 7c 00 0c 01 00 00 13 0c 02 00 fa 0c e4 16 00 01 2c "
498     "0c 1c 16 00 00 fa 0a f0 14 00 00 fa 0b b8 14 00 00 be 09 60 12 00 01 2c "
499     "0d 7a 12 00 00 fa 0c 4e 10 00 00 fa 0c e4 10 00 00 be 0a 8c 16 00 01 2c "
500     "0c 1c 16 00 01 09 09 f6 16 00 00 fa 09 f6 14 00 00 fa 0b b8 14 00 00 fa "
501     "0a f0 14 00 00 be 08 ca 12 00 01 2c 0c e4 12 00 00 fa 0b 54 10 00 00 fa "
502     "0c 2d 10 00 00 be 08 ca 55 44 00 58 01 03 01 00 00 00 00 00 00 05 31 64 "
503     "00 00 00 00 00 05 0d d4 00 00 00 00 40 5f 06 e0 00 00 00 00 40 5d d2 00 "
504     "00 00 00 00 40 57 d3 d0 00 00 00 00 40 58 f6 a0 00 00 00 00 40 54 c9 34 "
505     "00 00 00 00 40 55 9a 10 00 00 00 00 40 4c 0a 80 00 00 00 00 00 00 27 14 "
506     "55 44 01 84 01 01 01 00 48 6f 73 74 62 6f 6f 74 20 42 75 69 6c 64 20 49 "
507     "44 3a 20 68 6f 73 74 62 6f 6f 74 2d 66 65 63 37 34 64 66 2d 70 30 61 38 "
508     "37 64 63 34 2f 68 62 69 63 6f 72 65 2e 62 69 6e 00 49 42 4d 2d 77 69 74 "
509     "68 65 72 73 70 6f 6f 6e 2d 4f 50 39 2d 76 32 2e 34 2d 39 2e 32 33 34 0a "
510     "09 6f 70 2d 62 75 69 6c 64 2d 38 32 66 34 63 66 30 0a 09 62 75 69 6c 64 "
511     "72 6f 6f 74 2d 32 30 31 39 2e 30 35 2e 32 2d 31 30 2d 67 38 39 35 39 31 "
512     "31 34 0a 09 73 6b 69 62 6f 6f 74 2d 76 36 2e 35 2d 31 38 2d 67 34 37 30 "
513     "66 66 62 35 66 32 39 64 37 0a 09 68 6f 73 74 62 6f 6f 74 2d 66 65 63 37 "
514     "34 64 66 2d 70 30 61 38 37 64 63 34 0a 09 6f 63 63 2d 65 34 35 39 37 61 "
515     "62 0a 09 6c 69 6e 75 78 2d 35 2e 32 2e 31 37 2d 6f 70 65 6e 70 6f 77 65 "
516     "72 31 2d 70 64 64 63 63 30 33 33 0a 09 70 65 74 69 74 62 6f 6f 74 2d 76 "
517     "31 2e 31 30 2e 34 0a 09 6d 61 63 68 69 6e 65 2d 78 6d 6c 2d 63 36 32 32 "
518     "63 62 35 2d 70 37 65 63 61 62 33 64 0a 09 68 6f 73 74 62 6f 6f 74 2d 62 "
519     "69 6e 61 72 69 65 73 2d 36 36 65 39 61 36 30 0a 09 63 61 70 70 2d 75 63 "
520     "6f 64 65 2d 70 39 2d 64 64 32 2d 76 34 0a 09 73 62 65 2d 36 30 33 33 30 "
521     "65 30 0a 09 68 63 6f 64 65 2d 68 77 30 39 32 31 31 39 61 2e 6f 70 6d 73 "
522     "74 0a 00 00 55 44 00 70 01 04 01 00 0f 9f de 6a 00 05 00 00 07 5f 1d f4 "
523     "30 32 43 59 34 37 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 "
524     "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 "
525     "0b ac 54 02 59 41 31 39 33 34 36 39 37 30 35 38 00 00 00 00 00 00 05 22 "
526     "a1 58 01 8a 00 58 40 20 17 18 4d 2c 00 00 00 fc 01 a1 00 00 55 44 00 14 "
527     "01 08 01 00 00 00 00 01 00 00 00 5a 00 00 00 05 55 44 03 fc 01 15 31 00 "
528     "01 28 00 42 46 41 50 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 f4 "
529     "00 00 00 00 00 00 03 f4 00 00 00 0b 00 00 00 00 00 00 00 3d 2c 9b c2 84 "
530     "00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 09 "
531     "00 00 00 00 00 11 bd 20 00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 "
532     "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 00 00 00 01 2c "
533     "00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0c 1c 00 00 00 64 00 00 00 3d "
534     "2c 9b d1 11 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 "
535     "00 00 00 0a 00 00 00 00 00 13 b5 a0 00 00 00 00 00 01 f8 80 00 00 00 00 "
536     "00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 "
537     "00 00 00 be 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0a 8c 00 00 00 64 "
538     "00 00 00 3d 2c 9b df 98 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 "
539     "00 00 00 00 00 00 00 0b 00 00 00 00 00 15 ae 20 00 00 00 00 00 01 f8 80 "
540     "00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 "
541     "00 00 00 00 00 00 00 fa 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0c e4 "
542     "00 00 00 64 00 00 00 3d 2c 9b ea b7 00 00 01 e4 00 48 43 4f fb ed 70 b1 "
543     "00 00 02 01 00 00 00 00 00 00 00 0c 00 00 00 00 00 17 a6 a0 00 00 00 00 "
544     "00 01 f8 80 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 "
545     "00 00 00 12 00 00 00 00 00 00 00 fa 00 00 00 00 00 00 07 d0 00 00 00 00 "
546     "00 00 0c 4e 00 00 00 64 00 00 00 3d 2c 9b f6 27 00 00 01 e4 00 48 43 4f "
547     "fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 0d 00 00 00 00 00 19 9f 20 "
548     "00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 "
549     "00 00 00 00 00 00 00 12 00 00 00 00 00 00 01 2c 00 00 00 00 00 00 07 d0 "
550     "00 00 00 00 00 00 0d 7a 00 00 00 64 00 00 00 3d 2c 9c 05 75 00 00 01 e4 "
551     "00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 0e 00 00 00 00 "
552     "00 1b 97 a0 00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 00 00 00 00 "
553     "00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 be 00 00 00 00 "
554     "00 00 07 d0 00 00 00 00 00 00 09 60 00 00 00 64 00 00 00 3d 2c 9c 11 29 "
555     "00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 0f "
556     "00 00 00 00 00 1d 90 20 00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 "
557     "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 fa "
558     "00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0b b8 00 00 00 64 00 00 00 3d "
559     "2c 9c 1c 45 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 "
560     "00 00 00 10 00 00 00 00 00 1f 88 a0 00 00 00 00 00 01 f8 80 00 00 00 00 "
561     "00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 00 "
562     "00 00 00 fa 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0a f0 00 00 00 64 "
563     "00 00 00 3d 2c 9c 2b 14 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 "
564     "00 00 00 00 00 00 00 11 00 00 00 00 00 21 81 20 00 00 00 00 00 01 f8 80 "
565     "00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 "
566     "00 00 00 00 00 00 01 2c 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0c 1c "
567     "00 00 00 64 00 00 00 3d 2d 6d 8f 9e 00 00 01 e4 00 00 43 4f 52 d7 9c 36 "
568     "00 00 04 73 00 00 00 1c 00 00 00 3d 2d 6d 99 ac 00 00 01 e4 00 10 43 4f "
569     "3f f2 02 3d 00 00 05 58 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00 40 "
570     "00 00 00 2c 55 44 00 30 01 15 31 00 01 28 00 42 46 41 50 49 5f 44 42 47 "
571     "00 00 00 00 00 00 00 00 00 00 00 28 00 00 00 00 00 00 00 28 00 00 00 00 "
572     "00 00 00 00 55 44 01 74 01 15 31 00 01 28 00 42 46 41 50 49 5f 49 00 00 "
573     "00 00 00 00 00 00 00 00 00 00 01 6c 00 00 00 00 00 00 01 6c 00 00 00 0b "
574     "00 00 00 00 00 00 00 3c 0d 52 18 5e 00 00 01 e4 00 08 43 4f 46 79 94 13 "
575     "00 00 0a 5b 00 00 00 00 00 00 2c 00 00 00 00 24 00 00 00 3c 0d 6b 26 6c "
576     "00 00 01 e4 00 00 43 4f 4e 9b 18 74 00 00 01 03 00 00 00 1c 00 00 00 3c "
577     "12 b9 2d 13 00 00 01 e4 00 00 43 4f ea 31 ed d4 00 00 05 c4 00 00 00 1c "
578     "00 00 00 3c 13 02 73 53 00 00 01 e4 00 00 43 4f ea 31 ed d4 00 00 05 c4 "
579     "00 00 00 1c 00 00 00 3c 13 04 7c 94 00 00 01 e4 00 00 43 4f ea 31 ed d4 "
580     "00 00 05 c4 00 00 00 1c 00 00 00 3c 13 06 ad e1 00 00 01 e4 00 00 43 4f "
581     "ea 31 ed d4 00 00 05 c4 00 00 00 1c 00 00 00 3c 13 07 3f 77 00 00 01 e4 "
582     "00 00 43 4f 5e 4a 55 32 00 00 10 f2 00 00 00 1c 00 00 00 3c 13 07 4e e4 "
583     "00 00 01 e4 00 00 43 4f 5e 4a 55 32 00 00 0d 68 00 00 00 1c 00 00 00 3c "
584     "13 36 79 18 00 00 01 e4 00 00 43 4f ea 31 ed d4 00 00 05 c4 00 00 00 1c "
585     "00 00 00 3d 2c 9c 36 70 00 00 01 e4 00 00 43 4f 23 45 90 97 00 00 02 47 "
586     "00 00 00 1c 00 00 00 3d 2d 6d a3 ed 00 00 01 e4 00 08 43 4f 74 3a 5b 1a "
587     "00 00 04 cc 00 00 00 00 02 00 00 01 00 00 00 24 55 44 00 30 01 15 31 00 "
588     "01 28 00 42 53 43 41 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 28 "
589     "00 00 00 00 00 00 00 28 00 00 00 00 00 00 00 00"};
590 
TEST_F(ManagerTest,TestESELToRawData)591 TEST_F(ManagerTest, TestESELToRawData)
592 {
593     auto data = Manager::eselToRawData(esel);
594 
595     EXPECT_EQ(data.size(), 2464);
596 
597     PEL pel{data};
598     EXPECT_TRUE(pel.valid());
599 }
600 
TEST_F(ManagerTest,TestCreateWithESEL)601 TEST_F(ManagerTest, TestCreateWithESEL)
602 {
603     std::unique_ptr<DataInterfaceBase> dataIface =
604         std::make_unique<MockDataInterface>();
605 
606     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
607 
608     openpower::pels::Manager manager{
609         logManager, std::move(dataIface),
610         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
611                   std::placeholders::_2, std::placeholders::_3),
612         std::move(journal)};
613 
614     {
615         std::map<std::string, std::string> additionalData{{"ESEL", esel}};
616         std::vector<std::string> associations;
617 
618         manager.create("error message", 37, 0,
619                        phosphor::logging::Entry::Level::Error, additionalData,
620                        associations);
621 
622         auto data = manager.getPELFromOBMCID(37);
623         PEL pel{data};
624         EXPECT_TRUE(pel.valid());
625     }
626 
627     // Now an invalid one
628     {
629         std::string adItem = esel;
630 
631         // Crop it
632         adItem.resize(adItem.size() - 300);
633 
634         std::map<std::string, std::string> additionalData{{"ESEL", adItem}};
635         std::vector<std::string> associations;
636 
637         manager.create("error message", 38, 0,
638                        phosphor::logging::Entry::Level::Error, additionalData,
639                        associations);
640 
641         EXPECT_THROW(
642             manager.getPELFromOBMCID(38),
643             sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
644 
645         // Run the event loop to log the bad PEL event
646         sdeventplus::Event e{sdEvent};
647         e.run(std::chrono::milliseconds(1));
648 
649         EXPECT_EQ(logger.errName, "org.open_power.Logging.Error.BadHostPEL");
650         EXPECT_EQ(logger.errLevel, phosphor::logging::Entry::Level::Error);
651     }
652 }
653 
654 // Test that PELs will be pruned when necessary
TEST_F(ManagerTest,TestPruning)655 TEST_F(ManagerTest, TestPruning)
656 {
657     sdeventplus::Event e{sdEvent};
658 
659     std::unique_ptr<DataInterfaceBase> dataIface =
660         std::make_unique<MockDataInterface>();
661 
662     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
663 
664     openpower::pels::Manager manager{
665         logManager, std::move(dataIface),
666         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
667                   std::placeholders::_2, std::placeholders::_3),
668         std::move(journal)};
669 
670     // Create 25 1000B (4096B on disk each, which is what is used for
671     // pruning) BMC non-informational PELs in the 100KB repository.  After
672     // the 24th one, the repo will be 96% full and a prune should be
673     // triggered to remove all but 7 to get under 30% full.  Then when the
674     // 25th is added there will be 8 left.
675 
676     auto dir = makeTempDir();
677     for (int i = 1; i <= 25; i++)
678     {
679         auto data = pelFactory(42, 'O', 0x40, 0x8800, 1000);
680 
681         fs::path pelFilename = dir / "rawpel";
682         std::ofstream pelFile{pelFilename};
683         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
684         pelFile.close();
685 
686         std::map<std::string, std::string> additionalData{
687             {"RAWPEL", pelFilename.string()}};
688         std::vector<std::string> associations;
689 
690         manager.create("error message", 42, 0,
691                        phosphor::logging::Entry::Level::Error, additionalData,
692                        associations);
693 
694         // Simulate the code getting back to the event loop
695         // after each create.
696         e.run(std::chrono::milliseconds(1));
697 
698         if (i < 24)
699         {
700             EXPECT_EQ(countPELsInRepo(), i);
701         }
702         else if (i == 24)
703         {
704             // Prune occured
705             EXPECT_EQ(countPELsInRepo(), 7);
706         }
707         else // i == 25
708         {
709             EXPECT_EQ(countPELsInRepo(), 8);
710         }
711     }
712 
713     try
714     {
715         // Make sure the 8 newest ones are still found.
716         for (uint32_t i = 0; i < 8; i++)
717         {
718             manager.getPEL(0x50000012 + i);
719         }
720     }
721     catch (
722         const sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument&
723             ex)
724     {
725         ADD_FAILURE() << "PELs should have all been found";
726     }
727 }
728 
729 // Test that manually deleting a PEL file will be recognized by the code.
TEST_F(ManagerTest,TestPELManualDelete)730 TEST_F(ManagerTest, TestPELManualDelete)
731 {
732     sdeventplus::Event e{sdEvent};
733 
734     std::unique_ptr<DataInterfaceBase> dataIface =
735         std::make_unique<MockDataInterface>();
736 
737     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
738 
739     openpower::pels::Manager manager{
740         logManager, std::move(dataIface),
741         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
742                   std::placeholders::_2, std::placeholders::_3),
743         std::move(journal)};
744 
745     auto data = pelDataFactory(TestPELType::pelSimple);
746     auto dir = makeTempDir();
747     fs::path pelFilename = dir / "rawpel";
748 
749     std::map<std::string, std::string> additionalData{
750         {"RAWPEL", pelFilename.string()}};
751     std::vector<std::string> associations;
752 
753     // Add 20 PELs, they will get incrementing IDs like
754     // 0x50000001, 0x50000002, etc.
755     for (int i = 1; i <= 20; i++)
756     {
757         std::ofstream pelFile{pelFilename};
758         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
759         pelFile.close();
760 
761         manager.create("error message", 42, 0,
762                        phosphor::logging::Entry::Level::Error, additionalData,
763                        associations);
764 
765         // Sanity check this ID is really there so we can test
766         // it was deleted later.  This will throw an exception if
767         // not present.
768         manager.getPEL(0x50000000 + i);
769 
770         // Run an event loop pass where the internal FD is deleted
771         // after the getPEL function call.
772         e.run(std::chrono::milliseconds(1));
773     }
774 
775     EXPECT_EQ(countPELsInRepo(), 20);
776 
777     deletePELFile(0x50000001);
778 
779     // Run a single event loop pass so the inotify event can run
780     e.run(std::chrono::milliseconds(1));
781 
782     EXPECT_EQ(countPELsInRepo(), 19);
783 
784     EXPECT_THROW(
785         manager.getPEL(0x50000001),
786         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
787 
788     // Delete a few more, they should all get handled in the same
789     // event loop pass
790     std::vector<uint32_t> toDelete{0x50000002, 0x50000003, 0x50000004,
791                                    0x50000005, 0x50000006};
792     std::for_each(toDelete.begin(), toDelete.end(),
793                   [](auto i) { deletePELFile(i); });
794 
795     e.run(std::chrono::milliseconds(1));
796 
797     EXPECT_EQ(countPELsInRepo(), 14);
798 
799     std::for_each(toDelete.begin(), toDelete.end(), [&manager](const auto i) {
800         EXPECT_THROW(
801             manager.getPEL(i),
802             sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
803     });
804 }
805 
806 // Test that deleting all PELs at once is handled OK.
TEST_F(ManagerTest,TestPELManualDeleteAll)807 TEST_F(ManagerTest, TestPELManualDeleteAll)
808 {
809     sdeventplus::Event e{sdEvent};
810 
811     std::unique_ptr<DataInterfaceBase> dataIface =
812         std::make_unique<MockDataInterface>();
813 
814     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
815 
816     openpower::pels::Manager manager{
817         logManager, std::move(dataIface),
818         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
819                   std::placeholders::_2, std::placeholders::_3),
820         std::move(journal)};
821 
822     auto data = pelDataFactory(TestPELType::pelSimple);
823     auto dir = makeTempDir();
824     fs::path pelFilename = dir / "rawpel";
825 
826     std::map<std::string, std::string> additionalData{
827         {"RAWPEL", pelFilename.string()}};
828     std::vector<std::string> associations;
829 
830     // Add 200 PELs, they will get incrementing IDs like
831     // 0x50000001, 0x50000002, etc.
832     for (int i = 1; i <= 200; i++)
833     {
834         std::ofstream pelFile{pelFilename};
835         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
836         pelFile.close();
837 
838         manager.create("error message", 42, 0,
839                        phosphor::logging::Entry::Level::Error, additionalData,
840                        associations);
841 
842         // Sanity check this ID is really there so we can test
843         // it was deleted later.  This will throw an exception if
844         // not present.
845         manager.getPEL(0x50000000 + i);
846 
847         // Run an event loop pass where the internal FD is deleted
848         // after the getPEL function call.
849         e.run(std::chrono::milliseconds(1));
850     }
851 
852     // Delete them all at once
853     auto logPath = getPELRepoPath() / "logs";
854     std::string cmd = "rm " + logPath.string() + "/*_*";
855 
856     {
857         auto rc = system(cmd.c_str());
858         EXPECT_EQ(rc, 0);
859     }
860 
861     EXPECT_EQ(countPELsInRepo(), 0);
862 
863     // It will take 5 event loop passes to process them all
864     for (int i = 0; i < 5; i++)
865     {
866         e.run(std::chrono::milliseconds(1));
867     }
868 
869     for (int i = 1; i <= 200; i++)
870     {
871         EXPECT_THROW(
872             manager.getPEL(0x50000000 + i),
873             sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
874     }
875 }
876 
877 // Test that fault LEDs are turned on when PELs are created
TEST_F(ManagerTest,TestServiceIndicators)878 TEST_F(ManagerTest, TestServiceIndicators)
879 {
880     std::unique_ptr<DataInterfaceBase> dataIface =
881         std::make_unique<MockDataInterface>();
882 
883     MockDataInterface* mockIface =
884         reinterpret_cast<MockDataInterface*>(dataIface.get());
885 
886     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
887 
888     openpower::pels::Manager manager{
889         logManager, std::move(dataIface),
890         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
891                   std::placeholders::_2, std::placeholders::_3),
892         std::move(journal)};
893 
894     // Add a PEL with a callout as if hostboot added it
895     {
896         EXPECT_CALL(*mockIface, getInventoryFromLocCode("U42", 0, true))
897             .WillOnce(
898                 Return(std::vector<std::string>{"/system/chassis/processor"}));
899 
900         EXPECT_CALL(*mockIface,
901                     setFunctional("/system/chassis/processor", false))
902             .Times(1);
903 
904         // This hostboot PEL has a single hardware callout in it.
905         auto data = pelFactory(1, 'B', 0x20, 0xA400, 500);
906 
907         fs::path pelFilename = makeTempDir() / "rawpel";
908         std::ofstream pelFile{pelFilename};
909         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
910         pelFile.close();
911 
912         std::map<std::string, std::string> additionalData{
913             {"RAWPEL", pelFilename.string()}};
914         std::vector<std::string> associations;
915 
916         manager.create("error message", 42, 0,
917                        phosphor::logging::Entry::Level::Error, additionalData,
918                        associations);
919     }
920 
921     // Add a BMC PEL with a callout that uses the message registry
922     {
923         std::vector<std::string> names{"systemA"};
924         EXPECT_CALL(*mockIface, getSystemNames)
925             .Times(1)
926             .WillOnce(Return(names));
927 
928         EXPECT_CALL(*mockIface, expandLocationCode("P42-C23", 0))
929             .WillOnce(Return("U42-P42-C23"));
930 
931         // First call to this is when building the Callout section
932         EXPECT_CALL(*mockIface, getInventoryFromLocCode("P42-C23", 0, false))
933             .WillOnce(
934                 Return(std::vector<std::string>{"/system/chassis/processor"}));
935 
936         // Second call to this is finding the associated LED group
937         EXPECT_CALL(*mockIface, getInventoryFromLocCode("U42-P42-C23", 0, true))
938             .WillOnce(
939                 Return(std::vector<std::string>{"/system/chassis/processor"}));
940 
941         EXPECT_CALL(*mockIface,
942                     setFunctional("/system/chassis/processor", false))
943             .Times(1);
944 
945         const auto registry = R"(
946         {
947             "PELs":
948             [
949                 {
950                     "Name": "xyz.openbmc_project.Error.Test",
951                     "Subsystem": "power_supply",
952                     "ActionFlags": ["service_action", "report"],
953                     "SRC":
954                     {
955                         "ReasonCode": "0x2030"
956                     },
957                     "Callouts": [
958                         {
959                             "CalloutList": [
960                                 {"Priority": "high", "LocCode": "P42-C23"}
961                             ]
962                         }
963                     ],
964                     "Documentation":
965                     {
966                         "Description": "Test Error",
967                         "Message": "Test Error"
968                     }
969                 }
970             ]
971         })";
972 
973         auto path = getPELReadOnlyDataPath();
974         fs::create_directories(path);
975         path /= "message_registry.json";
976 
977         std::ofstream registryFile{path};
978         registryFile << registry;
979         registryFile.close();
980 
981         std::map<std::string, std::string> additionalData;
982         std::vector<std::string> associations;
983 
984         manager.create("xyz.openbmc_project.Error.Test", 42, 0,
985                        phosphor::logging::Entry::Level::Error, additionalData,
986                        associations);
987     }
988 }
989 
990 // Test for duplicate PELs moved to archive folder
TEST_F(ManagerTest,TestDuplicatePEL)991 TEST_F(ManagerTest, TestDuplicatePEL)
992 {
993     sdeventplus::Event e{sdEvent};
994     size_t count = 0;
995 
996     std::unique_ptr<DataInterfaceBase> dataIface =
997         std::make_unique<MockDataInterface>();
998 
999     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
1000 
1001     openpower::pels::Manager manager{
1002         logManager, std::move(dataIface),
1003         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
1004                   std::placeholders::_2, std::placeholders::_3),
1005         std::move(journal)};
1006 
1007     for (int i = 0; i < 2; i++)
1008     {
1009         // This hostboot PEL has a single hardware callout in it.
1010         auto data = pelFactory(1, 'B', 0x20, 0xA400, 500);
1011 
1012         fs::path pelFilename = makeTempDir() / "rawpel";
1013         std::ofstream pelFile{pelFilename};
1014         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
1015         pelFile.close();
1016 
1017         std::map<std::string, std::string> additionalData{
1018             {"RAWPEL", pelFilename.string()}};
1019         std::vector<std::string> associations;
1020 
1021         manager.create("error message", 42, 0,
1022                        phosphor::logging::Entry::Level::Error, additionalData,
1023                        associations);
1024 
1025         e.run(std::chrono::milliseconds(1));
1026     }
1027 
1028     for (auto& f :
1029          fs::directory_iterator(getPELRepoPath() / "logs" / "archive"))
1030     {
1031         if (fs::is_regular_file(f.path()))
1032         {
1033             count++;
1034         }
1035     }
1036 
1037     // Get count of PELs in the repository & in archive directtory
1038     EXPECT_EQ(countPELsInRepo(), 1);
1039     EXPECT_EQ(count, 1);
1040 }
1041 
1042 // Test termination bit set for pel with critical system termination
1043 // severity
TEST_F(ManagerTest,TestTerminateBitWithPELSevCriticalSysTerminate)1044 TEST_F(ManagerTest, TestTerminateBitWithPELSevCriticalSysTerminate)
1045 {
1046     const auto registry = R"(
1047 {
1048     "PELs":
1049     [
1050         {
1051             "Name": "xyz.openbmc_project.Error.Test",
1052             "Subsystem": "power_supply",
1053             "Severity": "critical_system_term",
1054             "ActionFlags": ["service_action", "report"],
1055             "SRC":
1056             {
1057                 "ReasonCode": "0x2030"
1058             },
1059             "Documentation":
1060             {
1061                 "Description": "A PGOOD Fault",
1062                 "Message": "PS had a PGOOD Fault"
1063             }
1064         }
1065     ]
1066 }
1067 )";
1068 
1069     auto path = getPELReadOnlyDataPath();
1070     fs::create_directories(path);
1071     path /= "message_registry.json";
1072 
1073     std::ofstream registryFile{path};
1074     registryFile << registry;
1075     registryFile.close();
1076 
1077     std::unique_ptr<DataInterfaceBase> dataIface =
1078         std::make_unique<MockDataInterface>();
1079 
1080     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
1081 
1082     openpower::pels::Manager manager{
1083         logManager, std::move(dataIface),
1084         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
1085                   std::placeholders::_2, std::placeholders::_3),
1086         std::move(journal)};
1087 
1088     std::map<std::string, std::string> additionalData{{"FOO", "BAR"}};
1089     std::vector<std::string> associations;
1090 
1091     // Create the event log to create the PEL from.
1092     manager.create("xyz.openbmc_project.Error.Test", 33, 0,
1093                    phosphor::logging::Entry::Level::Error, additionalData,
1094                    associations);
1095 
1096     // Ensure a PEL was created in the repository
1097     auto pelData = findAnyPELInRepo();
1098     ASSERT_TRUE(pelData);
1099 
1100     auto getPELData = readPELFile(*pelData);
1101     PEL pel(*getPELData);
1102 
1103     // Spot check it.  Other testcases cover the details.
1104     EXPECT_TRUE(pel.valid());
1105 
1106     // Check for terminate bit set
1107     auto& hexwords = pel.primarySRC().value()->hexwordData();
1108     EXPECT_EQ(hexwords[3] & 0x20000000, 0x20000000);
1109 }
1110 
TEST_F(ManagerTest,TestSanitizeFieldforDBus)1111 TEST_F(ManagerTest, TestSanitizeFieldforDBus)
1112 {
1113     std::string base{"(test0!}\n\t ~"};
1114     auto string = base;
1115     string += char{' ' - 1};
1116     string += char{'~' + 1};
1117     string += char{0};
1118     string += char{static_cast<char>(0xFF)};
1119 
1120     // convert the last four chars to spaces
1121     EXPECT_EQ(Manager::sanitizeFieldForDBus(string), base + "    ");
1122 }
1123 
TEST_F(ManagerTest,TestFruPlug)1124 TEST_F(ManagerTest, TestFruPlug)
1125 {
1126     const auto registry = R"(
1127 {
1128     "PELs":
1129     [{
1130         "Name": "xyz.openbmc_project.Fan.Error.Fault",
1131         "Subsystem": "power_fans",
1132         "ComponentID": "0x2800",
1133         "SRC":
1134         {
1135             "Type": "11",
1136             "ReasonCode": "0x76F0",
1137             "Words6To9": {},
1138             "DeconfigFlag": true
1139         },
1140         "Callouts": [{
1141                 "CalloutList": [
1142                     {"Priority": "low", "LocCode": "P0"},
1143                     {"Priority": "high", "LocCode": "A3"}
1144                 ]
1145             }],
1146         "Documentation": {
1147             "Description": "A Fan Fault",
1148             "Message": "Fan had a Fault"
1149         }
1150      }]
1151 }
1152 )";
1153 
1154     auto path = getPELReadOnlyDataPath();
1155     fs::create_directories(path);
1156     path /= "message_registry.json";
1157 
1158     std::ofstream registryFile{path};
1159     registryFile << registry;
1160     registryFile.close();
1161 
1162     std::unique_ptr<DataInterfaceBase> dataIface =
1163         std::make_unique<MockDataInterface>();
1164 
1165     MockDataInterface* mockIface =
1166         reinterpret_cast<MockDataInterface*>(dataIface.get());
1167 
1168     // Set up the mock calls used when building callouts
1169     EXPECT_CALL(*mockIface, getInventoryFromLocCode("P0", 0, false))
1170         .WillRepeatedly(Return(std::vector<std::string>{"motherboard"}));
1171     EXPECT_CALL(*mockIface, expandLocationCode("P0", 0))
1172         .WillRepeatedly(Return("U1234-P0"));
1173     EXPECT_CALL(*mockIface, getInventoryFromLocCode("U1234-P0", 0, true))
1174         .WillRepeatedly(Return(std::vector<std::string>{"motherboard"}));
1175 
1176     EXPECT_CALL(*mockIface, getInventoryFromLocCode("A3", 0, false))
1177         .WillRepeatedly(Return(std::vector<std::string>{"fan"}));
1178     EXPECT_CALL(*mockIface, expandLocationCode("A3", 0))
1179         .WillRepeatedly(Return("U1234-A3"));
1180     EXPECT_CALL(*mockIface, getInventoryFromLocCode("U1234-A3", 0, true))
1181         .WillRepeatedly(Return(std::vector<std::string>{"fan"}));
1182 
1183     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
1184 
1185     openpower::pels::Manager manager{
1186         logManager, std::move(dataIface),
1187         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
1188                   std::placeholders::_2, std::placeholders::_3),
1189         std::move(journal)};
1190 
1191     std::map<std::string, std::string> additionalData;
1192     std::vector<std::string> associations;
1193 
1194     auto checkDeconfigured = [](bool deconfigured) {
1195         auto pelFile = findAnyPELInRepo();
1196         ASSERT_TRUE(pelFile);
1197 
1198         auto data = readPELFile(*pelFile);
1199         PEL pel(*data);
1200         ASSERT_TRUE(pel.valid());
1201 
1202         EXPECT_EQ(pel.primarySRC().value()->getErrorStatusFlag(
1203                       SRC::ErrorStatusFlags::deconfigured),
1204                   deconfigured);
1205     };
1206 
1207     manager.create("xyz.openbmc_project.Fan.Error.Fault", 42, 0,
1208                    phosphor::logging::Entry::Level::Error, additionalData,
1209                    associations);
1210     checkDeconfigured(true);
1211 
1212     // Replace A3 so PEL deconfigured flag should be set to false
1213     mockIface->fruPresent("U1234-A3");
1214     checkDeconfigured(false);
1215 
1216     manager.erase(42);
1217 
1218     // Create it again and replace a FRU not in the callout list.
1219     // Deconfig flag should stay on.
1220     manager.create("xyz.openbmc_project.Fan.Error.Fault", 43, 0,
1221                    phosphor::logging::Entry::Level::Error, additionalData,
1222                    associations);
1223     checkDeconfigured(true);
1224     mockIface->fruPresent("U1234-A4");
1225     checkDeconfigured(true);
1226 }
1227 
createHWIsolatedCalloutFile()1228 std::pair<int, std::filesystem::path> createHWIsolatedCalloutFile()
1229 {
1230     json jsonCalloutDataList(nlohmann::json::value_t::array);
1231     json jsonDimmCallout;
1232 
1233     jsonDimmCallout["LocationCode"] = "Ufcs-DIMM0";
1234     jsonDimmCallout["EntityPath"] = {35, 1, 0, 2, 0, 3, 0, 0, 0, 0, 0,
1235                                      0,  0, 0, 0, 0, 0, 0, 0, 0, 0};
1236     jsonDimmCallout["GuardType"] = "GARD_Predictive";
1237     jsonDimmCallout["Deconfigured"] = false;
1238     jsonDimmCallout["Guarded"] = true;
1239     jsonDimmCallout["Priority"] = "M";
1240     jsonCalloutDataList.emplace_back(std::move(jsonDimmCallout));
1241 
1242     std::string calloutData(jsonCalloutDataList.dump());
1243     std::string calloutFile("/tmp/phalPELCalloutsJson.XXXXXX");
1244     int fileFD = -1;
1245 
1246     fileFD = mkostemp(calloutFile.data(), O_RDWR);
1247     if (fileFD == -1)
1248     {
1249         perror("Failed to create PELCallouts file");
1250         return {-1, {}};
1251     }
1252 
1253     ssize_t rc = write(fileFD, calloutData.c_str(), calloutData.size());
1254     if (rc == -1)
1255     {
1256         perror("Failed to write PELCallouts file");
1257         close(fileFD);
1258         return {-1, {}};
1259     }
1260 
1261     // Ensure we seek to the beginning of the file
1262     rc = lseek(fileFD, 0, SEEK_SET);
1263     if (rc == -1)
1264     {
1265         perror("Failed to set SEEK_SET for PELCallouts file");
1266         close(fileFD);
1267         return {-1, {}};
1268     }
1269     return {fileFD, calloutFile};
1270 }
1271 
appendFFDCEntry(int fd,uint8_t subTypeJson,uint8_t version,phosphor::logging::FFDCEntries & ffdcEntries)1272 void appendFFDCEntry(int fd, uint8_t subTypeJson, uint8_t version,
1273                      phosphor::logging::FFDCEntries& ffdcEntries)
1274 {
1275     phosphor::logging::FFDCEntry ffdcEntry =
1276         std::make_tuple(sdbusplus::xyz::openbmc_project::Logging::server::
1277                             Create::FFDCFormat::JSON,
1278                         subTypeJson, version, fd);
1279     ffdcEntries.push_back(ffdcEntry);
1280 }
1281 
TEST_F(ManagerTest,TestPELDeleteWithoutHWIsolation)1282 TEST_F(ManagerTest, TestPELDeleteWithoutHWIsolation)
1283 {
1284     const auto registry = R"(
1285     {
1286         "PELs":
1287         [{
1288             "Name": "xyz.openbmc_project.Error.Test",
1289             "SRC":
1290             {
1291                 "ReasonCode": "0x2030"
1292             },
1293             "Documentation": {
1294                 "Description": "Test Error",
1295                 "Message": "Test Error"
1296             }
1297         }]
1298     }
1299     )";
1300 
1301     auto path = getPELReadOnlyDataPath();
1302     fs::create_directories(path);
1303     path /= "message_registry.json";
1304 
1305     std::ofstream registryFile{path};
1306     registryFile << registry;
1307     registryFile.close();
1308 
1309     std::unique_ptr<DataInterfaceBase> dataIface =
1310         std::make_unique<MockDataInterface>();
1311 
1312     MockDataInterface* mockIface =
1313         reinterpret_cast<MockDataInterface*>(dataIface.get());
1314 
1315     EXPECT_CALL(*mockIface, getInventoryFromLocCode("Ufcs-DIMM0", 0, false))
1316         .WillOnce(Return(std::vector<std::string>{
1317             "/xyz/openbmc_project/inventory/system/chassis/motherboard/dimm0"}));
1318 
1319     // Mock the scenario where the hardware isolation guard is flagged
1320     // but is not associated, resulting in an empty list being returned.
1321     EXPECT_CALL(
1322         *mockIface,
1323         getAssociatedPaths(
1324             ::testing::StrEq(
1325                 "/xyz/openbmc_project/logging/entry/42/isolated_hw_entry"),
1326             ::testing::StrEq("/"), 0,
1327             ::testing::ElementsAre(
1328                 "xyz.openbmc_project.HardwareIsolation.Entry")))
1329         .WillRepeatedly(Return(std::vector<std::string>{}));
1330 
1331     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
1332     openpower::pels::Manager manager{
1333         logManager, std::move(dataIface),
1334         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
1335                   std::placeholders::_2, std::placeholders::_3),
1336         std::move(journal)};
1337     std::map<std::string, std::string> additionalData;
1338     std::vector<std::string> associations;
1339 
1340     // Check when there's no PEL with given id.
1341     {
1342         EXPECT_FALSE(manager.isDeleteProhibited(42));
1343     }
1344     // creating without ffdcEntries
1345     manager.create("xyz.openbmc_project.Error.Test", 42, 0,
1346                    phosphor::logging::Entry::Level::Error, additionalData,
1347                    associations);
1348     auto pelFile = findAnyPELInRepo();
1349     auto data = readPELFile(*pelFile);
1350     PEL pel_unguarded(*data);
1351     {
1352         // Verify that the guard flag is false.
1353         EXPECT_FALSE(pel_unguarded.getGuardFlag());
1354         // Check that `isDeleteProhibited` returns false when the guard flag
1355         // is false.
1356         EXPECT_FALSE(manager.isDeleteProhibited(42));
1357     }
1358     manager.erase(42);
1359     EXPECT_FALSE(findAnyPELInRepo());
1360 
1361     auto [fd, calloutFile] = createHWIsolatedCalloutFile();
1362     ASSERT_NE(fd, -1);
1363     uint8_t subTypeJson = 0xCA;
1364     uint8_t version = 0x01;
1365     phosphor::logging::FFDCEntries ffdcEntries;
1366     appendFFDCEntry(fd, subTypeJson, version, ffdcEntries);
1367     manager.create("xyz.openbmc_project.Error.Test", 42, 0,
1368                    phosphor::logging::Entry::Level::Error, additionalData,
1369                    associations, ffdcEntries);
1370     close(fd);
1371     std::filesystem::remove(calloutFile);
1372 
1373     auto pelPathInRepo = findAnyPELInRepo();
1374     auto unguardedData = readPELFile(*pelPathInRepo);
1375     PEL pel(*unguardedData);
1376     {
1377         // Verify guard flag set to true
1378         EXPECT_TRUE(pel.getGuardFlag());
1379         // Check even if guard flag is true, if dbus call returns empty
1380         // array list then `isDeleteProhibited` returns false
1381         EXPECT_FALSE(manager.isDeleteProhibited(42));
1382     }
1383     manager.erase(42);
1384 }
1385 
TEST_F(ManagerTest,TestPELDeleteWithHWIsolation)1386 TEST_F(ManagerTest, TestPELDeleteWithHWIsolation)
1387 {
1388     const auto registry = R"(
1389     {
1390         "PELs":
1391         [{
1392             "Name": "xyz.openbmc_project.Error.Test",
1393             "Severity": "critical_system_term",
1394             "SRC":
1395             {
1396                 "ReasonCode": "0x2030"
1397             },
1398             "Documentation": {
1399                 "Description": "Test Error",
1400                 "Message": "Test Error"
1401             }
1402         }]
1403     }
1404     )";
1405 
1406     auto path = getPELReadOnlyDataPath();
1407     fs::create_directories(path);
1408     path /= "message_registry.json";
1409 
1410     std::ofstream registryFile{path};
1411     registryFile << registry;
1412     registryFile.close();
1413 
1414     std::unique_ptr<DataInterfaceBase> dataIface =
1415         std::make_unique<MockDataInterface>();
1416 
1417     MockDataInterface* mockIface =
1418         reinterpret_cast<MockDataInterface*>(dataIface.get());
1419 
1420     EXPECT_CALL(*mockIface, getInventoryFromLocCode("Ufcs-DIMM0", 0, false))
1421         .WillOnce(Return(std::vector<std::string>{
1422             "/xyz/openbmc_project/inventory/system/chassis/motherboard/dimm0"}));
1423 
1424     EXPECT_CALL(
1425         *mockIface,
1426         getAssociatedPaths(
1427             ::testing::StrEq(
1428                 "/xyz/openbmc_project/logging/entry/42/isolated_hw_entry"),
1429             ::testing::StrEq("/"), 0,
1430             ::testing::ElementsAre(
1431                 "xyz.openbmc_project.HardwareIsolation.Entry")))
1432         .WillRepeatedly(Return(std::vector<std::string>{
1433             "/xyz/openbmc_project/hardware_isolation/entry/1"}));
1434 
1435     std::unique_ptr<JournalBase> journal = std::make_unique<MockJournal>();
1436     openpower::pels::Manager manager{
1437         logManager, std::move(dataIface),
1438         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
1439                   std::placeholders::_2, std::placeholders::_3),
1440         std::move(journal)};
1441     std::map<std::string, std::string> additionalData;
1442     std::vector<std::string> associations;
1443 
1444     auto [fd, calloutFile] = createHWIsolatedCalloutFile();
1445     ASSERT_NE(fd, -1);
1446     uint8_t subTypeJson = 0xCA;
1447     uint8_t version = 0x01;
1448     phosphor::logging::FFDCEntries ffdcEntries;
1449     appendFFDCEntry(fd, subTypeJson, version, ffdcEntries);
1450     manager.create("xyz.openbmc_project.Error.Test", 42, 0,
1451                    phosphor::logging::Entry::Level::Error, additionalData,
1452                    associations, ffdcEntries);
1453     close(fd);
1454     std::filesystem::remove(calloutFile);
1455 
1456     auto pelFile = findAnyPELInRepo();
1457     EXPECT_TRUE(pelFile);
1458     auto data = readPELFile(*pelFile);
1459     PEL pel(*data);
1460     EXPECT_TRUE(pel.valid());
1461     // Test case where the guard flag is set to true and the hardware
1462     // isolation guard is associated, which should result in
1463     // `isDeleteProhibited` returning true as expected.
1464     EXPECT_TRUE(pel.getGuardFlag());
1465     EXPECT_TRUE(manager.isDeleteProhibited(42));
1466     manager.erase(42);
1467 }
1468