1 /**
2  * Copyright © 2020 IBM Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "journal.hpp"
18 
19 #include <errno.h>
20 #include <stdint.h>
21 #include <string.h>
22 #include <time.h>
23 
24 #include <chrono>
25 #include <stdexcept>
26 #include <thread>
27 
28 namespace phosphor::power::regulators
29 {
30 
31 /**
32  * @class JournalCloser
33  *
34  * Automatically closes the journal when the object goes out of scope.
35  */
36 class JournalCloser
37 {
38   public:
39     // Specify which compiler-generated methods we want
40     JournalCloser() = delete;
41     JournalCloser(const JournalCloser&) = delete;
42     JournalCloser(JournalCloser&&) = delete;
43     JournalCloser& operator=(const JournalCloser&) = delete;
44     JournalCloser& operator=(JournalCloser&&) = delete;
45 
JournalCloser(sd_journal * journal)46     explicit JournalCloser(sd_journal* journal) : journal{journal} {}
47 
~JournalCloser()48     ~JournalCloser()
49     {
50         sd_journal_close(journal);
51     }
52 
53   private:
54     sd_journal* journal{nullptr};
55 };
56 
57 std::vector<std::string>
getMessages(const std::string & field,const std::string & fieldValue,unsigned int max)58     SystemdJournal::getMessages(const std::string& field,
59                                 const std::string& fieldValue, unsigned int max)
60 {
61     // Sleep 100ms; otherwise recent journal entries sometimes not available
62     using namespace std::chrono_literals;
63     std::this_thread::sleep_for(100ms);
64 
65     // Open the journal
66     sd_journal* journal;
67     int rc = sd_journal_open(&journal, SD_JOURNAL_LOCAL_ONLY);
68     if (rc < 0)
69     {
70         throw std::runtime_error{std::string{"Failed to open journal: "} +
71                                  strerror(-rc)};
72     }
73 
74     // Create object to automatically close journal
75     JournalCloser closer{journal};
76 
77     // Add match so we only loop over entries with specified field value
78     std::string match{field + '=' + fieldValue};
79     rc = sd_journal_add_match(journal, match.c_str(), 0);
80     if (rc < 0)
81     {
82         throw std::runtime_error{std::string{"Failed to add journal match: "} +
83                                  strerror(-rc)};
84     }
85 
86     // Loop through matching entries from newest to oldest
87     std::vector<std::string> messages;
88     messages.reserve((max != 0) ? max : 10);
89     std::string syslogID, pid, message, timeStamp, line;
90     SD_JOURNAL_FOREACH_BACKWARDS(journal)
91     {
92         // Get relevant journal entry fields
93         timeStamp = getTimeStamp(journal);
94         syslogID = getFieldValue(journal, "SYSLOG_IDENTIFIER");
95         pid = getFieldValue(journal, "_PID");
96         message = getFieldValue(journal, "MESSAGE");
97 
98         // Build one line string containing field values
99         line = timeStamp + " " + syslogID + "[" + pid + "]: " + message;
100         messages.emplace(messages.begin(), line);
101 
102         // Stop looping if a max was specified and we have reached it
103         if ((max != 0) && (messages.size() >= max))
104         {
105             break;
106         }
107     }
108 
109     return messages;
110 }
111 
getFieldValue(sd_journal * journal,const std::string & field)112 std::string SystemdJournal::getFieldValue(sd_journal* journal,
113                                           const std::string& field)
114 {
115     std::string value{};
116 
117     // Get field data from current journal entry
118     const void* data{nullptr};
119     size_t length{0};
120     int rc = sd_journal_get_data(journal, field.c_str(), &data, &length);
121     if (rc < 0)
122     {
123         if (-rc == ENOENT)
124         {
125             // Current entry does not include this field; return empty value
126             return value;
127         }
128         else
129         {
130             throw std::runtime_error{
131                 std::string{"Failed to read journal entry field: "} +
132                 strerror(-rc)};
133         }
134     }
135 
136     // Get value from field data.  Field data in format "FIELD=value".
137     std::string dataString{static_cast<const char*>(data), length};
138     std::string::size_type pos = dataString.find('=');
139     if ((pos != std::string::npos) && ((pos + 1) < dataString.size()))
140     {
141         // Value is substring after the '='
142         value = dataString.substr(pos + 1);
143     }
144 
145     return value;
146 }
147 
getTimeStamp(sd_journal * journal)148 std::string SystemdJournal::getTimeStamp(sd_journal* journal)
149 {
150     // Get realtime (wallclock) timestamp of current journal entry.  The
151     // timestamp is in microseconds since the epoch.
152     uint64_t usec{0};
153     int rc = sd_journal_get_realtime_usec(journal, &usec);
154     if (rc < 0)
155     {
156         throw std::runtime_error{
157             std::string{"Failed to get journal entry timestamp: "} +
158             strerror(-rc)};
159     }
160 
161     // Convert to number of seconds since the epoch
162     time_t secs = usec / 1000000;
163 
164     // Convert seconds to tm struct required by strftime()
165     struct tm* timeStruct = localtime(&secs);
166     if (timeStruct == nullptr)
167     {
168         throw std::runtime_error{
169             std::string{"Invalid journal entry timestamp: "} + strerror(errno)};
170     }
171 
172     // Convert tm struct into a date/time string
173     char timeStamp[80];
174     strftime(timeStamp, sizeof(timeStamp), "%b %d %H:%M:%S", timeStruct);
175 
176     return timeStamp;
177 }
178 
179 } // namespace phosphor::power::regulators
180