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