xref: /openbmc/bmcweb/features/redfish/lib/log_services.hpp (revision c6fecdabd58b4c380caf1b83801ad4eb54922fff)
1 /*
2 // Copyright (c) 2018 Intel 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 #pragma once
17 
18 #include "gzfile.hpp"
19 #include "http_utility.hpp"
20 #include "human_sort.hpp"
21 #include "registries.hpp"
22 #include "registries/base_message_registry.hpp"
23 #include "registries/openbmc_message_registry.hpp"
24 #include "task.hpp"
25 
26 #include <systemd/sd-journal.h>
27 #include <unistd.h>
28 
29 #include <app.hpp>
30 #include <boost/algorithm/string/case_conv.hpp>
31 #include <boost/algorithm/string/classification.hpp>
32 #include <boost/algorithm/string/replace.hpp>
33 #include <boost/algorithm/string/split.hpp>
34 #include <boost/beast/http/verb.hpp>
35 #include <boost/container/flat_map.hpp>
36 #include <boost/system/linux_error.hpp>
37 #include <dbus_utility.hpp>
38 #include <error_messages.hpp>
39 #include <query.hpp>
40 #include <registries/privilege_registry.hpp>
41 #include <utils/time_utils.hpp>
42 
43 #include <charconv>
44 #include <filesystem>
45 #include <optional>
46 #include <span>
47 #include <string_view>
48 #include <variant>
49 
50 namespace redfish
51 {
52 
53 constexpr char const* crashdumpObject = "com.intel.crashdump";
54 constexpr char const* crashdumpPath = "/com/intel/crashdump";
55 constexpr char const* crashdumpInterface = "com.intel.crashdump";
56 constexpr char const* deleteAllInterface =
57     "xyz.openbmc_project.Collection.DeleteAll";
58 constexpr char const* crashdumpOnDemandInterface =
59     "com.intel.crashdump.OnDemand";
60 constexpr char const* crashdumpTelemetryInterface =
61     "com.intel.crashdump.Telemetry";
62 
63 namespace registries
64 {
65 static const Message*
66     getMessageFromRegistry(const std::string& messageKey,
67                            const std::span<const MessageEntry> registry)
68 {
69     std::span<const MessageEntry>::iterator messageIt =
70         std::find_if(registry.begin(), registry.end(),
71                      [&messageKey](const MessageEntry& messageEntry) {
72         return std::strcmp(messageEntry.first, messageKey.c_str()) == 0;
73         });
74     if (messageIt != registry.end())
75     {
76         return &messageIt->second;
77     }
78 
79     return nullptr;
80 }
81 
82 static const Message* getMessage(const std::string_view& messageID)
83 {
84     // Redfish MessageIds are in the form
85     // RegistryName.MajorVersion.MinorVersion.MessageKey, so parse it to find
86     // the right Message
87     std::vector<std::string> fields;
88     fields.reserve(4);
89     boost::split(fields, messageID, boost::is_any_of("."));
90     const std::string& registryName = fields[0];
91     const std::string& messageKey = fields[3];
92 
93     // Find the right registry and check it for the MessageKey
94     if (std::string(base::header.registryPrefix) == registryName)
95     {
96         return getMessageFromRegistry(
97             messageKey, std::span<const MessageEntry>(base::registry));
98     }
99     if (std::string(openbmc::header.registryPrefix) == registryName)
100     {
101         return getMessageFromRegistry(
102             messageKey, std::span<const MessageEntry>(openbmc::registry));
103     }
104     return nullptr;
105 }
106 } // namespace registries
107 
108 namespace fs = std::filesystem;
109 
110 inline std::string translateSeverityDbusToRedfish(const std::string& s)
111 {
112     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Alert") ||
113         (s == "xyz.openbmc_project.Logging.Entry.Level.Critical") ||
114         (s == "xyz.openbmc_project.Logging.Entry.Level.Emergency") ||
115         (s == "xyz.openbmc_project.Logging.Entry.Level.Error"))
116     {
117         return "Critical";
118     }
119     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Debug") ||
120         (s == "xyz.openbmc_project.Logging.Entry.Level.Informational") ||
121         (s == "xyz.openbmc_project.Logging.Entry.Level.Notice"))
122     {
123         return "OK";
124     }
125     if (s == "xyz.openbmc_project.Logging.Entry.Level.Warning")
126     {
127         return "Warning";
128     }
129     return "";
130 }
131 
132 inline static int getJournalMetadata(sd_journal* journal,
133                                      const std::string_view& field,
134                                      std::string_view& contents)
135 {
136     const char* data = nullptr;
137     size_t length = 0;
138     int ret = 0;
139     // Get the metadata from the requested field of the journal entry
140     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
141     const void** dataVoid = reinterpret_cast<const void**>(&data);
142 
143     ret = sd_journal_get_data(journal, field.data(), dataVoid, &length);
144     if (ret < 0)
145     {
146         return ret;
147     }
148     contents = std::string_view(data, length);
149     // Only use the content after the "=" character.
150     contents.remove_prefix(std::min(contents.find('=') + 1, contents.size()));
151     return ret;
152 }
153 
154 inline static int getJournalMetadata(sd_journal* journal,
155                                      const std::string_view& field,
156                                      const int& base, long int& contents)
157 {
158     int ret = 0;
159     std::string_view metadata;
160     // Get the metadata from the requested field of the journal entry
161     ret = getJournalMetadata(journal, field, metadata);
162     if (ret < 0)
163     {
164         return ret;
165     }
166     contents = strtol(metadata.data(), nullptr, base);
167     return ret;
168 }
169 
170 inline static bool getEntryTimestamp(sd_journal* journal,
171                                      std::string& entryTimestamp)
172 {
173     int ret = 0;
174     uint64_t timestamp = 0;
175     ret = sd_journal_get_realtime_usec(journal, &timestamp);
176     if (ret < 0)
177     {
178         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
179                          << strerror(-ret);
180         return false;
181     }
182     entryTimestamp =
183         redfish::time_utils::getDateTimeUint(timestamp / 1000 / 1000);
184     return true;
185 }
186 
187 inline static bool getUniqueEntryID(sd_journal* journal, std::string& entryID,
188                                     const bool firstEntry = true)
189 {
190     int ret = 0;
191     static uint64_t prevTs = 0;
192     static int index = 0;
193     if (firstEntry)
194     {
195         prevTs = 0;
196     }
197 
198     // Get the entry timestamp
199     uint64_t curTs = 0;
200     ret = sd_journal_get_realtime_usec(journal, &curTs);
201     if (ret < 0)
202     {
203         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
204                          << strerror(-ret);
205         return false;
206     }
207     // If the timestamp isn't unique, increment the index
208     if (curTs == prevTs)
209     {
210         index++;
211     }
212     else
213     {
214         // Otherwise, reset it
215         index = 0;
216     }
217     // Save the timestamp
218     prevTs = curTs;
219 
220     entryID = std::to_string(curTs);
221     if (index > 0)
222     {
223         entryID += "_" + std::to_string(index);
224     }
225     return true;
226 }
227 
228 static bool getUniqueEntryID(const std::string& logEntry, std::string& entryID,
229                              const bool firstEntry = true)
230 {
231     static time_t prevTs = 0;
232     static int index = 0;
233     if (firstEntry)
234     {
235         prevTs = 0;
236     }
237 
238     // Get the entry timestamp
239     std::time_t curTs = 0;
240     std::tm timeStruct = {};
241     std::istringstream entryStream(logEntry);
242     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
243     {
244         curTs = std::mktime(&timeStruct);
245     }
246     // If the timestamp isn't unique, increment the index
247     if (curTs == prevTs)
248     {
249         index++;
250     }
251     else
252     {
253         // Otherwise, reset it
254         index = 0;
255     }
256     // Save the timestamp
257     prevTs = curTs;
258 
259     entryID = std::to_string(curTs);
260     if (index > 0)
261     {
262         entryID += "_" + std::to_string(index);
263     }
264     return true;
265 }
266 
267 inline static bool
268     getTimestampFromID(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
269                        const std::string& entryID, uint64_t& timestamp,
270                        uint64_t& index)
271 {
272     if (entryID.empty())
273     {
274         return false;
275     }
276     // Convert the unique ID back to a timestamp to find the entry
277     std::string_view tsStr(entryID);
278 
279     auto underscorePos = tsStr.find('_');
280     if (underscorePos != std::string_view::npos)
281     {
282         // Timestamp has an index
283         tsStr.remove_suffix(tsStr.size() - underscorePos);
284         std::string_view indexStr(entryID);
285         indexStr.remove_prefix(underscorePos + 1);
286         auto [ptr, ec] = std::from_chars(
287             indexStr.data(), indexStr.data() + indexStr.size(), index);
288         if (ec != std::errc())
289         {
290             messages::resourceMissingAtURI(
291                 asyncResp->res, crow::utility::urlFromPieces(entryID));
292             return false;
293         }
294     }
295     // Timestamp has no index
296     auto [ptr, ec] =
297         std::from_chars(tsStr.data(), tsStr.data() + tsStr.size(), timestamp);
298     if (ec != std::errc())
299     {
300         messages::resourceMissingAtURI(asyncResp->res,
301                                        crow::utility::urlFromPieces(entryID));
302         return false;
303     }
304     return true;
305 }
306 
307 static bool
308     getRedfishLogFiles(std::vector<std::filesystem::path>& redfishLogFiles)
309 {
310     static const std::filesystem::path redfishLogDir = "/var/log";
311     static const std::string redfishLogFilename = "redfish";
312 
313     // Loop through the directory looking for redfish log files
314     for (const std::filesystem::directory_entry& dirEnt :
315          std::filesystem::directory_iterator(redfishLogDir))
316     {
317         // If we find a redfish log file, save the path
318         std::string filename = dirEnt.path().filename();
319         if (filename.starts_with(redfishLogFilename))
320         {
321             redfishLogFiles.emplace_back(redfishLogDir / filename);
322         }
323     }
324     // As the log files rotate, they are appended with a ".#" that is higher for
325     // the older logs. Since we don't expect more than 10 log files, we
326     // can just sort the list to get them in order from newest to oldest
327     std::sort(redfishLogFiles.begin(), redfishLogFiles.end());
328 
329     return !redfishLogFiles.empty();
330 }
331 
332 inline void parseDumpEntryFromDbusObject(
333     const dbus::utility::ManagedObjectType::value_type& object,
334     std::string& dumpStatus, uint64_t& size, uint64_t& timestampUs,
335     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
336 {
337     for (const auto& interfaceMap : object.second)
338     {
339         if (interfaceMap.first == "xyz.openbmc_project.Common.Progress")
340         {
341             for (const auto& propertyMap : interfaceMap.second)
342             {
343                 if (propertyMap.first == "Status")
344                 {
345                     const auto* status =
346                         std::get_if<std::string>(&propertyMap.second);
347                     if (status == nullptr)
348                     {
349                         messages::internalError(asyncResp->res);
350                         break;
351                     }
352                     dumpStatus = *status;
353                 }
354             }
355         }
356         else if (interfaceMap.first == "xyz.openbmc_project.Dump.Entry")
357         {
358             for (const auto& propertyMap : interfaceMap.second)
359             {
360                 if (propertyMap.first == "Size")
361                 {
362                     const auto* sizePtr =
363                         std::get_if<uint64_t>(&propertyMap.second);
364                     if (sizePtr == nullptr)
365                     {
366                         messages::internalError(asyncResp->res);
367                         break;
368                     }
369                     size = *sizePtr;
370                     break;
371                 }
372             }
373         }
374         else if (interfaceMap.first == "xyz.openbmc_project.Time.EpochTime")
375         {
376             for (const auto& propertyMap : interfaceMap.second)
377             {
378                 if (propertyMap.first == "Elapsed")
379                 {
380                     const uint64_t* usecsTimeStamp =
381                         std::get_if<uint64_t>(&propertyMap.second);
382                     if (usecsTimeStamp == nullptr)
383                     {
384                         messages::internalError(asyncResp->res);
385                         break;
386                     }
387                     timestampUs = *usecsTimeStamp;
388                     break;
389                 }
390             }
391         }
392     }
393 }
394 
395 static std::string getDumpEntriesPath(const std::string& dumpType)
396 {
397     std::string entriesPath;
398 
399     if (dumpType == "BMC")
400     {
401         entriesPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/";
402     }
403     else if (dumpType == "FaultLog")
404     {
405         entriesPath = "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/";
406     }
407     else if (dumpType == "System")
408     {
409         entriesPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/";
410     }
411     else
412     {
413         BMCWEB_LOG_ERROR << "getDumpEntriesPath() invalid dump type: "
414                          << dumpType;
415     }
416 
417     // Returns empty string on error
418     return entriesPath;
419 }
420 
421 inline void
422     getDumpEntryCollection(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
423                            const std::string& dumpType)
424 {
425     std::string entriesPath = getDumpEntriesPath(dumpType);
426     if (entriesPath.empty())
427     {
428         messages::internalError(asyncResp->res);
429         return;
430     }
431 
432     crow::connections::systemBus->async_method_call(
433         [asyncResp, entriesPath,
434          dumpType](const boost::system::error_code ec,
435                    dbus::utility::ManagedObjectType& resp) {
436         if (ec)
437         {
438             BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec;
439             messages::internalError(asyncResp->res);
440             return;
441         }
442 
443         // Remove ending slash
444         std::string odataIdStr = entriesPath;
445         if (!odataIdStr.empty())
446         {
447             odataIdStr.pop_back();
448         }
449 
450         asyncResp->res.jsonValue["@odata.type"] =
451             "#LogEntryCollection.LogEntryCollection";
452         asyncResp->res.jsonValue["@odata.id"] = std::move(odataIdStr);
453         asyncResp->res.jsonValue["Name"] = dumpType + " Dump Entries";
454         asyncResp->res.jsonValue["Description"] =
455             "Collection of " + dumpType + " Dump Entries";
456 
457         nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
458         entriesArray = nlohmann::json::array();
459         std::string dumpEntryPath =
460             "/xyz/openbmc_project/dump/" +
461             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/";
462 
463         std::sort(resp.begin(), resp.end(), [](const auto& l, const auto& r) {
464             return AlphanumLess<std::string>()(l.first.filename(),
465                                                r.first.filename());
466         });
467 
468         for (auto& object : resp)
469         {
470             if (object.first.str.find(dumpEntryPath) == std::string::npos)
471             {
472                 continue;
473             }
474             uint64_t timestampUs = 0;
475             uint64_t size = 0;
476             std::string dumpStatus;
477             nlohmann::json::object_t thisEntry;
478 
479             std::string entryID = object.first.filename();
480             if (entryID.empty())
481             {
482                 continue;
483             }
484 
485             parseDumpEntryFromDbusObject(object, dumpStatus, size, timestampUs,
486                                          asyncResp);
487 
488             if (dumpStatus !=
489                     "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" &&
490                 !dumpStatus.empty())
491             {
492                 // Dump status is not Complete, no need to enumerate
493                 continue;
494             }
495 
496             thisEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
497             thisEntry["@odata.id"] = entriesPath + entryID;
498             thisEntry["Id"] = entryID;
499             thisEntry["EntryType"] = "Event";
500             thisEntry["Name"] = dumpType + " Dump Entry";
501 
502             if (dumpType == "BMC")
503             {
504                 thisEntry["Created"] = redfish::time_utils::getDateTimeUint(
505                     timestampUs / 1000 / 1000);
506                 thisEntry["DiagnosticDataType"] = "Manager";
507                 thisEntry["AdditionalDataURI"] =
508                     entriesPath + entryID + "/attachment";
509                 thisEntry["AdditionalDataSizeBytes"] = size;
510             }
511             else if (dumpType == "FaultLog")
512             {
513                 thisEntry["Created"] =
514                     redfish::time_utils::getDateTimeUintUs(timestampUs);
515             }
516             else if (dumpType == "System")
517             {
518                 thisEntry["Created"] = redfish::time_utils::getDateTimeUint(
519                     timestampUs / 1000 / 1000);
520                 thisEntry["DiagnosticDataType"] = "OEM";
521                 thisEntry["OEMDiagnosticDataType"] = "System";
522                 thisEntry["AdditionalDataURI"] =
523                     entriesPath + entryID + "/attachment";
524                 thisEntry["AdditionalDataSizeBytes"] = size;
525             }
526             entriesArray.push_back(std::move(thisEntry));
527         }
528         asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
529         },
530         "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump",
531         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
532 }
533 
534 inline void
535     getDumpEntryById(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
536                      const std::string& entryID, const std::string& dumpType)
537 {
538     std::string entriesPath = getDumpEntriesPath(dumpType);
539     if (entriesPath.empty())
540     {
541         messages::internalError(asyncResp->res);
542         return;
543     }
544 
545     crow::connections::systemBus->async_method_call(
546         [asyncResp, entryID, dumpType,
547          entriesPath](const boost::system::error_code ec,
548                       const dbus::utility::ManagedObjectType& resp) {
549         if (ec)
550         {
551             BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec;
552             messages::internalError(asyncResp->res);
553             return;
554         }
555 
556         bool foundDumpEntry = false;
557         std::string dumpEntryPath =
558             "/xyz/openbmc_project/dump/" +
559             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/";
560 
561         for (const auto& objectPath : resp)
562         {
563             if (objectPath.first.str != dumpEntryPath + entryID)
564             {
565                 continue;
566             }
567 
568             foundDumpEntry = true;
569             uint64_t timestampUs = 0;
570             uint64_t size = 0;
571             std::string dumpStatus;
572 
573             parseDumpEntryFromDbusObject(objectPath, dumpStatus, size,
574                                          timestampUs, asyncResp);
575 
576             if (dumpStatus !=
577                     "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" &&
578                 !dumpStatus.empty())
579             {
580                 // Dump status is not Complete
581                 // return not found until status is changed to Completed
582                 messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
583                 return;
584             }
585 
586             asyncResp->res.jsonValue["@odata.type"] =
587                 "#LogEntry.v1_8_0.LogEntry";
588             asyncResp->res.jsonValue["@odata.id"] = entriesPath + entryID;
589             asyncResp->res.jsonValue["Id"] = entryID;
590             asyncResp->res.jsonValue["EntryType"] = "Event";
591             asyncResp->res.jsonValue["Name"] = dumpType + " Dump Entry";
592 
593             if (dumpType == "BMC")
594             {
595                 asyncResp->res.jsonValue["Created"] =
596                     redfish::time_utils::getDateTimeUint(timestampUs / 1000 /
597                                                          1000);
598                 asyncResp->res.jsonValue["DiagnosticDataType"] = "Manager";
599                 asyncResp->res.jsonValue["AdditionalDataURI"] =
600                     entriesPath + entryID + "/attachment";
601                 asyncResp->res.jsonValue["AdditionalDataSizeBytes"] = size;
602             }
603             else if (dumpType == "FaultLog")
604             {
605                 asyncResp->res.jsonValue["Created"] =
606                     redfish::time_utils::getDateTimeUintUs(timestampUs);
607             }
608             else if (dumpType == "System")
609             {
610                 asyncResp->res.jsonValue["Created"] =
611                     redfish::time_utils::getDateTimeUint(timestampUs / 1000 /
612                                                          1000);
613                 asyncResp->res.jsonValue["DiagnosticDataType"] = "OEM";
614                 asyncResp->res.jsonValue["OEMDiagnosticDataType"] = "System";
615                 asyncResp->res.jsonValue["AdditionalDataURI"] =
616                     entriesPath + entryID + "/attachment";
617                 asyncResp->res.jsonValue["AdditionalDataSizeBytes"] = size;
618             }
619         }
620         if (!foundDumpEntry)
621         {
622             BMCWEB_LOG_ERROR << "Can't find Dump Entry";
623             messages::internalError(asyncResp->res);
624             return;
625         }
626         },
627         "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump",
628         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
629 }
630 
631 inline void deleteDumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
632                             const std::string& entryID,
633                             const std::string& dumpType)
634 {
635     auto respHandler =
636         [asyncResp, entryID](const boost::system::error_code ec) {
637         BMCWEB_LOG_DEBUG << "Dump Entry doDelete callback: Done";
638         if (ec)
639         {
640             if (ec.value() == EBADR)
641             {
642                 messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
643                 return;
644             }
645             BMCWEB_LOG_ERROR << "Dump (DBus) doDelete respHandler got error "
646                              << ec << " entryID=" << entryID;
647             messages::internalError(asyncResp->res);
648             return;
649         }
650     };
651     crow::connections::systemBus->async_method_call(
652         respHandler, "xyz.openbmc_project.Dump.Manager",
653         "/xyz/openbmc_project/dump/" +
654             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/" +
655             entryID,
656         "xyz.openbmc_project.Object.Delete", "Delete");
657 }
658 
659 inline void
660     createDumpTaskCallback(task::Payload&& payload,
661                            const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
662                            const uint32_t& dumpId, const std::string& dumpPath,
663                            const std::string& dumpType)
664 {
665     std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
666         [dumpId, dumpPath,
667          dumpType](boost::system::error_code err, sdbusplus::message_t& m,
668                    const std::shared_ptr<task::TaskData>& taskData) {
669         if (err)
670         {
671             BMCWEB_LOG_ERROR << "Error in creating a dump";
672             taskData->state = "Cancelled";
673             return task::completed;
674         }
675 
676         dbus::utility::DBusInteracesMap interfacesList;
677 
678         sdbusplus::message::object_path objPath;
679 
680         m.read(objPath, interfacesList);
681 
682         if (objPath.str ==
683             "/xyz/openbmc_project/dump/" +
684                 std::string(boost::algorithm::to_lower_copy(dumpType)) +
685                 "/entry/" + std::to_string(dumpId))
686         {
687             nlohmann::json retMessage = messages::success();
688             taskData->messages.emplace_back(retMessage);
689 
690             std::string headerLoc =
691                 "Location: " + dumpPath + std::to_string(dumpId);
692             taskData->payload->httpHeaders.emplace_back(std::move(headerLoc));
693 
694             taskData->state = "Completed";
695             return task::completed;
696         }
697         return task::completed;
698         },
699         "type='signal',interface='org.freedesktop.DBus.ObjectManager',"
700         "member='InterfacesAdded', "
701         "path='/xyz/openbmc_project/dump'");
702 
703     task->startTimer(std::chrono::minutes(3));
704     task->populateResp(asyncResp->res);
705     task->payload.emplace(std::move(payload));
706 }
707 
708 inline void createDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
709                        const crow::Request& req, const std::string& dumpType)
710 {
711     std::string dumpPath = getDumpEntriesPath(dumpType);
712     if (dumpPath.empty())
713     {
714         messages::internalError(asyncResp->res);
715         return;
716     }
717 
718     std::optional<std::string> diagnosticDataType;
719     std::optional<std::string> oemDiagnosticDataType;
720 
721     if (!redfish::json_util::readJsonAction(
722             req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
723             "OEMDiagnosticDataType", oemDiagnosticDataType))
724     {
725         return;
726     }
727 
728     if (dumpType == "System")
729     {
730         if (!oemDiagnosticDataType || !diagnosticDataType)
731         {
732             BMCWEB_LOG_ERROR
733                 << "CreateDump action parameter 'DiagnosticDataType'/'OEMDiagnosticDataType' value not found!";
734             messages::actionParameterMissing(
735                 asyncResp->res, "CollectDiagnosticData",
736                 "DiagnosticDataType & OEMDiagnosticDataType");
737             return;
738         }
739         if ((*oemDiagnosticDataType != "System") ||
740             (*diagnosticDataType != "OEM"))
741         {
742             BMCWEB_LOG_ERROR << "Wrong parameter values passed";
743             messages::internalError(asyncResp->res);
744             return;
745         }
746         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/";
747     }
748     else if (dumpType == "BMC")
749     {
750         if (!diagnosticDataType)
751         {
752             BMCWEB_LOG_ERROR
753                 << "CreateDump action parameter 'DiagnosticDataType' not found!";
754             messages::actionParameterMissing(
755                 asyncResp->res, "CollectDiagnosticData", "DiagnosticDataType");
756             return;
757         }
758         if (*diagnosticDataType != "Manager")
759         {
760             BMCWEB_LOG_ERROR
761                 << "Wrong parameter value passed for 'DiagnosticDataType'";
762             messages::internalError(asyncResp->res);
763             return;
764         }
765         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/";
766     }
767     else
768     {
769         BMCWEB_LOG_ERROR << "CreateDump failed. Unknown dump type";
770         messages::internalError(asyncResp->res);
771         return;
772     }
773 
774     crow::connections::systemBus->async_method_call(
775         [asyncResp, payload(task::Payload(req)), dumpPath,
776          dumpType](const boost::system::error_code ec,
777                    const sdbusplus::message::message& msg,
778                    const uint32_t& dumpId) mutable {
779         if (ec)
780         {
781             BMCWEB_LOG_ERROR << "CreateDump resp_handler got error " << ec;
782             const sd_bus_error* dbusError = msg.get_error();
783             if (dbusError == nullptr)
784             {
785                 messages::internalError(asyncResp->res);
786                 return;
787             }
788 
789             BMCWEB_LOG_ERROR << "CreateDump DBus error: " << dbusError->name
790                              << " and error msg: " << dbusError->message;
791             if (std::string_view(
792                     "xyz.openbmc_project.Common.Error.NotAllowed") ==
793                 dbusError->name)
794             {
795                 messages::resourceInStandby(asyncResp->res);
796                 return;
797             }
798             if (std::string_view(
799                     "xyz.openbmc_project.Dump.Create.Error.Disabled") ==
800                 dbusError->name)
801             {
802                 messages::serviceDisabled(asyncResp->res, dumpPath);
803                 return;
804             }
805             if (std::string_view(
806                     "xyz.openbmc_project.Common.Error.Unavailable") ==
807                 dbusError->name)
808             {
809                 messages::resourceInUse(asyncResp->res);
810                 return;
811             }
812             // Other Dbus errors such as:
813             // xyz.openbmc_project.Common.Error.InvalidArgument &
814             // org.freedesktop.DBus.Error.InvalidArgs are all related to
815             // the dbus call that is made here in the bmcweb
816             // implementation and has nothing to do with the client's
817             // input in the request. Hence, returning internal error
818             // back to the client.
819             messages::internalError(asyncResp->res);
820             return;
821         }
822         BMCWEB_LOG_DEBUG << "Dump Created. Id: " << dumpId;
823 
824         createDumpTaskCallback(std::move(payload), asyncResp, dumpId, dumpPath,
825                                dumpType);
826         },
827         "xyz.openbmc_project.Dump.Manager",
828         "/xyz/openbmc_project/dump/" +
829             std::string(boost::algorithm::to_lower_copy(dumpType)),
830         "xyz.openbmc_project.Dump.Create", "CreateDump");
831 }
832 
833 inline void clearDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
834                       const std::string& dumpType)
835 {
836     std::string dumpTypeLowerCopy =
837         std::string(boost::algorithm::to_lower_copy(dumpType));
838 
839     crow::connections::systemBus->async_method_call(
840         [asyncResp, dumpType](
841             const boost::system::error_code ec,
842             const dbus::utility::MapperGetSubTreePathsResponse& subTreePaths) {
843         if (ec)
844         {
845             BMCWEB_LOG_ERROR << "resp_handler got error " << ec;
846             messages::internalError(asyncResp->res);
847             return;
848         }
849 
850         for (const std::string& path : subTreePaths)
851         {
852             sdbusplus::message::object_path objPath(path);
853             std::string logID = objPath.filename();
854             if (logID.empty())
855             {
856                 continue;
857             }
858             deleteDumpEntry(asyncResp, logID, dumpType);
859         }
860         },
861         "xyz.openbmc_project.ObjectMapper",
862         "/xyz/openbmc_project/object_mapper",
863         "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
864         "/xyz/openbmc_project/dump/" + dumpTypeLowerCopy, 0,
865         std::array<std::string, 1>{"xyz.openbmc_project.Dump.Entry." +
866                                    dumpType});
867 }
868 
869 inline static void
870     parseCrashdumpParameters(const dbus::utility::DBusPropertiesMap& params,
871                              std::string& filename, std::string& timestamp,
872                              std::string& logfile)
873 {
874     for (auto property : params)
875     {
876         if (property.first == "Timestamp")
877         {
878             const std::string* value =
879                 std::get_if<std::string>(&property.second);
880             if (value != nullptr)
881             {
882                 timestamp = *value;
883             }
884         }
885         else if (property.first == "Filename")
886         {
887             const std::string* value =
888                 std::get_if<std::string>(&property.second);
889             if (value != nullptr)
890             {
891                 filename = *value;
892             }
893         }
894         else if (property.first == "Log")
895         {
896             const std::string* value =
897                 std::get_if<std::string>(&property.second);
898             if (value != nullptr)
899             {
900                 logfile = *value;
901             }
902         }
903     }
904 }
905 
906 constexpr char const* postCodeIface = "xyz.openbmc_project.State.Boot.PostCode";
907 inline void requestRoutesSystemLogServiceCollection(App& app)
908 {
909     /**
910      * Functions triggers appropriate requests on DBus
911      */
912     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/")
913         .privileges(redfish::privileges::getLogServiceCollection)
914         .methods(boost::beast::http::verb::get)(
915             [&app](const crow::Request& req,
916                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
917         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
918         {
919             return;
920         }
921         // Collections don't include the static data added by SubRoute
922         // because it has a duplicate entry for members
923         asyncResp->res.jsonValue["@odata.type"] =
924             "#LogServiceCollection.LogServiceCollection";
925         asyncResp->res.jsonValue["@odata.id"] =
926             "/redfish/v1/Systems/system/LogServices";
927         asyncResp->res.jsonValue["Name"] = "System Log Services Collection";
928         asyncResp->res.jsonValue["Description"] =
929             "Collection of LogServices for this Computer System";
930         nlohmann::json& logServiceArray = asyncResp->res.jsonValue["Members"];
931         logServiceArray = nlohmann::json::array();
932         nlohmann::json::object_t eventLog;
933         eventLog["@odata.id"] =
934             "/redfish/v1/Systems/system/LogServices/EventLog";
935         logServiceArray.push_back(std::move(eventLog));
936 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
937         nlohmann::json::object_t dumpLog;
938         dumpLog["@odata.id"] = "/redfish/v1/Systems/system/LogServices/Dump";
939         logServiceArray.push_back(std::move(dumpLog));
940 #endif
941 
942 #ifdef BMCWEB_ENABLE_REDFISH_CPU_LOG
943         nlohmann::json::object_t crashdump;
944         crashdump["@odata.id"] =
945             "/redfish/v1/Systems/system/LogServices/Crashdump";
946         logServiceArray.push_back(std::move(crashdump));
947 #endif
948 
949 #ifdef BMCWEB_ENABLE_REDFISH_HOST_LOGGER
950         nlohmann::json::object_t hostlogger;
951         hostlogger["@odata.id"] =
952             "/redfish/v1/Systems/system/LogServices/HostLogger";
953         logServiceArray.push_back(std::move(hostlogger));
954 #endif
955         asyncResp->res.jsonValue["Members@odata.count"] =
956             logServiceArray.size();
957 
958         crow::connections::systemBus->async_method_call(
959             [asyncResp](const boost::system::error_code ec,
960                         const dbus::utility::MapperGetSubTreePathsResponse&
961                             subtreePath) {
962             if (ec)
963             {
964                 BMCWEB_LOG_ERROR << ec;
965                 return;
966             }
967 
968             for (const auto& pathStr : subtreePath)
969             {
970                 if (pathStr.find("PostCode") != std::string::npos)
971                 {
972                     nlohmann::json& logServiceArrayLocal =
973                         asyncResp->res.jsonValue["Members"];
974                     logServiceArrayLocal.push_back(
975                         {{"@odata.id",
976                           "/redfish/v1/Systems/system/LogServices/PostCodes"}});
977                     asyncResp->res.jsonValue["Members@odata.count"] =
978                         logServiceArrayLocal.size();
979                     return;
980                 }
981             }
982             },
983             "xyz.openbmc_project.ObjectMapper",
984             "/xyz/openbmc_project/object_mapper",
985             "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", "/", 0,
986             std::array<const char*, 1>{postCodeIface});
987         });
988 }
989 
990 inline void requestRoutesEventLogService(App& app)
991 {
992     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/EventLog/")
993         .privileges(redfish::privileges::getLogService)
994         .methods(boost::beast::http::verb::get)(
995             [&app](const crow::Request& req,
996                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
997         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
998         {
999             return;
1000         }
1001         asyncResp->res.jsonValue["@odata.id"] =
1002             "/redfish/v1/Systems/system/LogServices/EventLog";
1003         asyncResp->res.jsonValue["@odata.type"] =
1004             "#LogService.v1_1_0.LogService";
1005         asyncResp->res.jsonValue["Name"] = "Event Log Service";
1006         asyncResp->res.jsonValue["Description"] = "System Event Log Service";
1007         asyncResp->res.jsonValue["Id"] = "EventLog";
1008         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
1009 
1010         std::pair<std::string, std::string> redfishDateTimeOffset =
1011             redfish::time_utils::getDateTimeOffsetNow();
1012 
1013         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
1014         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
1015             redfishDateTimeOffset.second;
1016 
1017         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
1018             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1019         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
1020 
1021             {"target",
1022              "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog"}};
1023         });
1024 }
1025 
1026 inline void requestRoutesJournalEventLogClear(App& app)
1027 {
1028     BMCWEB_ROUTE(
1029         app,
1030         "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog/")
1031         .privileges({{"ConfigureComponents"}})
1032         .methods(boost::beast::http::verb::post)(
1033             [&app](const crow::Request& req,
1034                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1035         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1036         {
1037             return;
1038         }
1039         // Clear the EventLog by deleting the log files
1040         std::vector<std::filesystem::path> redfishLogFiles;
1041         if (getRedfishLogFiles(redfishLogFiles))
1042         {
1043             for (const std::filesystem::path& file : redfishLogFiles)
1044             {
1045                 std::error_code ec;
1046                 std::filesystem::remove(file, ec);
1047             }
1048         }
1049 
1050         // Reload rsyslog so it knows to start new log files
1051         crow::connections::systemBus->async_method_call(
1052             [asyncResp](const boost::system::error_code ec) {
1053             if (ec)
1054             {
1055                 BMCWEB_LOG_ERROR << "Failed to reload rsyslog: " << ec;
1056                 messages::internalError(asyncResp->res);
1057                 return;
1058             }
1059 
1060             messages::success(asyncResp->res);
1061             },
1062             "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
1063             "org.freedesktop.systemd1.Manager", "ReloadUnit", "rsyslog.service",
1064             "replace");
1065         });
1066 }
1067 
1068 enum class LogParseError
1069 {
1070     success,
1071     parseFailed,
1072     messageIdNotInRegistry,
1073 };
1074 
1075 static LogParseError
1076     fillEventLogEntryJson(const std::string& logEntryID,
1077                           const std::string& logEntry,
1078                           nlohmann::json::object_t& logEntryJson)
1079 {
1080     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1081     // First get the Timestamp
1082     size_t space = logEntry.find_first_of(' ');
1083     if (space == std::string::npos)
1084     {
1085         return LogParseError::parseFailed;
1086     }
1087     std::string timestamp = logEntry.substr(0, space);
1088     // Then get the log contents
1089     size_t entryStart = logEntry.find_first_not_of(' ', space);
1090     if (entryStart == std::string::npos)
1091     {
1092         return LogParseError::parseFailed;
1093     }
1094     std::string_view entry(logEntry);
1095     entry.remove_prefix(entryStart);
1096     // Use split to separate the entry into its fields
1097     std::vector<std::string> logEntryFields;
1098     boost::split(logEntryFields, entry, boost::is_any_of(","),
1099                  boost::token_compress_on);
1100     // We need at least a MessageId to be valid
1101     if (logEntryFields.empty())
1102     {
1103         return LogParseError::parseFailed;
1104     }
1105     std::string& messageID = logEntryFields[0];
1106 
1107     // Get the Message from the MessageRegistry
1108     const registries::Message* message = registries::getMessage(messageID);
1109 
1110     if (message == nullptr)
1111     {
1112         BMCWEB_LOG_WARNING << "Log entry not found in registry: " << logEntry;
1113         return LogParseError::messageIdNotInRegistry;
1114     }
1115 
1116     std::string msg = message->message;
1117 
1118     // Get the MessageArgs from the log if there are any
1119     std::span<std::string> messageArgs;
1120     if (logEntryFields.size() > 1)
1121     {
1122         std::string& messageArgsStart = logEntryFields[1];
1123         // If the first string is empty, assume there are no MessageArgs
1124         std::size_t messageArgsSize = 0;
1125         if (!messageArgsStart.empty())
1126         {
1127             messageArgsSize = logEntryFields.size() - 1;
1128         }
1129 
1130         messageArgs = {&messageArgsStart, messageArgsSize};
1131 
1132         // Fill the MessageArgs into the Message
1133         int i = 0;
1134         for (const std::string& messageArg : messageArgs)
1135         {
1136             std::string argStr = "%" + std::to_string(++i);
1137             size_t argPos = msg.find(argStr);
1138             if (argPos != std::string::npos)
1139             {
1140                 msg.replace(argPos, argStr.length(), messageArg);
1141             }
1142         }
1143     }
1144 
1145     // Get the Created time from the timestamp. The log timestamp is in RFC3339
1146     // format which matches the Redfish format except for the fractional seconds
1147     // between the '.' and the '+', so just remove them.
1148     std::size_t dot = timestamp.find_first_of('.');
1149     std::size_t plus = timestamp.find_first_of('+');
1150     if (dot != std::string::npos && plus != std::string::npos)
1151     {
1152         timestamp.erase(dot, plus - dot);
1153     }
1154 
1155     // Fill in the log entry with the gathered data
1156     logEntryJson["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
1157     logEntryJson["@odata.id"] =
1158         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" + logEntryID;
1159     logEntryJson["Name"] = "System Event Log Entry";
1160     logEntryJson["Id"] = logEntryID;
1161     logEntryJson["Message"] = std::move(msg);
1162     logEntryJson["MessageId"] = std::move(messageID);
1163     logEntryJson["MessageArgs"] = messageArgs;
1164     logEntryJson["EntryType"] = "Event";
1165     logEntryJson["Severity"] = message->messageSeverity;
1166     logEntryJson["Created"] = std::move(timestamp);
1167     return LogParseError::success;
1168 }
1169 
1170 inline void requestRoutesJournalEventLogEntryCollection(App& app)
1171 {
1172     BMCWEB_ROUTE(app,
1173                  "/redfish/v1/Systems/system/LogServices/EventLog/Entries/")
1174         .privileges(redfish::privileges::getLogEntryCollection)
1175         .methods(boost::beast::http::verb::get)(
1176             [&app](const crow::Request& req,
1177                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1178         query_param::QueryCapabilities capabilities = {
1179             .canDelegateTop = true,
1180             .canDelegateSkip = true,
1181         };
1182         query_param::Query delegatedQuery;
1183         if (!redfish::setUpRedfishRouteWithDelegation(
1184                 app, req, asyncResp, delegatedQuery, capabilities))
1185         {
1186             return;
1187         }
1188         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
1189         size_t skip = delegatedQuery.skip.value_or(0);
1190 
1191         // Collections don't include the static data added by SubRoute
1192         // because it has a duplicate entry for members
1193         asyncResp->res.jsonValue["@odata.type"] =
1194             "#LogEntryCollection.LogEntryCollection";
1195         asyncResp->res.jsonValue["@odata.id"] =
1196             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1197         asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1198         asyncResp->res.jsonValue["Description"] =
1199             "Collection of System Event Log Entries";
1200 
1201         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
1202         logEntryArray = nlohmann::json::array();
1203         // Go through the log files and create a unique ID for each
1204         // entry
1205         std::vector<std::filesystem::path> redfishLogFiles;
1206         getRedfishLogFiles(redfishLogFiles);
1207         uint64_t entryCount = 0;
1208         std::string logEntry;
1209 
1210         // Oldest logs are in the last file, so start there and loop
1211         // backwards
1212         for (auto it = redfishLogFiles.rbegin(); it < redfishLogFiles.rend();
1213              it++)
1214         {
1215             std::ifstream logStream(*it);
1216             if (!logStream.is_open())
1217             {
1218                 continue;
1219             }
1220 
1221             // Reset the unique ID on the first entry
1222             bool firstEntry = true;
1223             while (std::getline(logStream, logEntry))
1224             {
1225                 std::string idStr;
1226                 if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1227                 {
1228                     continue;
1229                 }
1230                 firstEntry = false;
1231 
1232                 nlohmann::json::object_t bmcLogEntry;
1233                 LogParseError status =
1234                     fillEventLogEntryJson(idStr, logEntry, bmcLogEntry);
1235                 if (status == LogParseError::messageIdNotInRegistry)
1236                 {
1237                     continue;
1238                 }
1239                 if (status != LogParseError::success)
1240                 {
1241                     messages::internalError(asyncResp->res);
1242                     return;
1243                 }
1244 
1245                 entryCount++;
1246                 // Handle paging using skip (number of entries to skip from the
1247                 // start) and top (number of entries to display)
1248                 if (entryCount <= skip || entryCount > skip + top)
1249                 {
1250                     continue;
1251                 }
1252 
1253                 logEntryArray.push_back(std::move(bmcLogEntry));
1254             }
1255         }
1256         asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
1257         if (skip + top < entryCount)
1258         {
1259             asyncResp->res.jsonValue["Members@odata.nextLink"] =
1260                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries?$skip=" +
1261                 std::to_string(skip + top);
1262         }
1263         });
1264 }
1265 
1266 inline void requestRoutesJournalEventLogEntry(App& app)
1267 {
1268     BMCWEB_ROUTE(
1269         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1270         .privileges(redfish::privileges::getLogEntry)
1271         .methods(boost::beast::http::verb::get)(
1272             [&app](const crow::Request& req,
1273                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1274                    const std::string& param) {
1275         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1276         {
1277             return;
1278         }
1279         const std::string& targetID = param;
1280 
1281         // Go through the log files and check the unique ID for each
1282         // entry to find the target entry
1283         std::vector<std::filesystem::path> redfishLogFiles;
1284         getRedfishLogFiles(redfishLogFiles);
1285         std::string logEntry;
1286 
1287         // Oldest logs are in the last file, so start there and loop
1288         // backwards
1289         for (auto it = redfishLogFiles.rbegin(); it < redfishLogFiles.rend();
1290              it++)
1291         {
1292             std::ifstream logStream(*it);
1293             if (!logStream.is_open())
1294             {
1295                 continue;
1296             }
1297 
1298             // Reset the unique ID on the first entry
1299             bool firstEntry = true;
1300             while (std::getline(logStream, logEntry))
1301             {
1302                 std::string idStr;
1303                 if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1304                 {
1305                     continue;
1306                 }
1307                 firstEntry = false;
1308 
1309                 if (idStr == targetID)
1310                 {
1311                     nlohmann::json::object_t bmcLogEntry;
1312                     LogParseError status =
1313                         fillEventLogEntryJson(idStr, logEntry, bmcLogEntry);
1314                     if (status != LogParseError::success)
1315                     {
1316                         messages::internalError(asyncResp->res);
1317                         return;
1318                     }
1319                     asyncResp->res.jsonValue.update(bmcLogEntry);
1320                     return;
1321                 }
1322             }
1323         }
1324         // Requested ID was not found
1325         messages::resourceMissingAtURI(asyncResp->res,
1326                                        crow::utility::urlFromPieces(targetID));
1327         });
1328 }
1329 
1330 inline void requestRoutesDBusEventLogEntryCollection(App& app)
1331 {
1332     BMCWEB_ROUTE(app,
1333                  "/redfish/v1/Systems/system/LogServices/EventLog/Entries/")
1334         .privileges(redfish::privileges::getLogEntryCollection)
1335         .methods(boost::beast::http::verb::get)(
1336             [&app](const crow::Request& req,
1337                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1338         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1339         {
1340             return;
1341         }
1342         // Collections don't include the static data added by SubRoute
1343         // because it has a duplicate entry for members
1344         asyncResp->res.jsonValue["@odata.type"] =
1345             "#LogEntryCollection.LogEntryCollection";
1346         asyncResp->res.jsonValue["@odata.id"] =
1347             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1348         asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1349         asyncResp->res.jsonValue["Description"] =
1350             "Collection of System Event Log Entries";
1351 
1352         // DBus implementation of EventLog/Entries
1353         // Make call to Logging Service to find all log entry objects
1354         crow::connections::systemBus->async_method_call(
1355             [asyncResp](const boost::system::error_code ec,
1356                         const dbus::utility::ManagedObjectType& resp) {
1357             if (ec)
1358             {
1359                 // TODO Handle for specific error code
1360                 BMCWEB_LOG_ERROR
1361                     << "getLogEntriesIfaceData resp_handler got error " << ec;
1362                 messages::internalError(asyncResp->res);
1363                 return;
1364             }
1365             nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
1366             entriesArray = nlohmann::json::array();
1367             for (const auto& objectPath : resp)
1368             {
1369                 const uint32_t* id = nullptr;
1370                 const uint64_t* timestamp = nullptr;
1371                 const uint64_t* updateTimestamp = nullptr;
1372                 const std::string* severity = nullptr;
1373                 const std::string* message = nullptr;
1374                 const std::string* filePath = nullptr;
1375                 bool resolved = false;
1376                 for (const auto& interfaceMap : objectPath.second)
1377                 {
1378                     if (interfaceMap.first ==
1379                         "xyz.openbmc_project.Logging.Entry")
1380                     {
1381                         for (const auto& propertyMap : interfaceMap.second)
1382                         {
1383                             if (propertyMap.first == "Id")
1384                             {
1385                                 id = std::get_if<uint32_t>(&propertyMap.second);
1386                             }
1387                             else if (propertyMap.first == "Timestamp")
1388                             {
1389                                 timestamp =
1390                                     std::get_if<uint64_t>(&propertyMap.second);
1391                             }
1392                             else if (propertyMap.first == "UpdateTimestamp")
1393                             {
1394                                 updateTimestamp =
1395                                     std::get_if<uint64_t>(&propertyMap.second);
1396                             }
1397                             else if (propertyMap.first == "Severity")
1398                             {
1399                                 severity = std::get_if<std::string>(
1400                                     &propertyMap.second);
1401                             }
1402                             else if (propertyMap.first == "Message")
1403                             {
1404                                 message = std::get_if<std::string>(
1405                                     &propertyMap.second);
1406                             }
1407                             else if (propertyMap.first == "Resolved")
1408                             {
1409                                 const bool* resolveptr =
1410                                     std::get_if<bool>(&propertyMap.second);
1411                                 if (resolveptr == nullptr)
1412                                 {
1413                                     messages::internalError(asyncResp->res);
1414                                     return;
1415                                 }
1416                                 resolved = *resolveptr;
1417                             }
1418                         }
1419                         if (id == nullptr || message == nullptr ||
1420                             severity == nullptr)
1421                         {
1422                             messages::internalError(asyncResp->res);
1423                             return;
1424                         }
1425                     }
1426                     else if (interfaceMap.first ==
1427                              "xyz.openbmc_project.Common.FilePath")
1428                     {
1429                         for (const auto& propertyMap : interfaceMap.second)
1430                         {
1431                             if (propertyMap.first == "Path")
1432                             {
1433                                 filePath = std::get_if<std::string>(
1434                                     &propertyMap.second);
1435                             }
1436                         }
1437                     }
1438                 }
1439                 // Object path without the
1440                 // xyz.openbmc_project.Logging.Entry interface, ignore
1441                 // and continue.
1442                 if (id == nullptr || message == nullptr ||
1443                     severity == nullptr || timestamp == nullptr ||
1444                     updateTimestamp == nullptr)
1445                 {
1446                     continue;
1447                 }
1448                 entriesArray.push_back({});
1449                 nlohmann::json& thisEntry = entriesArray.back();
1450                 thisEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
1451                 thisEntry["@odata.id"] =
1452                     "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1453                     std::to_string(*id);
1454                 thisEntry["Name"] = "System Event Log Entry";
1455                 thisEntry["Id"] = std::to_string(*id);
1456                 thisEntry["Message"] = *message;
1457                 thisEntry["Resolved"] = resolved;
1458                 thisEntry["EntryType"] = "Event";
1459                 thisEntry["Severity"] =
1460                     translateSeverityDbusToRedfish(*severity);
1461                 thisEntry["Created"] =
1462                     redfish::time_utils::getDateTimeUintMs(*timestamp);
1463                 thisEntry["Modified"] =
1464                     redfish::time_utils::getDateTimeUintMs(*updateTimestamp);
1465                 if (filePath != nullptr)
1466                 {
1467                     thisEntry["AdditionalDataURI"] =
1468                         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1469                         std::to_string(*id) + "/attachment";
1470                 }
1471             }
1472             std::sort(
1473                 entriesArray.begin(), entriesArray.end(),
1474                 [](const nlohmann::json& left, const nlohmann::json& right) {
1475                 return (left["Id"] <= right["Id"]);
1476                 });
1477             asyncResp->res.jsonValue["Members@odata.count"] =
1478                 entriesArray.size();
1479             },
1480             "xyz.openbmc_project.Logging", "/xyz/openbmc_project/logging",
1481             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1482         });
1483 }
1484 
1485 inline void requestRoutesDBusEventLogEntry(App& app)
1486 {
1487     BMCWEB_ROUTE(
1488         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1489         .privileges(redfish::privileges::getLogEntry)
1490         .methods(boost::beast::http::verb::get)(
1491             [&app](const crow::Request& req,
1492                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1493                    const std::string& param) {
1494         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1495         {
1496             return;
1497         }
1498         std::string entryID = param;
1499         dbus::utility::escapePathForDbus(entryID);
1500 
1501         // DBus implementation of EventLog/Entries
1502         // Make call to Logging Service to find all log entry objects
1503         crow::connections::systemBus->async_method_call(
1504             [asyncResp, entryID](const boost::system::error_code ec,
1505                                  const dbus::utility::DBusPropertiesMap& resp) {
1506             if (ec.value() == EBADR)
1507             {
1508                 messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
1509                 return;
1510             }
1511             if (ec)
1512             {
1513                 BMCWEB_LOG_ERROR
1514                     << "EventLogEntry (DBus) resp_handler got error " << ec;
1515                 messages::internalError(asyncResp->res);
1516                 return;
1517             }
1518             const uint32_t* id = nullptr;
1519             const uint64_t* timestamp = nullptr;
1520             const uint64_t* updateTimestamp = nullptr;
1521             const std::string* severity = nullptr;
1522             const std::string* message = nullptr;
1523             const std::string* filePath = nullptr;
1524             bool resolved = false;
1525 
1526             for (const auto& propertyMap : resp)
1527             {
1528                 if (propertyMap.first == "Id")
1529                 {
1530                     id = std::get_if<uint32_t>(&propertyMap.second);
1531                 }
1532                 else if (propertyMap.first == "Timestamp")
1533                 {
1534                     timestamp = std::get_if<uint64_t>(&propertyMap.second);
1535                 }
1536                 else if (propertyMap.first == "UpdateTimestamp")
1537                 {
1538                     updateTimestamp =
1539                         std::get_if<uint64_t>(&propertyMap.second);
1540                 }
1541                 else if (propertyMap.first == "Severity")
1542                 {
1543                     severity = std::get_if<std::string>(&propertyMap.second);
1544                 }
1545                 else if (propertyMap.first == "Message")
1546                 {
1547                     message = std::get_if<std::string>(&propertyMap.second);
1548                 }
1549                 else if (propertyMap.first == "Resolved")
1550                 {
1551                     const bool* resolveptr =
1552                         std::get_if<bool>(&propertyMap.second);
1553                     if (resolveptr == nullptr)
1554                     {
1555                         messages::internalError(asyncResp->res);
1556                         return;
1557                     }
1558                     resolved = *resolveptr;
1559                 }
1560                 else if (propertyMap.first == "Path")
1561                 {
1562                     filePath = std::get_if<std::string>(&propertyMap.second);
1563                 }
1564             }
1565             if (id == nullptr || message == nullptr || severity == nullptr ||
1566                 timestamp == nullptr || updateTimestamp == nullptr)
1567             {
1568                 messages::internalError(asyncResp->res);
1569                 return;
1570             }
1571             asyncResp->res.jsonValue["@odata.type"] =
1572                 "#LogEntry.v1_8_0.LogEntry";
1573             asyncResp->res.jsonValue["@odata.id"] =
1574                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1575                 std::to_string(*id);
1576             asyncResp->res.jsonValue["Name"] = "System Event Log Entry";
1577             asyncResp->res.jsonValue["Id"] = std::to_string(*id);
1578             asyncResp->res.jsonValue["Message"] = *message;
1579             asyncResp->res.jsonValue["Resolved"] = resolved;
1580             asyncResp->res.jsonValue["EntryType"] = "Event";
1581             asyncResp->res.jsonValue["Severity"] =
1582                 translateSeverityDbusToRedfish(*severity);
1583             asyncResp->res.jsonValue["Created"] =
1584                 redfish::time_utils::getDateTimeUintMs(*timestamp);
1585             asyncResp->res.jsonValue["Modified"] =
1586                 redfish::time_utils::getDateTimeUintMs(*updateTimestamp);
1587             if (filePath != nullptr)
1588             {
1589                 asyncResp->res.jsonValue["AdditionalDataURI"] =
1590                     "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1591                     std::to_string(*id) + "/attachment";
1592             }
1593             },
1594             "xyz.openbmc_project.Logging",
1595             "/xyz/openbmc_project/logging/entry/" + entryID,
1596             "org.freedesktop.DBus.Properties", "GetAll", "");
1597         });
1598 
1599     BMCWEB_ROUTE(
1600         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1601         .privileges(redfish::privileges::patchLogEntry)
1602         .methods(boost::beast::http::verb::patch)(
1603             [&app](const crow::Request& req,
1604                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1605                    const std::string& entryId) {
1606         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1607         {
1608             return;
1609         }
1610         std::optional<bool> resolved;
1611 
1612         if (!json_util::readJsonPatch(req, asyncResp->res, "Resolved",
1613                                       resolved))
1614         {
1615             return;
1616         }
1617         BMCWEB_LOG_DEBUG << "Set Resolved";
1618 
1619         crow::connections::systemBus->async_method_call(
1620             [asyncResp, entryId](const boost::system::error_code ec) {
1621             if (ec)
1622             {
1623                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1624                 messages::internalError(asyncResp->res);
1625                 return;
1626             }
1627             },
1628             "xyz.openbmc_project.Logging",
1629             "/xyz/openbmc_project/logging/entry/" + entryId,
1630             "org.freedesktop.DBus.Properties", "Set",
1631             "xyz.openbmc_project.Logging.Entry", "Resolved",
1632             dbus::utility::DbusVariantType(*resolved));
1633         });
1634 
1635     BMCWEB_ROUTE(
1636         app, "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/")
1637         .privileges(redfish::privileges::deleteLogEntry)
1638 
1639         .methods(boost::beast::http::verb::delete_)(
1640             [&app](const crow::Request& req,
1641                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1642                    const std::string& param) {
1643         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1644         {
1645             return;
1646         }
1647         BMCWEB_LOG_DEBUG << "Do delete single event entries.";
1648 
1649         std::string entryID = param;
1650 
1651         dbus::utility::escapePathForDbus(entryID);
1652 
1653         // Process response from Logging service.
1654         auto respHandler =
1655             [asyncResp, entryID](const boost::system::error_code ec) {
1656             BMCWEB_LOG_DEBUG << "EventLogEntry (DBus) doDelete callback: Done";
1657             if (ec)
1658             {
1659                 if (ec.value() == EBADR)
1660                 {
1661                     messages::resourceNotFound(asyncResp->res, "LogEntry",
1662                                                entryID);
1663                     return;
1664                 }
1665                 // TODO Handle for specific error code
1666                 BMCWEB_LOG_ERROR
1667                     << "EventLogEntry (DBus) doDelete respHandler got error "
1668                     << ec;
1669                 asyncResp->res.result(
1670                     boost::beast::http::status::internal_server_error);
1671                 return;
1672             }
1673 
1674             asyncResp->res.result(boost::beast::http::status::ok);
1675         };
1676 
1677         // Make call to Logging service to request Delete Log
1678         crow::connections::systemBus->async_method_call(
1679             respHandler, "xyz.openbmc_project.Logging",
1680             "/xyz/openbmc_project/logging/entry/" + entryID,
1681             "xyz.openbmc_project.Object.Delete", "Delete");
1682         });
1683 }
1684 
1685 inline void requestRoutesDBusEventLogEntryDownload(App& app)
1686 {
1687     BMCWEB_ROUTE(
1688         app,
1689         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/<str>/attachment")
1690         .privileges(redfish::privileges::getLogEntry)
1691         .methods(boost::beast::http::verb::get)(
1692             [&app](const crow::Request& req,
1693                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1694                    const std::string& param) {
1695         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1696         {
1697             return;
1698         }
1699         if (!http_helpers::isOctetAccepted(req.getHeaderValue("Accept")))
1700         {
1701             asyncResp->res.result(boost::beast::http::status::bad_request);
1702             return;
1703         }
1704 
1705         std::string entryID = param;
1706         dbus::utility::escapePathForDbus(entryID);
1707 
1708         crow::connections::systemBus->async_method_call(
1709             [asyncResp, entryID](const boost::system::error_code ec,
1710                                  const sdbusplus::message::unix_fd& unixfd) {
1711             if (ec.value() == EBADR)
1712             {
1713                 messages::resourceNotFound(asyncResp->res, "EventLogAttachment",
1714                                            entryID);
1715                 return;
1716             }
1717             if (ec)
1718             {
1719                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1720                 messages::internalError(asyncResp->res);
1721                 return;
1722             }
1723 
1724             int fd = -1;
1725             fd = dup(unixfd);
1726             if (fd == -1)
1727             {
1728                 messages::internalError(asyncResp->res);
1729                 return;
1730             }
1731 
1732             long long int size = lseek(fd, 0, SEEK_END);
1733             if (size == -1)
1734             {
1735                 messages::internalError(asyncResp->res);
1736                 return;
1737             }
1738 
1739             // Arbitrary max size of 64kb
1740             constexpr int maxFileSize = 65536;
1741             if (size > maxFileSize)
1742             {
1743                 BMCWEB_LOG_ERROR << "File size exceeds maximum allowed size of "
1744                                  << maxFileSize;
1745                 messages::internalError(asyncResp->res);
1746                 return;
1747             }
1748             std::vector<char> data(static_cast<size_t>(size));
1749             long long int rc = lseek(fd, 0, SEEK_SET);
1750             if (rc == -1)
1751             {
1752                 messages::internalError(asyncResp->res);
1753                 return;
1754             }
1755             rc = read(fd, data.data(), data.size());
1756             if ((rc == -1) || (rc != size))
1757             {
1758                 messages::internalError(asyncResp->res);
1759                 return;
1760             }
1761             close(fd);
1762 
1763             std::string_view strData(data.data(), data.size());
1764             std::string output = crow::utility::base64encode(strData);
1765 
1766             asyncResp->res.addHeader(boost::beast::http::field::content_type,
1767                                      "application/octet-stream");
1768             asyncResp->res.addHeader(
1769                 boost::beast::http::field::content_transfer_encoding, "Base64");
1770             asyncResp->res.body() = std::move(output);
1771             },
1772             "xyz.openbmc_project.Logging",
1773             "/xyz/openbmc_project/logging/entry/" + entryID,
1774             "xyz.openbmc_project.Logging.Entry", "GetEntry");
1775         });
1776 }
1777 
1778 constexpr const char* hostLoggerFolderPath = "/var/log/console";
1779 
1780 inline bool
1781     getHostLoggerFiles(const std::string& hostLoggerFilePath,
1782                        std::vector<std::filesystem::path>& hostLoggerFiles)
1783 {
1784     std::error_code ec;
1785     std::filesystem::directory_iterator logPath(hostLoggerFilePath, ec);
1786     if (ec)
1787     {
1788         BMCWEB_LOG_ERROR << ec.message();
1789         return false;
1790     }
1791     for (const std::filesystem::directory_entry& it : logPath)
1792     {
1793         std::string filename = it.path().filename();
1794         // Prefix of each log files is "log". Find the file and save the
1795         // path
1796         if (filename.starts_with("log"))
1797         {
1798             hostLoggerFiles.emplace_back(it.path());
1799         }
1800     }
1801     // As the log files rotate, they are appended with a ".#" that is higher for
1802     // the older logs. Since we start from oldest logs, sort the name in
1803     // descending order.
1804     std::sort(hostLoggerFiles.rbegin(), hostLoggerFiles.rend(),
1805               AlphanumLess<std::string>());
1806 
1807     return true;
1808 }
1809 
1810 inline bool getHostLoggerEntries(
1811     const std::vector<std::filesystem::path>& hostLoggerFiles, uint64_t skip,
1812     uint64_t top, std::vector<std::string>& logEntries, size_t& logCount)
1813 {
1814     GzFileReader logFile;
1815 
1816     // Go though all log files and expose host logs.
1817     for (const std::filesystem::path& it : hostLoggerFiles)
1818     {
1819         if (!logFile.gzGetLines(it.string(), skip, top, logEntries, logCount))
1820         {
1821             BMCWEB_LOG_ERROR << "fail to expose host logs";
1822             return false;
1823         }
1824     }
1825     // Get lastMessage from constructor by getter
1826     std::string lastMessage = logFile.getLastMessage();
1827     if (!lastMessage.empty())
1828     {
1829         logCount++;
1830         if (logCount > skip && logCount <= (skip + top))
1831         {
1832             logEntries.push_back(lastMessage);
1833         }
1834     }
1835     return true;
1836 }
1837 
1838 inline void fillHostLoggerEntryJson(const std::string& logEntryID,
1839                                     const std::string& msg,
1840                                     nlohmann::json::object_t& logEntryJson)
1841 {
1842     // Fill in the log entry with the gathered data.
1843     logEntryJson["@odata.type"] = "#LogEntry.v1_4_0.LogEntry";
1844     logEntryJson["@odata.id"] =
1845         "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/" +
1846         logEntryID;
1847     logEntryJson["Name"] = "Host Logger Entry";
1848     logEntryJson["Id"] = logEntryID;
1849     logEntryJson["Message"] = msg;
1850     logEntryJson["EntryType"] = "Oem";
1851     logEntryJson["Severity"] = "OK";
1852     logEntryJson["OemRecordFormat"] = "Host Logger Entry";
1853 }
1854 
1855 inline void requestRoutesSystemHostLogger(App& app)
1856 {
1857     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/HostLogger/")
1858         .privileges(redfish::privileges::getLogService)
1859         .methods(boost::beast::http::verb::get)(
1860             [&app](const crow::Request& req,
1861                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1862         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1863         {
1864             return;
1865         }
1866         asyncResp->res.jsonValue["@odata.id"] =
1867             "/redfish/v1/Systems/system/LogServices/HostLogger";
1868         asyncResp->res.jsonValue["@odata.type"] =
1869             "#LogService.v1_1_0.LogService";
1870         asyncResp->res.jsonValue["Name"] = "Host Logger Service";
1871         asyncResp->res.jsonValue["Description"] = "Host Logger Service";
1872         asyncResp->res.jsonValue["Id"] = "HostLogger";
1873         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
1874             "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
1875         });
1876 }
1877 
1878 inline void requestRoutesSystemHostLoggerCollection(App& app)
1879 {
1880     BMCWEB_ROUTE(app,
1881                  "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/")
1882         .privileges(redfish::privileges::getLogEntry)
1883         .methods(boost::beast::http::verb::get)(
1884             [&app](const crow::Request& req,
1885                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
1886         query_param::QueryCapabilities capabilities = {
1887             .canDelegateTop = true,
1888             .canDelegateSkip = true,
1889         };
1890         query_param::Query delegatedQuery;
1891         if (!redfish::setUpRedfishRouteWithDelegation(
1892                 app, req, asyncResp, delegatedQuery, capabilities))
1893         {
1894             return;
1895         }
1896         asyncResp->res.jsonValue["@odata.id"] =
1897             "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
1898         asyncResp->res.jsonValue["@odata.type"] =
1899             "#LogEntryCollection.LogEntryCollection";
1900         asyncResp->res.jsonValue["Name"] = "HostLogger Entries";
1901         asyncResp->res.jsonValue["Description"] =
1902             "Collection of HostLogger Entries";
1903         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
1904         logEntryArray = nlohmann::json::array();
1905         asyncResp->res.jsonValue["Members@odata.count"] = 0;
1906 
1907         std::vector<std::filesystem::path> hostLoggerFiles;
1908         if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
1909         {
1910             BMCWEB_LOG_ERROR << "fail to get host log file path";
1911             return;
1912         }
1913         // If we weren't provided top and skip limits, use the defaults.
1914         size_t skip = delegatedQuery.skip.value_or(0);
1915         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
1916         size_t logCount = 0;
1917         // This vector only store the entries we want to expose that
1918         // control by skip and top.
1919         std::vector<std::string> logEntries;
1920         if (!getHostLoggerEntries(hostLoggerFiles, skip, top, logEntries,
1921                                   logCount))
1922         {
1923             messages::internalError(asyncResp->res);
1924             return;
1925         }
1926         // If vector is empty, that means skip value larger than total
1927         // log count
1928         if (logEntries.empty())
1929         {
1930             asyncResp->res.jsonValue["Members@odata.count"] = logCount;
1931             return;
1932         }
1933         if (!logEntries.empty())
1934         {
1935             for (size_t i = 0; i < logEntries.size(); i++)
1936             {
1937                 nlohmann::json::object_t hostLogEntry;
1938                 fillHostLoggerEntryJson(std::to_string(skip + i), logEntries[i],
1939                                         hostLogEntry);
1940                 logEntryArray.push_back(std::move(hostLogEntry));
1941             }
1942 
1943             asyncResp->res.jsonValue["Members@odata.count"] = logCount;
1944             if (skip + top < logCount)
1945             {
1946                 asyncResp->res.jsonValue["Members@odata.nextLink"] =
1947                     "/redfish/v1/Systems/system/LogServices/HostLogger/Entries?$skip=" +
1948                     std::to_string(skip + top);
1949             }
1950         }
1951         });
1952 }
1953 
1954 inline void requestRoutesSystemHostLoggerLogEntry(App& app)
1955 {
1956     BMCWEB_ROUTE(
1957         app, "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/<str>/")
1958         .privileges(redfish::privileges::getLogEntry)
1959         .methods(boost::beast::http::verb::get)(
1960             [&app](const crow::Request& req,
1961                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1962                    const std::string& param) {
1963         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1964         {
1965             return;
1966         }
1967         const std::string& targetID = param;
1968 
1969         uint64_t idInt = 0;
1970 
1971         // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
1972         const char* end = targetID.data() + targetID.size();
1973 
1974         auto [ptr, ec] = std::from_chars(targetID.data(), end, idInt);
1975         if (ec == std::errc::invalid_argument)
1976         {
1977             messages::resourceMissingAtURI(asyncResp->res, req.urlView);
1978             return;
1979         }
1980         if (ec == std::errc::result_out_of_range)
1981         {
1982             messages::resourceMissingAtURI(asyncResp->res, req.urlView);
1983             return;
1984         }
1985 
1986         std::vector<std::filesystem::path> hostLoggerFiles;
1987         if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
1988         {
1989             BMCWEB_LOG_ERROR << "fail to get host log file path";
1990             return;
1991         }
1992 
1993         size_t logCount = 0;
1994         size_t top = 1;
1995         std::vector<std::string> logEntries;
1996         // We can get specific entry by skip and top. For example, if we
1997         // want to get nth entry, we can set skip = n-1 and top = 1 to
1998         // get that entry
1999         if (!getHostLoggerEntries(hostLoggerFiles, idInt, top, logEntries,
2000                                   logCount))
2001         {
2002             messages::internalError(asyncResp->res);
2003             return;
2004         }
2005 
2006         if (!logEntries.empty())
2007         {
2008             nlohmann::json::object_t hostLogEntry;
2009             fillHostLoggerEntryJson(targetID, logEntries[0], hostLogEntry);
2010             asyncResp->res.jsonValue.update(hostLogEntry);
2011             return;
2012         }
2013 
2014         // Requested ID was not found
2015         messages::resourceMissingAtURI(asyncResp->res, req.urlView);
2016         });
2017 }
2018 
2019 constexpr char const* dumpManagerIface =
2020     "xyz.openbmc_project.Collection.DeleteAll";
2021 inline void handleBMCLogServicesCollectionGet(
2022     crow::App& app, const crow::Request& req,
2023     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2024 {
2025     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2026     {
2027         return;
2028     }
2029     // Collections don't include the static data added by SubRoute
2030     // because it has a duplicate entry for members
2031     asyncResp->res.jsonValue["@odata.type"] =
2032         "#LogServiceCollection.LogServiceCollection";
2033     asyncResp->res.jsonValue["@odata.id"] =
2034         "/redfish/v1/Managers/bmc/LogServices";
2035     asyncResp->res.jsonValue["Name"] = "Open BMC Log Services Collection";
2036     asyncResp->res.jsonValue["Description"] =
2037         "Collection of LogServices for this Manager";
2038     nlohmann::json& logServiceArray = asyncResp->res.jsonValue["Members"];
2039     logServiceArray = nlohmann::json::array();
2040 
2041 #ifdef BMCWEB_ENABLE_REDFISH_BMC_JOURNAL
2042     logServiceArray.push_back(
2043         {{"@odata.id", "/redfish/v1/Managers/bmc/LogServices/Journal"}});
2044 #endif
2045 
2046     asyncResp->res.jsonValue["Members@odata.count"] = logServiceArray.size();
2047 
2048 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
2049     auto respHandler =
2050         [asyncResp](
2051             const boost::system::error_code ec,
2052             const dbus::utility::MapperGetSubTreePathsResponse& subTreePaths) {
2053         if (ec)
2054         {
2055             BMCWEB_LOG_ERROR
2056                 << "handleBMCLogServicesCollectionGet respHandler got error "
2057                 << ec;
2058             // Assume that getting an error simply means there are no dump
2059             // LogServices. Return without adding any error response.
2060             return;
2061         }
2062 
2063         nlohmann::json& logServiceArrayLocal =
2064             asyncResp->res.jsonValue["Members"];
2065 
2066         for (const std::string& path : subTreePaths)
2067         {
2068             if (path == "/xyz/openbmc_project/dump/bmc")
2069             {
2070                 logServiceArrayLocal.push_back(
2071                     {{"@odata.id",
2072                       "/redfish/v1/Managers/bmc/LogServices/Dump"}});
2073             }
2074             else if (path == "/xyz/openbmc_project/dump/faultlog")
2075             {
2076                 logServiceArrayLocal.push_back(
2077                     {{"@odata.id",
2078                       "/redfish/v1/Managers/bmc/LogServices/FaultLog"}});
2079             }
2080         }
2081 
2082         asyncResp->res.jsonValue["Members@odata.count"] =
2083             logServiceArrayLocal.size();
2084     };
2085 
2086     crow::connections::systemBus->async_method_call(
2087         respHandler, "xyz.openbmc_project.ObjectMapper",
2088         "/xyz/openbmc_project/object_mapper",
2089         "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
2090         "/xyz/openbmc_project/dump", 0,
2091         std::array<const char*, 1>{dumpManagerIface});
2092 #endif
2093 }
2094 
2095 inline void requestRoutesBMCLogServiceCollection(App& app)
2096 {
2097     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/")
2098         .privileges(redfish::privileges::getLogServiceCollection)
2099         .methods(boost::beast::http::verb::get)(
2100             std::bind_front(handleBMCLogServicesCollectionGet, std::ref(app)));
2101 }
2102 
2103 inline void requestRoutesBMCJournalLogService(App& app)
2104 {
2105     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/")
2106         .privileges(redfish::privileges::getLogService)
2107         .methods(boost::beast::http::verb::get)(
2108             [&app](const crow::Request& req,
2109                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2110         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2111         {
2112             return;
2113         }
2114         asyncResp->res.jsonValue["@odata.type"] =
2115             "#LogService.v1_1_0.LogService";
2116         asyncResp->res.jsonValue["@odata.id"] =
2117             "/redfish/v1/Managers/bmc/LogServices/Journal";
2118         asyncResp->res.jsonValue["Name"] = "Open BMC Journal Log Service";
2119         asyncResp->res.jsonValue["Description"] = "BMC Journal Log Service";
2120         asyncResp->res.jsonValue["Id"] = "BMC Journal";
2121         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2122 
2123         std::pair<std::string, std::string> redfishDateTimeOffset =
2124             redfish::time_utils::getDateTimeOffsetNow();
2125         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2126         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2127             redfishDateTimeOffset.second;
2128 
2129         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2130             "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2131         });
2132 }
2133 
2134 static int
2135     fillBMCJournalLogEntryJson(const std::string& bmcJournalLogEntryID,
2136                                sd_journal* journal,
2137                                nlohmann::json::object_t& bmcJournalLogEntryJson)
2138 {
2139     // Get the Log Entry contents
2140     int ret = 0;
2141 
2142     std::string message;
2143     std::string_view syslogID;
2144     ret = getJournalMetadata(journal, "SYSLOG_IDENTIFIER", syslogID);
2145     if (ret < 0)
2146     {
2147         BMCWEB_LOG_ERROR << "Failed to read SYSLOG_IDENTIFIER field: "
2148                          << strerror(-ret);
2149     }
2150     if (!syslogID.empty())
2151     {
2152         message += std::string(syslogID) + ": ";
2153     }
2154 
2155     std::string_view msg;
2156     ret = getJournalMetadata(journal, "MESSAGE", msg);
2157     if (ret < 0)
2158     {
2159         BMCWEB_LOG_ERROR << "Failed to read MESSAGE field: " << strerror(-ret);
2160         return 1;
2161     }
2162     message += std::string(msg);
2163 
2164     // Get the severity from the PRIORITY field
2165     long int severity = 8; // Default to an invalid priority
2166     ret = getJournalMetadata(journal, "PRIORITY", 10, severity);
2167     if (ret < 0)
2168     {
2169         BMCWEB_LOG_ERROR << "Failed to read PRIORITY field: " << strerror(-ret);
2170     }
2171 
2172     // Get the Created time from the timestamp
2173     std::string entryTimeStr;
2174     if (!getEntryTimestamp(journal, entryTimeStr))
2175     {
2176         return 1;
2177     }
2178 
2179     // Fill in the log entry with the gathered data
2180     bmcJournalLogEntryJson["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
2181     bmcJournalLogEntryJson["@odata.id"] =
2182         "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/" +
2183         bmcJournalLogEntryID;
2184     bmcJournalLogEntryJson["Name"] = "BMC Journal Entry";
2185     bmcJournalLogEntryJson["Id"] = bmcJournalLogEntryID;
2186     bmcJournalLogEntryJson["Message"] = std::move(message);
2187     bmcJournalLogEntryJson["EntryType"] = "Oem";
2188     bmcJournalLogEntryJson["Severity"] = severity <= 2   ? "Critical"
2189                                          : severity <= 4 ? "Warning"
2190                                                          : "OK";
2191     bmcJournalLogEntryJson["OemRecordFormat"] = "BMC Journal Entry";
2192     bmcJournalLogEntryJson["Created"] = std::move(entryTimeStr);
2193     return 0;
2194 }
2195 
2196 inline void requestRoutesBMCJournalLogEntryCollection(App& app)
2197 {
2198     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/")
2199         .privileges(redfish::privileges::getLogEntryCollection)
2200         .methods(boost::beast::http::verb::get)(
2201             [&app](const crow::Request& req,
2202                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2203         query_param::QueryCapabilities capabilities = {
2204             .canDelegateTop = true,
2205             .canDelegateSkip = true,
2206         };
2207         query_param::Query delegatedQuery;
2208         if (!redfish::setUpRedfishRouteWithDelegation(
2209                 app, req, asyncResp, delegatedQuery, capabilities))
2210         {
2211             return;
2212         }
2213 
2214         size_t skip = delegatedQuery.skip.value_or(0);
2215         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
2216 
2217         // Collections don't include the static data added by SubRoute
2218         // because it has a duplicate entry for members
2219         asyncResp->res.jsonValue["@odata.type"] =
2220             "#LogEntryCollection.LogEntryCollection";
2221         asyncResp->res.jsonValue["@odata.id"] =
2222             "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2223         asyncResp->res.jsonValue["Name"] = "Open BMC Journal Entries";
2224         asyncResp->res.jsonValue["Description"] =
2225             "Collection of BMC Journal Entries";
2226         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
2227         logEntryArray = nlohmann::json::array();
2228 
2229         // Go through the journal and use the timestamp to create a
2230         // unique ID for each entry
2231         sd_journal* journalTmp = nullptr;
2232         int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2233         if (ret < 0)
2234         {
2235             BMCWEB_LOG_ERROR << "failed to open journal: " << strerror(-ret);
2236             messages::internalError(asyncResp->res);
2237             return;
2238         }
2239         std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2240             journalTmp, sd_journal_close);
2241         journalTmp = nullptr;
2242         uint64_t entryCount = 0;
2243         // Reset the unique ID on the first entry
2244         bool firstEntry = true;
2245         SD_JOURNAL_FOREACH(journal.get())
2246         {
2247             entryCount++;
2248             // Handle paging using skip (number of entries to skip from
2249             // the start) and top (number of entries to display)
2250             if (entryCount <= skip || entryCount > skip + top)
2251             {
2252                 continue;
2253             }
2254 
2255             std::string idStr;
2256             if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2257             {
2258                 continue;
2259             }
2260             firstEntry = false;
2261 
2262             nlohmann::json::object_t bmcJournalLogEntry;
2263             if (fillBMCJournalLogEntryJson(idStr, journal.get(),
2264                                            bmcJournalLogEntry) != 0)
2265             {
2266                 messages::internalError(asyncResp->res);
2267                 return;
2268             }
2269             logEntryArray.push_back(std::move(bmcJournalLogEntry));
2270         }
2271         asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
2272         if (skip + top < entryCount)
2273         {
2274             asyncResp->res.jsonValue["Members@odata.nextLink"] =
2275                 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries?$skip=" +
2276                 std::to_string(skip + top);
2277         }
2278         });
2279 }
2280 
2281 inline void requestRoutesBMCJournalLogEntry(App& app)
2282 {
2283     BMCWEB_ROUTE(app,
2284                  "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/<str>/")
2285         .privileges(redfish::privileges::getLogEntry)
2286         .methods(boost::beast::http::verb::get)(
2287             [&app](const crow::Request& req,
2288                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2289                    const std::string& entryID) {
2290         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2291         {
2292             return;
2293         }
2294         // Convert the unique ID back to a timestamp to find the entry
2295         uint64_t ts = 0;
2296         uint64_t index = 0;
2297         if (!getTimestampFromID(asyncResp, entryID, ts, index))
2298         {
2299             return;
2300         }
2301 
2302         sd_journal* journalTmp = nullptr;
2303         int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2304         if (ret < 0)
2305         {
2306             BMCWEB_LOG_ERROR << "failed to open journal: " << strerror(-ret);
2307             messages::internalError(asyncResp->res);
2308             return;
2309         }
2310         std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2311             journalTmp, sd_journal_close);
2312         journalTmp = nullptr;
2313         // Go to the timestamp in the log and move to the entry at the
2314         // index tracking the unique ID
2315         std::string idStr;
2316         bool firstEntry = true;
2317         ret = sd_journal_seek_realtime_usec(journal.get(), ts);
2318         if (ret < 0)
2319         {
2320             BMCWEB_LOG_ERROR << "failed to seek to an entry in journal"
2321                              << strerror(-ret);
2322             messages::internalError(asyncResp->res);
2323             return;
2324         }
2325         for (uint64_t i = 0; i <= index; i++)
2326         {
2327             sd_journal_next(journal.get());
2328             if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2329             {
2330                 messages::internalError(asyncResp->res);
2331                 return;
2332             }
2333             firstEntry = false;
2334         }
2335         // Confirm that the entry ID matches what was requested
2336         if (idStr != entryID)
2337         {
2338             messages::resourceMissingAtURI(asyncResp->res, req.urlView);
2339             return;
2340         }
2341 
2342         nlohmann::json::object_t bmcJournalLogEntry;
2343         if (fillBMCJournalLogEntryJson(entryID, journal.get(),
2344                                        bmcJournalLogEntry) != 0)
2345         {
2346             messages::internalError(asyncResp->res);
2347             return;
2348         }
2349         asyncResp->res.jsonValue.update(bmcJournalLogEntry);
2350         });
2351 }
2352 
2353 inline void
2354     getDumpServiceInfo(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2355                        const std::string& dumpType)
2356 {
2357     std::string dumpPath;
2358     std::string overWritePolicy;
2359     bool collectDiagnosticDataSupported = false;
2360 
2361     if (dumpType == "BMC")
2362     {
2363         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump";
2364         overWritePolicy = "WrapsWhenFull";
2365         collectDiagnosticDataSupported = true;
2366     }
2367     else if (dumpType == "FaultLog")
2368     {
2369         dumpPath = "/redfish/v1/Managers/bmc/LogServices/FaultLog";
2370         overWritePolicy = "Unknown";
2371         collectDiagnosticDataSupported = false;
2372     }
2373     else if (dumpType == "System")
2374     {
2375         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump";
2376         overWritePolicy = "WrapsWhenFull";
2377         collectDiagnosticDataSupported = true;
2378     }
2379     else
2380     {
2381         BMCWEB_LOG_ERROR << "getDumpServiceInfo() invalid dump type: "
2382                          << dumpType;
2383         messages::internalError(asyncResp->res);
2384         return;
2385     }
2386 
2387     asyncResp->res.jsonValue["@odata.id"] = dumpPath;
2388     asyncResp->res.jsonValue["@odata.type"] = "#LogService.v1_2_0.LogService";
2389     asyncResp->res.jsonValue["Name"] = "Dump LogService";
2390     asyncResp->res.jsonValue["Description"] = dumpType + " Dump LogService";
2391     asyncResp->res.jsonValue["Id"] = std::filesystem::path(dumpPath).filename();
2392     asyncResp->res.jsonValue["OverWritePolicy"] = std::move(overWritePolicy);
2393 
2394     std::pair<std::string, std::string> redfishDateTimeOffset =
2395         redfish::time_utils::getDateTimeOffsetNow();
2396     asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2397     asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2398         redfishDateTimeOffset.second;
2399 
2400     asyncResp->res.jsonValue["Entries"]["@odata.id"] = dumpPath + "/Entries";
2401     asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
2402         dumpPath + "/Actions/LogService.ClearLog";
2403 
2404     if (collectDiagnosticDataSupported)
2405     {
2406         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
2407                                 ["target"] =
2408             dumpPath + "/Actions/LogService.CollectDiagnosticData";
2409     }
2410 }
2411 
2412 inline void handleLogServicesDumpServiceGet(
2413     crow::App& app, const std::string& dumpType, const crow::Request& req,
2414     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2415 {
2416     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2417     {
2418         return;
2419     }
2420     getDumpServiceInfo(asyncResp, dumpType);
2421 }
2422 
2423 inline void handleLogServicesDumpEntriesCollectionGet(
2424     crow::App& app, const std::string& dumpType, const crow::Request& req,
2425     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2426 {
2427     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2428     {
2429         return;
2430     }
2431     getDumpEntryCollection(asyncResp, dumpType);
2432 }
2433 
2434 inline void handleLogServicesDumpEntryGet(
2435     crow::App& app, const std::string& dumpType, const crow::Request& req,
2436     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2437     const std::string& dumpId)
2438 {
2439     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2440     {
2441         return;
2442     }
2443     getDumpEntryById(asyncResp, dumpId, dumpType);
2444 }
2445 
2446 inline void handleLogServicesDumpEntryDelete(
2447     crow::App& app, const std::string& dumpType, const crow::Request& req,
2448     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2449     const std::string& dumpId)
2450 {
2451     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2452     {
2453         return;
2454     }
2455     deleteDumpEntry(asyncResp, dumpId, dumpType);
2456 }
2457 
2458 inline void handleLogServicesDumpCollectDiagnosticDataPost(
2459     crow::App& app, const std::string& dumpType, const crow::Request& req,
2460     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2461 {
2462     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2463     {
2464         return;
2465     }
2466     createDump(asyncResp, req, dumpType);
2467 }
2468 
2469 inline void handleLogServicesDumpClearLogPost(
2470     crow::App& app, const std::string& dumpType, const crow::Request& req,
2471     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2472 {
2473     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2474     {
2475         return;
2476     }
2477     clearDump(asyncResp, dumpType);
2478 }
2479 
2480 inline void requestRoutesBMCDumpService(App& app)
2481 {
2482     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/")
2483         .privileges(redfish::privileges::getLogService)
2484         .methods(boost::beast::http::verb::get)(std::bind_front(
2485             handleLogServicesDumpServiceGet, std::ref(app), "BMC"));
2486 }
2487 
2488 inline void requestRoutesBMCDumpEntryCollection(App& app)
2489 {
2490     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/")
2491         .privileges(redfish::privileges::getLogEntryCollection)
2492         .methods(boost::beast::http::verb::get)(std::bind_front(
2493             handleLogServicesDumpEntriesCollectionGet, std::ref(app), "BMC"));
2494 }
2495 
2496 inline void requestRoutesBMCDumpEntry(App& app)
2497 {
2498     BMCWEB_ROUTE(app,
2499                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2500         .privileges(redfish::privileges::getLogEntry)
2501         .methods(boost::beast::http::verb::get)(std::bind_front(
2502             handleLogServicesDumpEntryGet, std::ref(app), "BMC"));
2503 
2504     BMCWEB_ROUTE(app,
2505                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2506         .privileges(redfish::privileges::deleteLogEntry)
2507         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2508             handleLogServicesDumpEntryDelete, std::ref(app), "BMC"));
2509 }
2510 
2511 inline void requestRoutesBMCDumpCreate(App& app)
2512 {
2513     BMCWEB_ROUTE(
2514         app,
2515         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
2516         .privileges(redfish::privileges::postLogService)
2517         .methods(boost::beast::http::verb::post)(
2518             std::bind_front(handleLogServicesDumpCollectDiagnosticDataPost,
2519                             std::ref(app), "BMC"));
2520 }
2521 
2522 inline void requestRoutesBMCDumpClear(App& app)
2523 {
2524     BMCWEB_ROUTE(
2525         app,
2526         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog/")
2527         .privileges(redfish::privileges::postLogService)
2528         .methods(boost::beast::http::verb::post)(std::bind_front(
2529             handleLogServicesDumpClearLogPost, std::ref(app), "BMC"));
2530 }
2531 
2532 inline void requestRoutesFaultLogDumpService(App& app)
2533 {
2534     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/FaultLog/")
2535         .privileges(redfish::privileges::getLogService)
2536         .methods(boost::beast::http::verb::get)(std::bind_front(
2537             handleLogServicesDumpServiceGet, std::ref(app), "FaultLog"));
2538 }
2539 
2540 inline void requestRoutesFaultLogDumpEntryCollection(App& app)
2541 {
2542     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/")
2543         .privileges(redfish::privileges::getLogEntryCollection)
2544         .methods(boost::beast::http::verb::get)(
2545             std::bind_front(handleLogServicesDumpEntriesCollectionGet,
2546                             std::ref(app), "FaultLog"));
2547 }
2548 
2549 inline void requestRoutesFaultLogDumpEntry(App& app)
2550 {
2551     BMCWEB_ROUTE(app,
2552                  "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/<str>/")
2553         .privileges(redfish::privileges::getLogEntry)
2554         .methods(boost::beast::http::verb::get)(std::bind_front(
2555             handleLogServicesDumpEntryGet, std::ref(app), "FaultLog"));
2556 
2557     BMCWEB_ROUTE(app,
2558                  "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/<str>/")
2559         .privileges(redfish::privileges::deleteLogEntry)
2560         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2561             handleLogServicesDumpEntryDelete, std::ref(app), "FaultLog"));
2562 }
2563 
2564 inline void requestRoutesFaultLogDumpClear(App& app)
2565 {
2566     BMCWEB_ROUTE(
2567         app,
2568         "/redfish/v1/Managers/bmc/LogServices/FaultLog/Actions/LogService.ClearLog/")
2569         .privileges(redfish::privileges::postLogService)
2570         .methods(boost::beast::http::verb::post)(std::bind_front(
2571             handleLogServicesDumpClearLogPost, std::ref(app), "FaultLog"));
2572 }
2573 
2574 inline void requestRoutesSystemDumpService(App& app)
2575 {
2576     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Dump/")
2577         .privileges(redfish::privileges::getLogService)
2578         .methods(boost::beast::http::verb::get)(
2579             [&app](const crow::Request& req,
2580                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2581         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2582         {
2583             return;
2584         }
2585         asyncResp->res.jsonValue["@odata.id"] =
2586             "/redfish/v1/Systems/system/LogServices/Dump";
2587         asyncResp->res.jsonValue["@odata.type"] =
2588             "#LogService.v1_2_0.LogService";
2589         asyncResp->res.jsonValue["Name"] = "Dump LogService";
2590         asyncResp->res.jsonValue["Description"] = "System Dump LogService";
2591         asyncResp->res.jsonValue["Id"] = "Dump";
2592         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2593 
2594         std::pair<std::string, std::string> redfishDateTimeOffset =
2595             redfish::time_utils::getDateTimeOffsetNow();
2596         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2597         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2598             redfishDateTimeOffset.second;
2599 
2600         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2601             "/redfish/v1/Systems/system/LogServices/Dump/Entries";
2602         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
2603             "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.ClearLog";
2604 
2605         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
2606                                 ["target"] =
2607             "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.CollectDiagnosticData";
2608         });
2609 }
2610 
2611 inline void requestRoutesSystemDumpEntryCollection(App& app)
2612 {
2613 
2614     /**
2615      * Functions triggers appropriate requests on DBus
2616      */
2617     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Dump/Entries/")
2618         .privileges(redfish::privileges::getLogEntryCollection)
2619         .methods(boost::beast::http::verb::get)(
2620             [&app](const crow::Request& req,
2621                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2622         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2623         {
2624             return;
2625         }
2626         getDumpEntryCollection(asyncResp, "System");
2627         });
2628 }
2629 
2630 inline void requestRoutesSystemDumpEntry(App& app)
2631 {
2632     BMCWEB_ROUTE(app,
2633                  "/redfish/v1/Systems/system/LogServices/Dump/Entries/<str>/")
2634         .privileges(redfish::privileges::getLogEntry)
2635 
2636         .methods(boost::beast::http::verb::get)(
2637             [&app](const crow::Request& req,
2638                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2639                    const std::string& param) {
2640         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2641         {
2642             return;
2643         }
2644         getDumpEntryById(asyncResp, param, "System");
2645         });
2646 
2647     BMCWEB_ROUTE(app,
2648                  "/redfish/v1/Systems/system/LogServices/Dump/Entries/<str>/")
2649         .privileges(redfish::privileges::deleteLogEntry)
2650         .methods(boost::beast::http::verb::delete_)(
2651             [&app](const crow::Request& req,
2652                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2653                    const std::string& param) {
2654         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2655         {
2656             return;
2657         }
2658         deleteDumpEntry(asyncResp, param, "system");
2659         });
2660 }
2661 
2662 inline void requestRoutesSystemDumpCreate(App& app)
2663 {
2664     BMCWEB_ROUTE(
2665         app,
2666         "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
2667         .privileges(redfish::privileges::postLogService)
2668         .methods(boost::beast::http::verb::post)(
2669             [&app](const crow::Request& req,
2670                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2671         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2672         {
2673             return;
2674         }
2675         createDump(asyncResp, req, "System");
2676         });
2677 }
2678 
2679 inline void requestRoutesSystemDumpClear(App& app)
2680 {
2681     BMCWEB_ROUTE(
2682         app,
2683         "/redfish/v1/Systems/system/LogServices/Dump/Actions/LogService.ClearLog/")
2684         .privileges(redfish::privileges::postLogService)
2685         .methods(boost::beast::http::verb::post)(
2686             [&app](const crow::Request& req,
2687                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2688 
2689             {
2690         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2691         {
2692             return;
2693         }
2694         clearDump(asyncResp, "System");
2695         });
2696 }
2697 
2698 inline void requestRoutesCrashdumpService(App& app)
2699 {
2700     // Note: Deviated from redfish privilege registry for GET & HEAD
2701     // method for security reasons.
2702     /**
2703      * Functions triggers appropriate requests on DBus
2704      */
2705     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/Crashdump/")
2706         // This is incorrect, should be:
2707         //.privileges(redfish::privileges::getLogService)
2708         .privileges({{"ConfigureManager"}})
2709         .methods(boost::beast::http::verb::get)(
2710             [&app](const crow::Request& req,
2711                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2712         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2713         {
2714             return;
2715         }
2716         // Copy over the static data to include the entries added by
2717         // SubRoute
2718         asyncResp->res.jsonValue["@odata.id"] =
2719             "/redfish/v1/Systems/system/LogServices/Crashdump";
2720         asyncResp->res.jsonValue["@odata.type"] =
2721             "#LogService.v1_2_0.LogService";
2722         asyncResp->res.jsonValue["Name"] = "Open BMC Oem Crashdump Service";
2723         asyncResp->res.jsonValue["Description"] = "Oem Crashdump Service";
2724         asyncResp->res.jsonValue["Id"] = "Oem Crashdump";
2725         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2726         asyncResp->res.jsonValue["MaxNumberOfRecords"] = 3;
2727 
2728         std::pair<std::string, std::string> redfishDateTimeOffset =
2729             redfish::time_utils::getDateTimeOffsetNow();
2730         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2731         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2732             redfishDateTimeOffset.second;
2733 
2734         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2735             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries";
2736         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
2737             "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog";
2738         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
2739                                 ["target"] =
2740             "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData";
2741         });
2742 }
2743 
2744 void inline requestRoutesCrashdumpClear(App& app)
2745 {
2746     BMCWEB_ROUTE(
2747         app,
2748         "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog/")
2749         // This is incorrect, should be:
2750         //.privileges(redfish::privileges::postLogService)
2751         .privileges({{"ConfigureComponents"}})
2752         .methods(boost::beast::http::verb::post)(
2753             [&app](const crow::Request& req,
2754                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2755         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2756         {
2757             return;
2758         }
2759         crow::connections::systemBus->async_method_call(
2760             [asyncResp](const boost::system::error_code ec,
2761                         const std::string&) {
2762             if (ec)
2763             {
2764                 messages::internalError(asyncResp->res);
2765                 return;
2766             }
2767             messages::success(asyncResp->res);
2768             },
2769             crashdumpObject, crashdumpPath, deleteAllInterface, "DeleteAll");
2770         });
2771 }
2772 
2773 static void
2774     logCrashdumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2775                       const std::string& logID, nlohmann::json& logEntryJson)
2776 {
2777     auto getStoredLogCallback =
2778         [asyncResp, logID,
2779          &logEntryJson](const boost::system::error_code ec,
2780                         const dbus::utility::DBusPropertiesMap& params) {
2781         if (ec)
2782         {
2783             BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
2784             if (ec.value() ==
2785                 boost::system::linux_error::bad_request_descriptor)
2786             {
2787                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
2788             }
2789             else
2790             {
2791                 messages::internalError(asyncResp->res);
2792             }
2793             return;
2794         }
2795 
2796         std::string timestamp{};
2797         std::string filename{};
2798         std::string logfile{};
2799         parseCrashdumpParameters(params, filename, timestamp, logfile);
2800 
2801         if (filename.empty() || timestamp.empty())
2802         {
2803             messages::resourceMissingAtURI(asyncResp->res,
2804                                            crow::utility::urlFromPieces(logID));
2805             return;
2806         }
2807 
2808         std::string crashdumpURI =
2809             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" +
2810             logID + "/" + filename;
2811         nlohmann::json::object_t logEntry;
2812         logEntry["@odata.type"] = "#LogEntry.v1_7_0.LogEntry";
2813         logEntry["@odata.id"] =
2814             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" + logID;
2815         logEntry["Name"] = "CPU Crashdump";
2816         logEntry["Id"] = logID;
2817         logEntry["EntryType"] = "Oem";
2818         logEntry["AdditionalDataURI"] = std::move(crashdumpURI);
2819         logEntry["DiagnosticDataType"] = "OEM";
2820         logEntry["OEMDiagnosticDataType"] = "PECICrashdump";
2821         logEntry["Created"] = std::move(timestamp);
2822 
2823         // If logEntryJson references an array of LogEntry resources
2824         // ('Members' list), then push this as a new entry, otherwise set it
2825         // directly
2826         if (logEntryJson.is_array())
2827         {
2828             logEntryJson.push_back(logEntry);
2829             asyncResp->res.jsonValue["Members@odata.count"] =
2830                 logEntryJson.size();
2831         }
2832         else
2833         {
2834             logEntryJson.update(logEntry);
2835         }
2836     };
2837     crow::connections::systemBus->async_method_call(
2838         std::move(getStoredLogCallback), crashdumpObject,
2839         crashdumpPath + std::string("/") + logID,
2840         "org.freedesktop.DBus.Properties", "GetAll", crashdumpInterface);
2841 }
2842 
2843 inline void requestRoutesCrashdumpEntryCollection(App& app)
2844 {
2845     // Note: Deviated from redfish privilege registry for GET & HEAD
2846     // method for security reasons.
2847     /**
2848      * Functions triggers appropriate requests on DBus
2849      */
2850     BMCWEB_ROUTE(app,
2851                  "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/")
2852         // This is incorrect, should be.
2853         //.privileges(redfish::privileges::postLogEntryCollection)
2854         .privileges({{"ConfigureComponents"}})
2855         .methods(boost::beast::http::verb::get)(
2856             [&app](const crow::Request& req,
2857                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2858         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2859         {
2860             return;
2861         }
2862         crow::connections::systemBus->async_method_call(
2863             [asyncResp](const boost::system::error_code ec,
2864                         const std::vector<std::string>& resp) {
2865             if (ec)
2866             {
2867                 if (ec.value() !=
2868                     boost::system::errc::no_such_file_or_directory)
2869                 {
2870                     BMCWEB_LOG_DEBUG << "failed to get entries ec: "
2871                                      << ec.message();
2872                     messages::internalError(asyncResp->res);
2873                     return;
2874                 }
2875             }
2876             asyncResp->res.jsonValue["@odata.type"] =
2877                 "#LogEntryCollection.LogEntryCollection";
2878             asyncResp->res.jsonValue["@odata.id"] =
2879                 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries";
2880             asyncResp->res.jsonValue["Name"] = "Open BMC Crashdump Entries";
2881             asyncResp->res.jsonValue["Description"] =
2882                 "Collection of Crashdump Entries";
2883             asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
2884             asyncResp->res.jsonValue["Members@odata.count"] = 0;
2885 
2886             for (const std::string& path : resp)
2887             {
2888                 const sdbusplus::message::object_path objPath(path);
2889                 // Get the log ID
2890                 std::string logID = objPath.filename();
2891                 if (logID.empty())
2892                 {
2893                     continue;
2894                 }
2895                 // Add the log entry to the array
2896                 logCrashdumpEntry(asyncResp, logID,
2897                                   asyncResp->res.jsonValue["Members"]);
2898             }
2899             },
2900             "xyz.openbmc_project.ObjectMapper",
2901             "/xyz/openbmc_project/object_mapper",
2902             "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", "", 0,
2903             std::array<const char*, 1>{crashdumpInterface});
2904         });
2905 }
2906 
2907 inline void requestRoutesCrashdumpEntry(App& app)
2908 {
2909     // Note: Deviated from redfish privilege registry for GET & HEAD
2910     // method for security reasons.
2911 
2912     BMCWEB_ROUTE(
2913         app, "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/<str>/")
2914         // this is incorrect, should be
2915         // .privileges(redfish::privileges::getLogEntry)
2916         .privileges({{"ConfigureComponents"}})
2917         .methods(boost::beast::http::verb::get)(
2918             [&app](const crow::Request& req,
2919                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2920                    const std::string& param) {
2921         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2922         {
2923             return;
2924         }
2925         const std::string& logID = param;
2926         logCrashdumpEntry(asyncResp, logID, asyncResp->res.jsonValue);
2927         });
2928 }
2929 
2930 inline void requestRoutesCrashdumpFile(App& app)
2931 {
2932     // Note: Deviated from redfish privilege registry for GET & HEAD
2933     // method for security reasons.
2934     BMCWEB_ROUTE(
2935         app,
2936         "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/<str>/<str>/")
2937         .privileges(redfish::privileges::getLogEntry)
2938         .methods(boost::beast::http::verb::get)(
2939             [](const crow::Request& req,
2940                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2941                const std::string& logID, const std::string& fileName) {
2942         // Do not call getRedfishRoute here since the crashdump file is not a
2943         // Redfish resource.
2944         auto getStoredLogCallback =
2945             [asyncResp, logID, fileName, url(boost::urls::url(req.urlView))](
2946                 const boost::system::error_code ec,
2947                 const std::vector<
2948                     std::pair<std::string, dbus::utility::DbusVariantType>>&
2949                     resp) {
2950             if (ec)
2951             {
2952                 BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
2953                 messages::internalError(asyncResp->res);
2954                 return;
2955             }
2956 
2957             std::string dbusFilename{};
2958             std::string dbusTimestamp{};
2959             std::string dbusFilepath{};
2960 
2961             parseCrashdumpParameters(resp, dbusFilename, dbusTimestamp,
2962                                      dbusFilepath);
2963 
2964             if (dbusFilename.empty() || dbusTimestamp.empty() ||
2965                 dbusFilepath.empty())
2966             {
2967                 messages::resourceMissingAtURI(asyncResp->res, url);
2968                 return;
2969             }
2970 
2971             // Verify the file name parameter is correct
2972             if (fileName != dbusFilename)
2973             {
2974                 messages::resourceMissingAtURI(asyncResp->res, url);
2975                 return;
2976             }
2977 
2978             if (!std::filesystem::exists(dbusFilepath))
2979             {
2980                 messages::resourceMissingAtURI(asyncResp->res, url);
2981                 return;
2982             }
2983             std::ifstream ifs(dbusFilepath, std::ios::in | std::ios::binary);
2984             asyncResp->res.body() =
2985                 std::string(std::istreambuf_iterator<char>{ifs}, {});
2986 
2987             // Configure this to be a file download when accessed
2988             // from a browser
2989             asyncResp->res.addHeader(
2990                 boost::beast::http::field::content_disposition, "attachment");
2991         };
2992         crow::connections::systemBus->async_method_call(
2993             std::move(getStoredLogCallback), crashdumpObject,
2994             crashdumpPath + std::string("/") + logID,
2995             "org.freedesktop.DBus.Properties", "GetAll", crashdumpInterface);
2996         });
2997 }
2998 
2999 enum class OEMDiagnosticType
3000 {
3001     onDemand,
3002     telemetry,
3003     invalid,
3004 };
3005 
3006 inline OEMDiagnosticType
3007     getOEMDiagnosticType(const std::string_view& oemDiagStr)
3008 {
3009     if (oemDiagStr == "OnDemand")
3010     {
3011         return OEMDiagnosticType::onDemand;
3012     }
3013     if (oemDiagStr == "Telemetry")
3014     {
3015         return OEMDiagnosticType::telemetry;
3016     }
3017 
3018     return OEMDiagnosticType::invalid;
3019 }
3020 
3021 inline void requestRoutesCrashdumpCollect(App& app)
3022 {
3023     // Note: Deviated from redfish privilege registry for GET & HEAD
3024     // method for security reasons.
3025     BMCWEB_ROUTE(
3026         app,
3027         "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData/")
3028         // The below is incorrect;  Should be ConfigureManager
3029         //.privileges(redfish::privileges::postLogService)
3030         .privileges({{"ConfigureComponents"}})
3031         .methods(boost::beast::http::verb::post)(
3032             [&app](const crow::Request& req,
3033                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3034         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3035         {
3036             return;
3037         }
3038         std::string diagnosticDataType;
3039         std::string oemDiagnosticDataType;
3040         if (!redfish::json_util::readJsonAction(
3041                 req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
3042                 "OEMDiagnosticDataType", oemDiagnosticDataType))
3043         {
3044             return;
3045         }
3046 
3047         if (diagnosticDataType != "OEM")
3048         {
3049             BMCWEB_LOG_ERROR
3050                 << "Only OEM DiagnosticDataType supported for Crashdump";
3051             messages::actionParameterValueFormatError(
3052                 asyncResp->res, diagnosticDataType, "DiagnosticDataType",
3053                 "CollectDiagnosticData");
3054             return;
3055         }
3056 
3057         OEMDiagnosticType oemDiagType =
3058             getOEMDiagnosticType(oemDiagnosticDataType);
3059 
3060         std::string iface;
3061         std::string method;
3062         std::string taskMatchStr;
3063         if (oemDiagType == OEMDiagnosticType::onDemand)
3064         {
3065             iface = crashdumpOnDemandInterface;
3066             method = "GenerateOnDemandLog";
3067             taskMatchStr = "type='signal',"
3068                            "interface='org.freedesktop.DBus.Properties',"
3069                            "member='PropertiesChanged',"
3070                            "arg0namespace='com.intel.crashdump'";
3071         }
3072         else if (oemDiagType == OEMDiagnosticType::telemetry)
3073         {
3074             iface = crashdumpTelemetryInterface;
3075             method = "GenerateTelemetryLog";
3076             taskMatchStr = "type='signal',"
3077                            "interface='org.freedesktop.DBus.Properties',"
3078                            "member='PropertiesChanged',"
3079                            "arg0namespace='com.intel.crashdump'";
3080         }
3081         else
3082         {
3083             BMCWEB_LOG_ERROR << "Unsupported OEMDiagnosticDataType: "
3084                              << oemDiagnosticDataType;
3085             messages::actionParameterValueFormatError(
3086                 asyncResp->res, oemDiagnosticDataType, "OEMDiagnosticDataType",
3087                 "CollectDiagnosticData");
3088             return;
3089         }
3090 
3091         auto collectCrashdumpCallback =
3092             [asyncResp, payload(task::Payload(req)),
3093              taskMatchStr](const boost::system::error_code ec,
3094                            const std::string&) mutable {
3095             if (ec)
3096             {
3097                 if (ec.value() == boost::system::errc::operation_not_supported)
3098                 {
3099                     messages::resourceInStandby(asyncResp->res);
3100                 }
3101                 else if (ec.value() ==
3102                          boost::system::errc::device_or_resource_busy)
3103                 {
3104                     messages::serviceTemporarilyUnavailable(asyncResp->res,
3105                                                             "60");
3106                 }
3107                 else
3108                 {
3109                     messages::internalError(asyncResp->res);
3110                 }
3111                 return;
3112             }
3113             std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
3114                 [](boost::system::error_code err, sdbusplus::message_t&,
3115                    const std::shared_ptr<task::TaskData>& taskData) {
3116                 if (!err)
3117                 {
3118                     taskData->messages.emplace_back(messages::taskCompletedOK(
3119                         std::to_string(taskData->index)));
3120                     taskData->state = "Completed";
3121                 }
3122                 return task::completed;
3123                 },
3124                 taskMatchStr);
3125 
3126             task->startTimer(std::chrono::minutes(5));
3127             task->populateResp(asyncResp->res);
3128             task->payload.emplace(std::move(payload));
3129         };
3130 
3131         crow::connections::systemBus->async_method_call(
3132             std::move(collectCrashdumpCallback), crashdumpObject, crashdumpPath,
3133             iface, method);
3134         });
3135 }
3136 
3137 /**
3138  * DBusLogServiceActionsClear class supports POST method for ClearLog action.
3139  */
3140 inline void requestRoutesDBusLogServiceActionsClear(App& app)
3141 {
3142     /**
3143      * Function handles POST method request.
3144      * The Clear Log actions does not require any parameter.The action deletes
3145      * all entries found in the Entries collection for this Log Service.
3146      */
3147 
3148     BMCWEB_ROUTE(
3149         app,
3150         "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog/")
3151         .privileges(redfish::privileges::postLogService)
3152         .methods(boost::beast::http::verb::post)(
3153             [&app](const crow::Request& req,
3154                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3155         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3156         {
3157             return;
3158         }
3159         BMCWEB_LOG_DEBUG << "Do delete all entries.";
3160 
3161         // Process response from Logging service.
3162         auto respHandler = [asyncResp](const boost::system::error_code ec) {
3163             BMCWEB_LOG_DEBUG << "doClearLog resp_handler callback: Done";
3164             if (ec)
3165             {
3166                 // TODO Handle for specific error code
3167                 BMCWEB_LOG_ERROR << "doClearLog resp_handler got error " << ec;
3168                 asyncResp->res.result(
3169                     boost::beast::http::status::internal_server_error);
3170                 return;
3171             }
3172 
3173             asyncResp->res.result(boost::beast::http::status::no_content);
3174         };
3175 
3176         // Make call to Logging service to request Clear Log
3177         crow::connections::systemBus->async_method_call(
3178             respHandler, "xyz.openbmc_project.Logging",
3179             "/xyz/openbmc_project/logging",
3180             "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3181         });
3182 }
3183 
3184 /****************************************************
3185  * Redfish PostCode interfaces
3186  * using DBUS interface: getPostCodesTS
3187  ******************************************************/
3188 inline void requestRoutesPostCodesLogService(App& app)
3189 {
3190     BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/LogServices/PostCodes/")
3191         .privileges(redfish::privileges::getLogService)
3192         .methods(boost::beast::http::verb::get)(
3193             [&app](const crow::Request& req,
3194                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3195         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3196         {
3197             return;
3198         }
3199 
3200         asyncResp->res.jsonValue["@odata.id"] =
3201             "/redfish/v1/Systems/system/LogServices/PostCodes";
3202         asyncResp->res.jsonValue["@odata.type"] =
3203             "#LogService.v1_1_0.LogService";
3204         asyncResp->res.jsonValue["Name"] = "POST Code Log Service";
3205         asyncResp->res.jsonValue["Description"] = "POST Code Log Service";
3206         asyncResp->res.jsonValue["Id"] = "BIOS POST Code Log";
3207         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
3208         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
3209             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3210 
3211         std::pair<std::string, std::string> redfishDateTimeOffset =
3212             redfish::time_utils::getDateTimeOffsetNow();
3213         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
3214         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
3215             redfishDateTimeOffset.second;
3216 
3217         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
3218             {"target",
3219              "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog"}};
3220         });
3221 }
3222 
3223 inline void requestRoutesPostCodesClear(App& app)
3224 {
3225     BMCWEB_ROUTE(
3226         app,
3227         "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog/")
3228         // The following privilege is incorrect;  It should be ConfigureManager
3229         //.privileges(redfish::privileges::postLogService)
3230         .privileges({{"ConfigureComponents"}})
3231         .methods(boost::beast::http::verb::post)(
3232             [&app](const crow::Request& req,
3233                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3234         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3235         {
3236             return;
3237         }
3238         BMCWEB_LOG_DEBUG << "Do delete all postcodes entries.";
3239 
3240         // Make call to post-code service to request clear all
3241         crow::connections::systemBus->async_method_call(
3242             [asyncResp](const boost::system::error_code ec) {
3243             if (ec)
3244             {
3245                 // TODO Handle for specific error code
3246                 BMCWEB_LOG_ERROR << "doClearPostCodes resp_handler got error "
3247                                  << ec;
3248                 asyncResp->res.result(
3249                     boost::beast::http::status::internal_server_error);
3250                 messages::internalError(asyncResp->res);
3251                 return;
3252             }
3253             },
3254             "xyz.openbmc_project.State.Boot.PostCode0",
3255             "/xyz/openbmc_project/State/Boot/PostCode0",
3256             "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3257         });
3258 }
3259 
3260 static void fillPostCodeEntry(
3261     const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3262     const boost::container::flat_map<
3263         uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& postcode,
3264     const uint16_t bootIndex, const uint64_t codeIndex = 0,
3265     const uint64_t skip = 0, const uint64_t top = 0)
3266 {
3267     // Get the Message from the MessageRegistry
3268     const registries::Message* message =
3269         registries::getMessage("OpenBMC.0.2.BIOSPOSTCode");
3270 
3271     uint64_t currentCodeIndex = 0;
3272     nlohmann::json& logEntryArray = aResp->res.jsonValue["Members"];
3273 
3274     uint64_t firstCodeTimeUs = 0;
3275     for (const std::pair<uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3276              code : postcode)
3277     {
3278         currentCodeIndex++;
3279         std::string postcodeEntryID =
3280             "B" + std::to_string(bootIndex) + "-" +
3281             std::to_string(currentCodeIndex); // 1 based index in EntryID string
3282 
3283         uint64_t usecSinceEpoch = code.first;
3284         uint64_t usTimeOffset = 0;
3285 
3286         if (1 == currentCodeIndex)
3287         { // already incremented
3288             firstCodeTimeUs = code.first;
3289         }
3290         else
3291         {
3292             usTimeOffset = code.first - firstCodeTimeUs;
3293         }
3294 
3295         // skip if no specific codeIndex is specified and currentCodeIndex does
3296         // not fall between top and skip
3297         if ((codeIndex == 0) &&
3298             (currentCodeIndex <= skip || currentCodeIndex > top))
3299         {
3300             continue;
3301         }
3302 
3303         // skip if a specific codeIndex is specified and does not match the
3304         // currentIndex
3305         if ((codeIndex > 0) && (currentCodeIndex != codeIndex))
3306         {
3307             // This is done for simplicity. 1st entry is needed to calculate
3308             // time offset. To improve efficiency, one can get to the entry
3309             // directly (possibly with flatmap's nth method)
3310             continue;
3311         }
3312 
3313         // currentCodeIndex is within top and skip or equal to specified code
3314         // index
3315 
3316         // Get the Created time from the timestamp
3317         std::string entryTimeStr;
3318         entryTimeStr =
3319             redfish::time_utils::getDateTimeUint(usecSinceEpoch / 1000 / 1000);
3320 
3321         // assemble messageArgs: BootIndex, TimeOffset(100us), PostCode(hex)
3322         std::ostringstream hexCode;
3323         hexCode << "0x" << std::setfill('0') << std::setw(2) << std::hex
3324                 << std::get<0>(code.second);
3325         std::ostringstream timeOffsetStr;
3326         // Set Fixed -Point Notation
3327         timeOffsetStr << std::fixed;
3328         // Set precision to 4 digits
3329         timeOffsetStr << std::setprecision(4);
3330         // Add double to stream
3331         timeOffsetStr << static_cast<double>(usTimeOffset) / 1000 / 1000;
3332         std::vector<std::string> messageArgs = {
3333             std::to_string(bootIndex), timeOffsetStr.str(), hexCode.str()};
3334 
3335         // Get MessageArgs template from message registry
3336         std::string msg;
3337         if (message != nullptr)
3338         {
3339             msg = message->message;
3340 
3341             // fill in this post code value
3342             int i = 0;
3343             for (const std::string& messageArg : messageArgs)
3344             {
3345                 std::string argStr = "%" + std::to_string(++i);
3346                 size_t argPos = msg.find(argStr);
3347                 if (argPos != std::string::npos)
3348                 {
3349                     msg.replace(argPos, argStr.length(), messageArg);
3350                 }
3351             }
3352         }
3353 
3354         // Get Severity template from message registry
3355         std::string severity;
3356         if (message != nullptr)
3357         {
3358             severity = message->messageSeverity;
3359         }
3360 
3361         // add to AsyncResp
3362         logEntryArray.push_back({});
3363         nlohmann::json& bmcLogEntry = logEntryArray.back();
3364         bmcLogEntry["@odata.type"] = "#LogEntry.v1_8_0.LogEntry";
3365         bmcLogEntry["@odata.id"] =
3366             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" +
3367             postcodeEntryID;
3368         bmcLogEntry["Name"] = "POST Code Log Entry";
3369         bmcLogEntry["Id"] = postcodeEntryID;
3370         bmcLogEntry["Message"] = std::move(msg);
3371         bmcLogEntry["MessageId"] = "OpenBMC.0.2.BIOSPOSTCode";
3372         bmcLogEntry["MessageArgs"] = std::move(messageArgs);
3373         bmcLogEntry["EntryType"] = "Event";
3374         bmcLogEntry["Severity"] = std::move(severity);
3375         bmcLogEntry["Created"] = entryTimeStr;
3376         if (!std::get<std::vector<uint8_t>>(code.second).empty())
3377         {
3378             bmcLogEntry["AdditionalDataURI"] =
3379                 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" +
3380                 postcodeEntryID + "/attachment";
3381         }
3382     }
3383 }
3384 
3385 static void getPostCodeForEntry(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3386                                 const uint16_t bootIndex,
3387                                 const uint64_t codeIndex)
3388 {
3389     crow::connections::systemBus->async_method_call(
3390         [aResp, bootIndex,
3391          codeIndex](const boost::system::error_code ec,
3392                     const boost::container::flat_map<
3393                         uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3394                         postcode) {
3395         if (ec)
3396         {
3397             BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error";
3398             messages::internalError(aResp->res);
3399             return;
3400         }
3401 
3402         // skip the empty postcode boots
3403         if (postcode.empty())
3404         {
3405             return;
3406         }
3407 
3408         fillPostCodeEntry(aResp, postcode, bootIndex, codeIndex);
3409 
3410         aResp->res.jsonValue["Members@odata.count"] =
3411             aResp->res.jsonValue["Members"].size();
3412         },
3413         "xyz.openbmc_project.State.Boot.PostCode0",
3414         "/xyz/openbmc_project/State/Boot/PostCode0",
3415         "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp",
3416         bootIndex);
3417 }
3418 
3419 static void getPostCodeForBoot(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3420                                const uint16_t bootIndex,
3421                                const uint16_t bootCount,
3422                                const uint64_t entryCount, size_t skip,
3423                                size_t top)
3424 {
3425     crow::connections::systemBus->async_method_call(
3426         [aResp, bootIndex, bootCount, entryCount, skip,
3427          top](const boost::system::error_code ec,
3428               const boost::container::flat_map<
3429                   uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3430                   postcode) {
3431         if (ec)
3432         {
3433             BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error";
3434             messages::internalError(aResp->res);
3435             return;
3436         }
3437 
3438         uint64_t endCount = entryCount;
3439         if (!postcode.empty())
3440         {
3441             endCount = entryCount + postcode.size();
3442             if (skip < endCount && (top + skip) > entryCount)
3443             {
3444                 uint64_t thisBootSkip =
3445                     std::max(static_cast<uint64_t>(skip), entryCount) -
3446                     entryCount;
3447                 uint64_t thisBootTop =
3448                     std::min(static_cast<uint64_t>(top + skip), endCount) -
3449                     entryCount;
3450 
3451                 fillPostCodeEntry(aResp, postcode, bootIndex, 0, thisBootSkip,
3452                                   thisBootTop);
3453             }
3454             aResp->res.jsonValue["Members@odata.count"] = endCount;
3455         }
3456 
3457         // continue to previous bootIndex
3458         if (bootIndex < bootCount)
3459         {
3460             getPostCodeForBoot(aResp, static_cast<uint16_t>(bootIndex + 1),
3461                                bootCount, endCount, skip, top);
3462         }
3463         else if (skip + top < endCount)
3464         {
3465             aResp->res.jsonValue["Members@odata.nextLink"] =
3466                 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries?$skip=" +
3467                 std::to_string(skip + top);
3468         }
3469         },
3470         "xyz.openbmc_project.State.Boot.PostCode0",
3471         "/xyz/openbmc_project/State/Boot/PostCode0",
3472         "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp",
3473         bootIndex);
3474 }
3475 
3476 static void
3477     getCurrentBootNumber(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3478                          size_t skip, size_t top)
3479 {
3480     uint64_t entryCount = 0;
3481     sdbusplus::asio::getProperty<uint16_t>(
3482         *crow::connections::systemBus,
3483         "xyz.openbmc_project.State.Boot.PostCode0",
3484         "/xyz/openbmc_project/State/Boot/PostCode0",
3485         "xyz.openbmc_project.State.Boot.PostCode", "CurrentBootCycleCount",
3486         [aResp, entryCount, skip, top](const boost::system::error_code ec,
3487                                        const uint16_t bootCount) {
3488         if (ec)
3489         {
3490             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
3491             messages::internalError(aResp->res);
3492             return;
3493         }
3494         getPostCodeForBoot(aResp, 1, bootCount, entryCount, skip, top);
3495         });
3496 }
3497 
3498 inline void requestRoutesPostCodesEntryCollection(App& app)
3499 {
3500     BMCWEB_ROUTE(app,
3501                  "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/")
3502         .privileges(redfish::privileges::getLogEntryCollection)
3503         .methods(boost::beast::http::verb::get)(
3504             [&app](const crow::Request& req,
3505                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
3506         query_param::QueryCapabilities capabilities = {
3507             .canDelegateTop = true,
3508             .canDelegateSkip = true,
3509         };
3510         query_param::Query delegatedQuery;
3511         if (!redfish::setUpRedfishRouteWithDelegation(
3512                 app, req, asyncResp, delegatedQuery, capabilities))
3513         {
3514             return;
3515         }
3516         asyncResp->res.jsonValue["@odata.type"] =
3517             "#LogEntryCollection.LogEntryCollection";
3518         asyncResp->res.jsonValue["@odata.id"] =
3519             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3520         asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries";
3521         asyncResp->res.jsonValue["Description"] =
3522             "Collection of POST Code Log Entries";
3523         asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3524         asyncResp->res.jsonValue["Members@odata.count"] = 0;
3525         size_t skip = delegatedQuery.skip.value_or(0);
3526         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
3527         getCurrentBootNumber(asyncResp, skip, top);
3528         });
3529 }
3530 
3531 /**
3532  * @brief Parse post code ID and get the current value and index value
3533  *        eg: postCodeID=B1-2, currentValue=1, index=2
3534  *
3535  * @param[in]  postCodeID     Post Code ID
3536  * @param[out] currentValue   Current value
3537  * @param[out] index          Index value
3538  *
3539  * @return bool true if the parsing is successful, false the parsing fails
3540  */
3541 inline static bool parsePostCode(const std::string& postCodeID,
3542                                  uint64_t& currentValue, uint16_t& index)
3543 {
3544     std::vector<std::string> split;
3545     boost::algorithm::split(split, postCodeID, boost::is_any_of("-"));
3546     if (split.size() != 2 || split[0].length() < 2 || split[0].front() != 'B')
3547     {
3548         return false;
3549     }
3550 
3551     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3552     const char* start = split[0].data() + 1;
3553     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3554     const char* end = split[0].data() + split[0].size();
3555     auto [ptrIndex, ecIndex] = std::from_chars(start, end, index);
3556 
3557     if (ptrIndex != end || ecIndex != std::errc())
3558     {
3559         return false;
3560     }
3561 
3562     start = split[1].data();
3563 
3564     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3565     end = split[1].data() + split[1].size();
3566     auto [ptrValue, ecValue] = std::from_chars(start, end, currentValue);
3567 
3568     return ptrValue == end && ecValue == std::errc();
3569 }
3570 
3571 inline void requestRoutesPostCodesEntryAdditionalData(App& app)
3572 {
3573     BMCWEB_ROUTE(
3574         app,
3575         "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/<str>/attachment/")
3576         .privileges(redfish::privileges::getLogEntry)
3577         .methods(boost::beast::http::verb::get)(
3578             [&app](const crow::Request& req,
3579                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3580                    const std::string& postCodeID) {
3581         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3582         {
3583             return;
3584         }
3585         if (!http_helpers::isOctetAccepted(req.getHeaderValue("Accept")))
3586         {
3587             asyncResp->res.result(boost::beast::http::status::bad_request);
3588             return;
3589         }
3590 
3591         uint64_t currentValue = 0;
3592         uint16_t index = 0;
3593         if (!parsePostCode(postCodeID, currentValue, index))
3594         {
3595             messages::resourceNotFound(asyncResp->res, "LogEntry", postCodeID);
3596             return;
3597         }
3598 
3599         crow::connections::systemBus->async_method_call(
3600             [asyncResp, postCodeID, currentValue](
3601                 const boost::system::error_code ec,
3602                 const std::vector<std::tuple<uint64_t, std::vector<uint8_t>>>&
3603                     postcodes) {
3604             if (ec.value() == EBADR)
3605             {
3606                 messages::resourceNotFound(asyncResp->res, "LogEntry",
3607                                            postCodeID);
3608                 return;
3609             }
3610             if (ec)
3611             {
3612                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
3613                 messages::internalError(asyncResp->res);
3614                 return;
3615             }
3616 
3617             size_t value = static_cast<size_t>(currentValue) - 1;
3618             if (value == std::string::npos || postcodes.size() < currentValue)
3619             {
3620                 BMCWEB_LOG_ERROR << "Wrong currentValue value";
3621                 messages::resourceNotFound(asyncResp->res, "LogEntry",
3622                                            postCodeID);
3623                 return;
3624             }
3625 
3626             const auto& [tID, c] = postcodes[value];
3627             if (c.empty())
3628             {
3629                 BMCWEB_LOG_INFO << "No found post code data";
3630                 messages::resourceNotFound(asyncResp->res, "LogEntry",
3631                                            postCodeID);
3632                 return;
3633             }
3634             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
3635             const char* d = reinterpret_cast<const char*>(c.data());
3636             std::string_view strData(d, c.size());
3637 
3638             asyncResp->res.addHeader(boost::beast::http::field::content_type,
3639                                      "application/octet-stream");
3640             asyncResp->res.addHeader(
3641                 boost::beast::http::field::content_transfer_encoding, "Base64");
3642             asyncResp->res.body() = crow::utility::base64encode(strData);
3643             },
3644             "xyz.openbmc_project.State.Boot.PostCode0",
3645             "/xyz/openbmc_project/State/Boot/PostCode0",
3646             "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodes", index);
3647         });
3648 }
3649 
3650 inline void requestRoutesPostCodesEntry(App& app)
3651 {
3652     BMCWEB_ROUTE(
3653         app, "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/<str>/")
3654         .privileges(redfish::privileges::getLogEntry)
3655         .methods(boost::beast::http::verb::get)(
3656             [&app](const crow::Request& req,
3657                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3658                    const std::string& targetID) {
3659         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3660         {
3661             return;
3662         }
3663         uint16_t bootIndex = 0;
3664         uint64_t codeIndex = 0;
3665         if (!parsePostCode(targetID, codeIndex, bootIndex))
3666         {
3667             // Requested ID was not found
3668             messages::resourceMissingAtURI(asyncResp->res, req.urlView);
3669             return;
3670         }
3671         if (bootIndex == 0 || codeIndex == 0)
3672         {
3673             BMCWEB_LOG_DEBUG << "Get Post Code invalid entry string "
3674                              << targetID;
3675         }
3676 
3677         asyncResp->res.jsonValue["@odata.type"] = "#LogEntry.v1_4_0.LogEntry";
3678         asyncResp->res.jsonValue["@odata.id"] =
3679             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3680         asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries";
3681         asyncResp->res.jsonValue["Description"] =
3682             "Collection of POST Code Log Entries";
3683         asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3684         asyncResp->res.jsonValue["Members@odata.count"] = 0;
3685 
3686         getPostCodeForEntry(asyncResp, bootIndex, codeIndex);
3687         });
3688 }
3689 
3690 } // namespace redfish
3691