1 /**
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  */
16 #include "extensions/openpower-pels/manager.hpp"
17 #include "log_manager.hpp"
18 #include "mocks.hpp"
19 #include "pel_utils.hpp"
20 
21 #include <fstream>
22 #include <regex>
23 #include <sdbusplus/test/sdbus_mock.hpp>
24 #include <xyz/openbmc_project/Common/error.hpp>
25 
26 #include <gtest/gtest.h>
27 
28 using namespace openpower::pels;
29 namespace fs = std::filesystem;
30 
31 using ::testing::NiceMock;
32 using ::testing::Return;
33 
34 class TestLogger
35 {
36   public:
37     void log(const std::string& name, phosphor::logging::Entry::Level level,
38              const EventLogger::ADMap& additionalData)
39     {
40         errName = name;
41         errLevel = level;
42         ad = additionalData;
43     }
44 
45     std::string errName;
46     phosphor::logging::Entry::Level errLevel;
47     EventLogger::ADMap ad;
48 };
49 
50 class ManagerTest : public CleanPELFiles
51 {
52   public:
53     ManagerTest() :
54         bus(sdbusplus::get_mocked_new(&sdbusInterface)),
55         logManager(bus, "logging_path")
56     {
57         sd_event_default(&sdEvent);
58     }
59 
60     ~ManagerTest()
61     {
62         sd_event_unref(sdEvent);
63     }
64 
65     NiceMock<sdbusplus::SdBusMock> sdbusInterface;
66     sdbusplus::bus::bus bus;
67     phosphor::logging::internal::Manager logManager;
68     sd_event* sdEvent;
69     TestLogger logger;
70 };
71 
72 fs::path makeTempDir()
73 {
74     char path[] = "/tmp/tempnameXXXXXX";
75     std::filesystem::path dir = mkdtemp(path);
76     return dir;
77 }
78 
79 std::optional<fs::path> findAnyPELInRepo()
80 {
81     // PELs are named <timestamp>_<ID>
82     std::regex expr{"\\d+_\\d+"};
83 
84     for (auto& f : fs::directory_iterator(getPELRepoPath() / "logs"))
85     {
86         if (std::regex_search(f.path().string(), expr))
87         {
88             return f.path();
89         }
90     }
91     return std::nullopt;
92 }
93 
94 size_t countPELsInRepo()
95 {
96     size_t count = 0;
97     std::regex expr{"\\d+_\\d+"};
98 
99     for (auto& f : fs::directory_iterator(getPELRepoPath() / "logs"))
100     {
101         if (std::regex_search(f.path().string(), expr))
102         {
103             count++;
104         }
105     }
106     return count;
107 }
108 
109 void deletePELFile(uint32_t id)
110 {
111     char search[20];
112 
113     sprintf(search, "\\d+_%.8X", id);
114     std::regex expr{search};
115 
116     for (auto& f : fs::directory_iterator(getPELRepoPath() / "logs"))
117     {
118         if (std::regex_search(f.path().string(), expr))
119         {
120             fs::remove(f.path());
121             break;
122         }
123     }
124 }
125 
126 // Test that using the RAWPEL=<file> with the Manager::create() call gets
127 // a PEL saved in the repository.
128 TEST_F(ManagerTest, TestCreateWithPEL)
129 {
130     std::unique_ptr<DataInterfaceBase> dataIface =
131         std::make_unique<MockDataInterface>();
132 
133     openpower::pels::Manager manager{
134         logManager, std::move(dataIface),
135         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
136                   std::placeholders::_2, std::placeholders::_3)};
137 
138     // Create a PEL, write it to a file, and pass that filename into
139     // the create function.
140     auto data = pelDataFactory(TestPELType::pelSimple);
141 
142     fs::path pelFilename = makeTempDir() / "rawpel";
143     std::ofstream pelFile{pelFilename};
144     pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
145     pelFile.close();
146 
147     std::string adItem = "RAWPEL=" + pelFilename.string();
148     std::vector<std::string> additionalData{adItem};
149     std::vector<std::string> associations;
150 
151     manager.create("error message", 42, 0,
152                    phosphor::logging::Entry::Level::Error, additionalData,
153                    associations);
154 
155     // Find the file in the PEL repository directory
156     auto pelPathInRepo = findAnyPELInRepo();
157 
158     EXPECT_TRUE(pelPathInRepo);
159 
160     // Now remove it based on its OpenBMC event log ID
161     manager.erase(42);
162 
163     pelPathInRepo = findAnyPELInRepo();
164 
165     EXPECT_FALSE(pelPathInRepo);
166 
167     fs::remove_all(pelFilename.parent_path());
168 }
169 
170 TEST_F(ManagerTest, TestCreateWithInvalidPEL)
171 {
172     std::unique_ptr<DataInterfaceBase> dataIface =
173         std::make_unique<MockDataInterface>();
174 
175     openpower::pels::Manager manager{
176         logManager, std::move(dataIface),
177         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
178                   std::placeholders::_2, std::placeholders::_3)};
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::string adItem = "RAWPEL=" + pelFilename.string();
193     std::vector<std::string> additionalData{adItem};
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     fs::remove_all(pelFilename.parent_path());
217 }
218 
219 // Test that the message registry can be used to build a PEL.
220 TEST_F(ManagerTest, TestCreateWithMessageRegistry)
221 {
222     const auto registry = R"(
223 {
224     "PELs":
225     [
226         {
227             "Name": "xyz.openbmc_project.Error.Test",
228             "Subsystem": "power_supply",
229             "ActionFlags": ["service_action", "report"],
230             "SRC":
231             {
232                 "ReasonCode": "0x2030"
233             },
234             "Documentation":
235             {
236                 "Description": "A PGOOD Fault",
237                 "Message": "PS had a PGOOD Fault"
238             }
239         },
240         {
241             "Name": "xyz.openbmc_project.Logging.Error.Default",
242             "Subsystem": "bmc_firmware",
243             "SRC":
244             {
245                 "ReasonCode": "0x2031"
246             },
247             "Documentation":
248             {
249                 "Description": "The entry used when no match found",
250                 "Message": "This is a generic SRC"
251             }
252         }
253     ]
254 }
255 )";
256 
257     auto path = getPELReadOnlyDataPath();
258     fs::create_directories(path);
259     path /= "message_registry.json";
260 
261     std::ofstream registryFile{path};
262     registryFile << registry;
263     registryFile.close();
264 
265     std::unique_ptr<DataInterfaceBase> dataIface =
266         std::make_unique<MockDataInterface>();
267 
268     openpower::pels::Manager manager{
269         logManager, std::move(dataIface),
270         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
271                   std::placeholders::_2, std::placeholders::_3)};
272 
273     std::vector<std::string> additionalData{"FOO=BAR"};
274     std::vector<std::string> associations;
275 
276     // Create the event log to create the PEL from.
277     manager.create("xyz.openbmc_project.Error.Test", 33, 0,
278                    phosphor::logging::Entry::Level::Error, additionalData,
279                    associations);
280 
281     // Ensure a PEL was created in the repository
282     auto pelFile = findAnyPELInRepo();
283     ASSERT_TRUE(pelFile);
284 
285     auto data = readPELFile(*pelFile);
286     PEL pel(*data);
287 
288     // Spot check it.  Other testcases cover the details.
289     EXPECT_TRUE(pel.valid());
290     EXPECT_EQ(pel.obmcLogID(), 33);
291     EXPECT_EQ(pel.primarySRC().value()->asciiString(),
292               "BD612030                        ");
293 
294     // Remove it
295     manager.erase(33);
296     pelFile = findAnyPELInRepo();
297     EXPECT_FALSE(pelFile);
298 
299     // Create an event log that can't be found in the registry.
300     // In this case, xyz.openbmc_project.Logging.Error.Default will
301     // be used as the key instead to find a registry match.
302     manager.create("xyz.openbmc_project.Error.Foo", 42, 0,
303                    phosphor::logging::Entry::Level::Error, additionalData,
304                    associations);
305 
306     // Ensure a PEL was still created in the repository
307     pelFile = findAnyPELInRepo();
308     ASSERT_TRUE(pelFile);
309 
310     data = readPELFile(*pelFile);
311     PEL newPEL(*data);
312 
313     EXPECT_TRUE(newPEL.valid());
314     EXPECT_EQ(newPEL.obmcLogID(), 42);
315     EXPECT_EQ(newPEL.primarySRC().value()->asciiString(),
316               "BD8D2031                        ");
317 
318     // Check for both the original AdditionalData item as well as
319     // the ERROR_NAME item that should contain the error message
320     // property that wasn't found.
321     std::string errorName;
322     std::string adItem;
323 
324     for (const auto& section : newPEL.optionalSections())
325     {
326         if (SectionID::userData == static_cast<SectionID>(section->header().id))
327         {
328             if (UserDataFormat::json ==
329                 static_cast<UserDataFormat>(section->header().subType))
330             {
331                 auto ud = static_cast<UserData*>(section.get());
332 
333                 // Check that there was a UserData section added that
334                 // contains debug details about the device.
335                 const auto& d = ud->data();
336                 std::string jsonString{d.begin(), d.end()};
337                 auto json = nlohmann::json::parse(jsonString);
338 
339                 if (json.contains("ERROR_NAME"))
340                 {
341                     errorName = json["ERROR_NAME"].get<std::string>();
342                 }
343 
344                 if (json.contains("FOO"))
345                 {
346                     adItem = json["FOO"].get<std::string>();
347                 }
348             }
349         }
350         if (!errorName.empty())
351         {
352             break;
353         }
354     }
355 
356     EXPECT_EQ(errorName, "xyz.openbmc_project.Error.Foo");
357     EXPECT_EQ(adItem, "BAR");
358 }
359 
360 TEST_F(ManagerTest, TestDBusMethods)
361 {
362     std::unique_ptr<DataInterfaceBase> dataIface =
363         std::make_unique<MockDataInterface>();
364 
365     Manager manager{logManager, std::move(dataIface),
366                     std::bind(std::mem_fn(&TestLogger::log), &logger,
367                               std::placeholders::_1, std::placeholders::_2,
368                               std::placeholders::_3)};
369 
370     // Create a PEL, write it to a file, and pass that filename into
371     // the create function so there's one in the repo.
372     auto data = pelDataFactory(TestPELType::pelSimple);
373 
374     fs::path pelFilename = makeTempDir() / "rawpel";
375     std::ofstream pelFile{pelFilename};
376     pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
377     pelFile.close();
378 
379     std::string adItem = "RAWPEL=" + pelFilename.string();
380     std::vector<std::string> additionalData{adItem};
381     std::vector<std::string> associations;
382 
383     manager.create("error message", 42, 0,
384                    phosphor::logging::Entry::Level::Error, additionalData,
385                    associations);
386 
387     // getPELFromOBMCID
388     auto newData = manager.getPELFromOBMCID(42);
389     EXPECT_EQ(newData.size(), data.size());
390 
391     // Read the PEL to get the ID for later
392     PEL pel{newData};
393     auto id = pel.id();
394 
395     EXPECT_THROW(
396         manager.getPELFromOBMCID(id + 1),
397         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
398 
399     // getPEL
400     auto unixfd = manager.getPEL(id);
401 
402     // Get the size
403     struct stat s;
404     int r = fstat(unixfd, &s);
405     ASSERT_EQ(r, 0);
406     auto size = s.st_size;
407 
408     // Open the FD and check the contents
409     FILE* fp = fdopen(unixfd, "r");
410     ASSERT_NE(fp, nullptr);
411 
412     std::vector<uint8_t> fdData;
413     fdData.resize(size);
414     r = fread(fdData.data(), 1, size, fp);
415     EXPECT_EQ(r, size);
416 
417     EXPECT_EQ(newData, fdData);
418 
419     fclose(fp);
420 
421     // Run the event loop to close the FD
422     sdeventplus::Event e{sdEvent};
423     e.run(std::chrono::milliseconds(1));
424 
425     EXPECT_THROW(
426         manager.getPEL(id + 1),
427         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
428 
429     // hostAck
430     manager.hostAck(id);
431 
432     EXPECT_THROW(
433         manager.hostAck(id + 1),
434         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
435 
436     // hostReject
437     manager.hostReject(id, Manager::RejectionReason::BadPEL);
438 
439     // Run the event loop to log the bad PEL event
440     e.run(std::chrono::milliseconds(1));
441 
442     EXPECT_EQ(logger.errName, "org.open_power.Logging.Error.SentBadPELToHost");
443     EXPECT_EQ(id, std::stoi(logger.ad["BAD_ID"], nullptr, 16));
444 
445     manager.hostReject(id, Manager::RejectionReason::HostFull);
446 
447     EXPECT_THROW(
448         manager.hostReject(id + 1, Manager::RejectionReason::BadPEL),
449         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
450 
451     fs::remove_all(pelFilename.parent_path());
452 }
453 
454 // An ESEL from the wild
455 const std::string esel{
456     "00 00 df 00 00 00 00 20 00 04 12 01 6f aa 00 00 "
457     "50 48 00 30 01 00 33 00 00 00 00 07 5c 69 cc 0d 00 00 00 07 5c d5 50 db "
458     "42 00 00 10 00 00 00 00 00 00 00 00 00 00 00 00 90 00 00 4e 90 00 00 4e "
459     "55 48 00 18 01 00 09 00 8a 03 40 00 00 00 00 00 ff ff 00 00 00 00 00 00 "
460     "50 53 00 50 01 01 00 00 02 00 00 09 33 2d 00 48 00 00 00 e0 00 00 10 00 "
461     "00 00 00 00 00 20 00 00 00 0c 00 02 00 00 00 fa 00 00 0c e4 00 00 00 12 "
462     "42 43 38 41 33 33 32 44 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
463     "20 20 20 20 20 20 20 20 55 44 00 1c 01 06 01 00 02 54 41 4b 00 00 00 06 "
464     "00 00 00 55 00 01 f9 20 00 00 00 00 55 44 00 24 01 06 01 00 01 54 41 4b "
465     "00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 23 01 00 02 00 05 00 00 "
466     "55 44 00 0c 01 0b 01 00 0f 01 00 00 55 44 00 10 01 04 01 00 0f 9f de 6a "
467     "00 01 00 00 55 44 00 7c 00 0c 01 00 00 13 0c 02 00 fa 0c e4 16 00 01 2c "
468     "0c 1c 16 00 00 fa 0a f0 14 00 00 fa 0b b8 14 00 00 be 09 60 12 00 01 2c "
469     "0d 7a 12 00 00 fa 0c 4e 10 00 00 fa 0c e4 10 00 00 be 0a 8c 16 00 01 2c "
470     "0c 1c 16 00 01 09 09 f6 16 00 00 fa 09 f6 14 00 00 fa 0b b8 14 00 00 fa "
471     "0a f0 14 00 00 be 08 ca 12 00 01 2c 0c e4 12 00 00 fa 0b 54 10 00 00 fa "
472     "0c 2d 10 00 00 be 08 ca 55 44 00 58 01 03 01 00 00 00 00 00 00 05 31 64 "
473     "00 00 00 00 00 05 0d d4 00 00 00 00 40 5f 06 e0 00 00 00 00 40 5d d2 00 "
474     "00 00 00 00 40 57 d3 d0 00 00 00 00 40 58 f6 a0 00 00 00 00 40 54 c9 34 "
475     "00 00 00 00 40 55 9a 10 00 00 00 00 40 4c 0a 80 00 00 00 00 00 00 27 14 "
476     "55 44 01 84 01 01 01 00 48 6f 73 74 62 6f 6f 74 20 42 75 69 6c 64 20 49 "
477     "44 3a 20 68 6f 73 74 62 6f 6f 74 2d 66 65 63 37 34 64 66 2d 70 30 61 38 "
478     "37 64 63 34 2f 68 62 69 63 6f 72 65 2e 62 69 6e 00 49 42 4d 2d 77 69 74 "
479     "68 65 72 73 70 6f 6f 6e 2d 4f 50 39 2d 76 32 2e 34 2d 39 2e 32 33 34 0a "
480     "09 6f 70 2d 62 75 69 6c 64 2d 38 32 66 34 63 66 30 0a 09 62 75 69 6c 64 "
481     "72 6f 6f 74 2d 32 30 31 39 2e 30 35 2e 32 2d 31 30 2d 67 38 39 35 39 31 "
482     "31 34 0a 09 73 6b 69 62 6f 6f 74 2d 76 36 2e 35 2d 31 38 2d 67 34 37 30 "
483     "66 66 62 35 66 32 39 64 37 0a 09 68 6f 73 74 62 6f 6f 74 2d 66 65 63 37 "
484     "34 64 66 2d 70 30 61 38 37 64 63 34 0a 09 6f 63 63 2d 65 34 35 39 37 61 "
485     "62 0a 09 6c 69 6e 75 78 2d 35 2e 32 2e 31 37 2d 6f 70 65 6e 70 6f 77 65 "
486     "72 31 2d 70 64 64 63 63 30 33 33 0a 09 70 65 74 69 74 62 6f 6f 74 2d 76 "
487     "31 2e 31 30 2e 34 0a 09 6d 61 63 68 69 6e 65 2d 78 6d 6c 2d 63 36 32 32 "
488     "63 62 35 2d 70 37 65 63 61 62 33 64 0a 09 68 6f 73 74 62 6f 6f 74 2d 62 "
489     "69 6e 61 72 69 65 73 2d 36 36 65 39 61 36 30 0a 09 63 61 70 70 2d 75 63 "
490     "6f 64 65 2d 70 39 2d 64 64 32 2d 76 34 0a 09 73 62 65 2d 36 30 33 33 30 "
491     "65 30 0a 09 68 63 6f 64 65 2d 68 77 30 39 32 31 31 39 61 2e 6f 70 6d 73 "
492     "74 0a 00 00 55 44 00 70 01 04 01 00 0f 9f de 6a 00 05 00 00 07 5f 1d f4 "
493     "30 32 43 59 34 37 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 "
494     "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 "
495     "0b ac 54 02 59 41 31 39 33 34 36 39 37 30 35 38 00 00 00 00 00 00 05 22 "
496     "a1 58 01 8a 00 58 40 20 17 18 4d 2c 00 00 00 fc 01 a1 00 00 55 44 00 14 "
497     "01 08 01 00 00 00 00 01 00 00 00 5a 00 00 00 05 55 44 03 fc 01 15 31 00 "
498     "01 28 00 42 46 41 50 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 f4 "
499     "00 00 00 00 00 00 03 f4 00 00 00 0b 00 00 00 00 00 00 00 3d 2c 9b c2 84 "
500     "00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 09 "
501     "00 00 00 00 00 11 bd 20 00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 "
502     "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 00 00 00 01 2c "
503     "00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0c 1c 00 00 00 64 00 00 00 3d "
504     "2c 9b d1 11 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 "
505     "00 00 00 0a 00 00 00 00 00 13 b5 a0 00 00 00 00 00 01 f8 80 00 00 00 00 "
506     "00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 "
507     "00 00 00 be 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0a 8c 00 00 00 64 "
508     "00 00 00 3d 2c 9b df 98 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 "
509     "00 00 00 00 00 00 00 0b 00 00 00 00 00 15 ae 20 00 00 00 00 00 01 f8 80 "
510     "00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 "
511     "00 00 00 00 00 00 00 fa 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0c e4 "
512     "00 00 00 64 00 00 00 3d 2c 9b ea b7 00 00 01 e4 00 48 43 4f fb ed 70 b1 "
513     "00 00 02 01 00 00 00 00 00 00 00 0c 00 00 00 00 00 17 a6 a0 00 00 00 00 "
514     "00 01 f8 80 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 "
515     "00 00 00 12 00 00 00 00 00 00 00 fa 00 00 00 00 00 00 07 d0 00 00 00 00 "
516     "00 00 0c 4e 00 00 00 64 00 00 00 3d 2c 9b f6 27 00 00 01 e4 00 48 43 4f "
517     "fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 0d 00 00 00 00 00 19 9f 20 "
518     "00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 "
519     "00 00 00 00 00 00 00 12 00 00 00 00 00 00 01 2c 00 00 00 00 00 00 07 d0 "
520     "00 00 00 00 00 00 0d 7a 00 00 00 64 00 00 00 3d 2c 9c 05 75 00 00 01 e4 "
521     "00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 0e 00 00 00 00 "
522     "00 1b 97 a0 00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 00 00 00 00 "
523     "00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 be 00 00 00 00 "
524     "00 00 07 d0 00 00 00 00 00 00 09 60 00 00 00 64 00 00 00 3d 2c 9c 11 29 "
525     "00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 00 00 00 0f "
526     "00 00 00 00 00 1d 90 20 00 00 00 00 00 01 f8 80 00 00 00 00 00 00 00 01 "
527     "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 fa "
528     "00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0b b8 00 00 00 64 00 00 00 3d "
529     "2c 9c 1c 45 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 00 00 00 00 "
530     "00 00 00 10 00 00 00 00 00 1f 88 a0 00 00 00 00 00 01 f8 80 00 00 00 00 "
531     "00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 00 "
532     "00 00 00 fa 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0a f0 00 00 00 64 "
533     "00 00 00 3d 2c 9c 2b 14 00 00 01 e4 00 48 43 4f fb ed 70 b1 00 00 02 01 "
534     "00 00 00 00 00 00 00 11 00 00 00 00 00 21 81 20 00 00 00 00 00 01 f8 80 "
535     "00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 "
536     "00 00 00 00 00 00 01 2c 00 00 00 00 00 00 07 d0 00 00 00 00 00 00 0c 1c "
537     "00 00 00 64 00 00 00 3d 2d 6d 8f 9e 00 00 01 e4 00 00 43 4f 52 d7 9c 36 "
538     "00 00 04 73 00 00 00 1c 00 00 00 3d 2d 6d 99 ac 00 00 01 e4 00 10 43 4f "
539     "3f f2 02 3d 00 00 05 58 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00 40 "
540     "00 00 00 2c 55 44 00 30 01 15 31 00 01 28 00 42 46 41 50 49 5f 44 42 47 "
541     "00 00 00 00 00 00 00 00 00 00 00 28 00 00 00 00 00 00 00 28 00 00 00 00 "
542     "00 00 00 00 55 44 01 74 01 15 31 00 01 28 00 42 46 41 50 49 5f 49 00 00 "
543     "00 00 00 00 00 00 00 00 00 00 01 6c 00 00 00 00 00 00 01 6c 00 00 00 0b "
544     "00 00 00 00 00 00 00 3c 0d 52 18 5e 00 00 01 e4 00 08 43 4f 46 79 94 13 "
545     "00 00 0a 5b 00 00 00 00 00 00 2c 00 00 00 00 24 00 00 00 3c 0d 6b 26 6c "
546     "00 00 01 e4 00 00 43 4f 4e 9b 18 74 00 00 01 03 00 00 00 1c 00 00 00 3c "
547     "12 b9 2d 13 00 00 01 e4 00 00 43 4f ea 31 ed d4 00 00 05 c4 00 00 00 1c "
548     "00 00 00 3c 13 02 73 53 00 00 01 e4 00 00 43 4f ea 31 ed d4 00 00 05 c4 "
549     "00 00 00 1c 00 00 00 3c 13 04 7c 94 00 00 01 e4 00 00 43 4f ea 31 ed d4 "
550     "00 00 05 c4 00 00 00 1c 00 00 00 3c 13 06 ad e1 00 00 01 e4 00 00 43 4f "
551     "ea 31 ed d4 00 00 05 c4 00 00 00 1c 00 00 00 3c 13 07 3f 77 00 00 01 e4 "
552     "00 00 43 4f 5e 4a 55 32 00 00 10 f2 00 00 00 1c 00 00 00 3c 13 07 4e e4 "
553     "00 00 01 e4 00 00 43 4f 5e 4a 55 32 00 00 0d 68 00 00 00 1c 00 00 00 3c "
554     "13 36 79 18 00 00 01 e4 00 00 43 4f ea 31 ed d4 00 00 05 c4 00 00 00 1c "
555     "00 00 00 3d 2c 9c 36 70 00 00 01 e4 00 00 43 4f 23 45 90 97 00 00 02 47 "
556     "00 00 00 1c 00 00 00 3d 2d 6d a3 ed 00 00 01 e4 00 08 43 4f 74 3a 5b 1a "
557     "00 00 04 cc 00 00 00 00 02 00 00 01 00 00 00 24 55 44 00 30 01 15 31 00 "
558     "01 28 00 42 53 43 41 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 28 "
559     "00 00 00 00 00 00 00 28 00 00 00 00 00 00 00 00"};
560 
561 TEST_F(ManagerTest, TestESELToRawData)
562 {
563     auto data = Manager::eselToRawData(esel);
564 
565     EXPECT_EQ(data.size(), 2464);
566 
567     PEL pel{data};
568     EXPECT_TRUE(pel.valid());
569 }
570 
571 TEST_F(ManagerTest, TestCreateWithESEL)
572 {
573     std::unique_ptr<DataInterfaceBase> dataIface =
574         std::make_unique<MockDataInterface>();
575 
576     openpower::pels::Manager manager{
577         logManager, std::move(dataIface),
578         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
579                   std::placeholders::_2, std::placeholders::_3)};
580 
581     {
582         std::string adItem = "ESEL=" + esel;
583         std::vector<std::string> additionalData{adItem};
584         std::vector<std::string> associations;
585 
586         manager.create("error message", 37, 0,
587                        phosphor::logging::Entry::Level::Error, additionalData,
588                        associations);
589 
590         auto data = manager.getPELFromOBMCID(37);
591         PEL pel{data};
592         EXPECT_TRUE(pel.valid());
593     }
594 
595     // Now an invalid one
596     {
597         std::string adItem = "ESEL=" + esel;
598 
599         // Crop it
600         adItem.resize(adItem.size() - 300);
601 
602         std::vector<std::string> additionalData{adItem};
603         std::vector<std::string> associations;
604 
605         manager.create("error message", 38, 0,
606                        phosphor::logging::Entry::Level::Error, additionalData,
607                        associations);
608 
609         EXPECT_THROW(
610             manager.getPELFromOBMCID(38),
611             sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
612 
613         // Run the event loop to log the bad PEL event
614         sdeventplus::Event e{sdEvent};
615         e.run(std::chrono::milliseconds(1));
616 
617         EXPECT_EQ(logger.errName, "org.open_power.Logging.Error.BadHostPEL");
618         EXPECT_EQ(logger.errLevel, phosphor::logging::Entry::Level::Error);
619     }
620 }
621 
622 // Test that PELs will be pruned when necessary
623 TEST_F(ManagerTest, TestPruning)
624 {
625     sdeventplus::Event e{sdEvent};
626 
627     std::unique_ptr<DataInterfaceBase> dataIface =
628         std::make_unique<MockDataInterface>();
629 
630     openpower::pels::Manager manager{
631         logManager, std::move(dataIface),
632         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
633                   std::placeholders::_2, std::placeholders::_3)};
634 
635     // Create 25 1000B (4096B on disk each, which is what is used for pruning)
636     // BMC non-informational PELs in the 100KB repository.  After the 24th one,
637     // the repo will be 96% full and a prune should be triggered to remove all
638     // but 7 to get under 30% full.  Then when the 25th is added there will be
639     // 8 left.
640 
641     auto dir = makeTempDir();
642     for (int i = 1; i <= 25; i++)
643     {
644         auto data = pelFactory(42, 'O', 0x40, 0x8800, 1000);
645 
646         fs::path pelFilename = dir / "rawpel";
647         std::ofstream pelFile{pelFilename};
648         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
649         pelFile.close();
650 
651         std::string adItem = "RAWPEL=" + pelFilename.string();
652         std::vector<std::string> additionalData{adItem};
653         std::vector<std::string> associations;
654 
655         manager.create("error message", 42, 0,
656                        phosphor::logging::Entry::Level::Error, additionalData,
657                        associations);
658 
659         // Simulate the code getting back to the event loop
660         // after each create.
661         e.run(std::chrono::milliseconds(1));
662 
663         if (i < 24)
664         {
665             EXPECT_EQ(countPELsInRepo(), i);
666         }
667         else if (i == 24)
668         {
669             // Prune occured
670             EXPECT_EQ(countPELsInRepo(), 7);
671         }
672         else // i == 25
673         {
674             EXPECT_EQ(countPELsInRepo(), 8);
675         }
676     }
677 
678     try
679     {
680         // Make sure the 8 newest ones are still found.
681         for (uint32_t i = 0; i < 8; i++)
682         {
683             manager.getPEL(0x50000012 + i);
684         }
685     }
686     catch (sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument& e)
687     {
688         ADD_FAILURE() << "PELs should have all been found";
689     }
690 
691     fs::remove_all(dir);
692 }
693 
694 // Test that manually deleting a PEL file will be recognized by the code.
695 TEST_F(ManagerTest, TestPELManualDelete)
696 {
697     sdeventplus::Event e{sdEvent};
698 
699     std::unique_ptr<DataInterfaceBase> dataIface =
700         std::make_unique<MockDataInterface>();
701 
702     openpower::pels::Manager manager{
703         logManager, std::move(dataIface),
704         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
705                   std::placeholders::_2, std::placeholders::_3)};
706 
707     auto data = pelDataFactory(TestPELType::pelSimple);
708     auto dir = makeTempDir();
709     fs::path pelFilename = dir / "rawpel";
710 
711     std::string adItem = "RAWPEL=" + pelFilename.string();
712     std::vector<std::string> additionalData{adItem};
713     std::vector<std::string> associations;
714 
715     // Add 20 PELs, they will get incrementing IDs like
716     // 0x50000001, 0x50000002, etc.
717     for (int i = 1; i <= 20; i++)
718     {
719         std::ofstream pelFile{pelFilename};
720         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
721         pelFile.close();
722 
723         manager.create("error message", 42, 0,
724                        phosphor::logging::Entry::Level::Error, additionalData,
725                        associations);
726 
727         // Sanity check this ID is really there so we can test
728         // it was deleted later.  This will throw an exception if
729         // not present.
730         manager.getPEL(0x50000000 + i);
731 
732         // Run an event loop pass where the internal FD is deleted
733         // after the getPEL function call.
734         e.run(std::chrono::milliseconds(1));
735     }
736 
737     EXPECT_EQ(countPELsInRepo(), 20);
738 
739     deletePELFile(0x50000001);
740 
741     // Run a single event loop pass so the inotify event can run
742     e.run(std::chrono::milliseconds(1));
743 
744     EXPECT_EQ(countPELsInRepo(), 19);
745 
746     EXPECT_THROW(
747         manager.getPEL(0x50000001),
748         sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
749 
750     // Delete a few more, they should all get handled in the same
751     // event loop pass
752     std::vector<uint32_t> toDelete{0x50000002, 0x50000003, 0x50000004,
753                                    0x50000005, 0x50000006};
754     std::for_each(toDelete.begin(), toDelete.end(),
755                   [](auto i) { deletePELFile(i); });
756 
757     e.run(std::chrono::milliseconds(1));
758 
759     EXPECT_EQ(countPELsInRepo(), 14);
760 
761     std::for_each(toDelete.begin(), toDelete.end(), [&manager](const auto i) {
762         EXPECT_THROW(
763             manager.getPEL(i),
764             sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
765     });
766 
767     fs::remove_all(dir);
768 }
769 
770 // Test that deleting all PELs at once is handled OK.
771 TEST_F(ManagerTest, TestPELManualDeleteAll)
772 {
773     sdeventplus::Event e{sdEvent};
774 
775     std::unique_ptr<DataInterfaceBase> dataIface =
776         std::make_unique<MockDataInterface>();
777 
778     openpower::pels::Manager manager{
779         logManager, std::move(dataIface),
780         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
781                   std::placeholders::_2, std::placeholders::_3)};
782 
783     auto data = pelDataFactory(TestPELType::pelSimple);
784     auto dir = makeTempDir();
785     fs::path pelFilename = dir / "rawpel";
786 
787     std::string adItem = "RAWPEL=" + pelFilename.string();
788     std::vector<std::string> additionalData{adItem};
789     std::vector<std::string> associations;
790 
791     // Add 200 PELs, they will get incrementing IDs like
792     // 0x50000001, 0x50000002, etc.
793     for (int i = 1; i <= 200; i++)
794     {
795         std::ofstream pelFile{pelFilename};
796         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
797         pelFile.close();
798 
799         manager.create("error message", 42, 0,
800                        phosphor::logging::Entry::Level::Error, additionalData,
801                        associations);
802 
803         // Sanity check this ID is really there so we can test
804         // it was deleted later.  This will throw an exception if
805         // not present.
806         manager.getPEL(0x50000000 + i);
807 
808         // Run an event loop pass where the internal FD is deleted
809         // after the getPEL function call.
810         e.run(std::chrono::milliseconds(1));
811     }
812 
813     // Delete them all at once
814     auto logPath = getPELRepoPath() / "logs";
815     std::string cmd = "rm " + logPath.string() + "/*";
816 
817     {
818         auto rc = system(cmd.c_str());
819         EXPECT_EQ(rc, 0);
820     }
821 
822     EXPECT_EQ(countPELsInRepo(), 0);
823 
824     // It will take 5 event loop passes to process them all
825     for (int i = 0; i < 5; i++)
826     {
827         e.run(std::chrono::milliseconds(1));
828     }
829 
830     for (int i = 1; i <= 200; i++)
831     {
832         EXPECT_THROW(
833             manager.getPEL(0x50000000 + i),
834             sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument);
835     }
836 
837     fs::remove_all(dir);
838 }
839 
840 // Test that fault LEDs are turned on when PELs are created
841 TEST_F(ManagerTest, TestServiceIndicators)
842 {
843     std::unique_ptr<DataInterfaceBase> dataIface =
844         std::make_unique<MockDataInterface>();
845 
846     MockDataInterface* mockIface =
847         reinterpret_cast<MockDataInterface*>(dataIface.get());
848 
849     openpower::pels::Manager manager{
850         logManager, std::move(dataIface),
851         std::bind(std::mem_fn(&TestLogger::log), &logger, std::placeholders::_1,
852                   std::placeholders::_2, std::placeholders::_3)};
853 
854     // Add a PEL with a callout as if hostboot added it
855     {
856         EXPECT_CALL(*mockIface, getInventoryFromLocCode("U42", 0, true))
857             .WillOnce(Return("/system/chassis/processor"));
858 
859         EXPECT_CALL(*mockIface,
860                     setFunctional("/system/chassis/processor", false))
861             .Times(1);
862 
863         // This hostboot PEL has a single hardware callout in it.
864         auto data = pelFactory(1, 'B', 0x20, 0xA400, 500);
865 
866         fs::path pelFilename = makeTempDir() / "rawpel";
867         std::ofstream pelFile{pelFilename};
868         pelFile.write(reinterpret_cast<const char*>(data.data()), data.size());
869         pelFile.close();
870 
871         std::string adItem = "RAWPEL=" + pelFilename.string();
872         std::vector<std::string> additionalData{adItem};
873         std::vector<std::string> associations;
874 
875         manager.create("error message", 42, 0,
876                        phosphor::logging::Entry::Level::Error, additionalData,
877                        associations);
878 
879         fs::remove_all(pelFilename.parent_path());
880     }
881 
882     // Add a BMC PEL with a callout that uses the message registry
883     {
884         std::vector<std::string> names{"systemA"};
885         EXPECT_CALL(*mockIface, getSystemNames)
886             .Times(1)
887             .WillOnce(Return(names));
888 
889         EXPECT_CALL(*mockIface, expandLocationCode("P42-C23", 0))
890             .WillOnce(Return("U42-P42-C23"));
891 
892         // First call to this is when building the Callout section
893         EXPECT_CALL(*mockIface, getInventoryFromLocCode("P42-C23", 0, false))
894             .WillOnce(Return("/system/chassis/processor"));
895 
896         // Second call to this is finding the associated LED group
897         EXPECT_CALL(*mockIface, getInventoryFromLocCode("U42-P42-C23", 0, true))
898             .WillOnce(Return("/system/chassis/processor"));
899 
900         EXPECT_CALL(*mockIface,
901                     setFunctional("/system/chassis/processor", false))
902             .Times(1);
903 
904         const auto registry = R"(
905         {
906             "PELs":
907             [
908                 {
909                     "Name": "xyz.openbmc_project.Error.Test",
910                     "Subsystem": "power_supply",
911                     "ActionFlags": ["service_action", "report"],
912                     "SRC":
913                     {
914                         "ReasonCode": "0x2030"
915                     },
916                     "Callouts": [
917                         {
918                             "CalloutList": [
919                                 {"Priority": "high", "LocCode": "P42-C23"}
920                             ]
921                         }
922                     ],
923                     "Documentation":
924                     {
925                         "Description": "Test Error",
926                         "Message": "Test Error"
927                     }
928                 }
929             ]
930         })";
931 
932         auto path = getPELReadOnlyDataPath();
933         fs::create_directories(path);
934         path /= "message_registry.json";
935 
936         std::ofstream registryFile{path};
937         registryFile << registry;
938         registryFile.close();
939 
940         std::vector<std::string> additionalData;
941         std::vector<std::string> associations;
942 
943         manager.create("xyz.openbmc_project.Error.Test", 42, 0,
944                        phosphor::logging::Entry::Level::Error, additionalData,
945                        associations);
946     }
947 }
948