summaryrefslogtreecommitdiff
path: root/redfish-core/src/filesystem_log_watcher.cpp
blob: 41f2c6a4880db9cff6b8a12b51bbca70ebe65da7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#include "filesystem_log_watcher.hpp"

#include "event_log.hpp"
#include "event_logs_object_type.hpp"
#include "event_service_manager.hpp"
#include "logging.hpp"

#include <sys/inotify.h>

#include <boost/asio/buffer.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>

#include <array>
#include <bit>
#include <cstddef>
#include <cstring>
#include <fstream>
#include <functional>
#include <string>
#include <vector>

namespace redfish
{
void FilesystemLogWatcher::resetRedfishFilePosition()
{
    // Control would be here when Redfish file is created.
    // Reset File Position as new file is created
    redfishLogFilePosition = 0;
}

void FilesystemLogWatcher::cacheRedfishLogFile()
{
    // Open the redfish file and read till the last record.

    std::ifstream logStream(redfishEventLogFile);
    if (!logStream.good())
    {
        BMCWEB_LOG_ERROR(" Redfish log file open failed ");
        return;
    }
    std::string logEntry;
    while (std::getline(logStream, logEntry))
    {
        redfishLogFilePosition = logStream.tellg();
    }
}

void FilesystemLogWatcher::readEventLogsFromFile()
{
    std::ifstream logStream(redfishEventLogFile);
    if (!logStream.good())
    {
        BMCWEB_LOG_ERROR(" Redfish log file open failed");
        return;
    }

    std::vector<EventLogObjectsType> eventRecords;

    std::string logEntry;

    BMCWEB_LOG_DEBUG("Redfish log file: seek to {}",
                     static_cast<int>(redfishLogFilePosition));

    // Get the read pointer to the next log to be read.
    logStream.seekg(redfishLogFilePosition);

    while (std::getline(logStream, logEntry))
    {
        BMCWEB_LOG_DEBUG("Redfish log file: found new event log entry");
        // Update Pointer position
        redfishLogFilePosition = logStream.tellg();

        std::string idStr;
        if (!event_log::getUniqueEntryID(logEntry, idStr))
        {
            BMCWEB_LOG_DEBUG(
                "Redfish log file: could not get unique entry id for {}",
                logEntry);
            continue;
        }

        std::string timestamp;
        std::string messageID;
        std::vector<std::string> messageArgs;
        if (event_log::getEventLogParams(logEntry, timestamp, messageID,
                                         messageArgs) != 0)
        {
            BMCWEB_LOG_DEBUG("Read eventLog entry params failed for {}",
                             logEntry);
            continue;
        }

        eventRecords.emplace_back(idStr, timestamp, messageID, messageArgs);
    }

    if (eventRecords.empty())
    {
        // No Records to send
        BMCWEB_LOG_DEBUG("No log entries available to be transferred.");
        return;
    }
    EventServiceManager::sendEventsToSubs(eventRecords);
}

static constexpr const char* redfishEventLogDir = "/var/log";
static constexpr const size_t iEventSize = sizeof(inotify_event);

void FilesystemLogWatcher::onINotify(const boost::system::error_code& ec,
                                     std::size_t bytesTransferred)
{
    if (ec == boost::asio::error::operation_aborted)
    {
        BMCWEB_LOG_DEBUG("Inotify was canceled (shutdown?)");
        return;
    }
    if (ec)
    {
        BMCWEB_LOG_ERROR("Callback Error: {}", ec.message());
        return;
    }

    BMCWEB_LOG_DEBUG("reading {} via inotify", bytesTransferred);

    std::size_t index = 0;
    while ((index + iEventSize) <= bytesTransferred)
    {
        struct inotify_event& event =
            *std::bit_cast<struct inotify_event*>(&readBuffer[index]);
        if (event.wd == dirWatchDesc)
        {
            if ((event.len == 0) ||
                (index + iEventSize + event.len > bytesTransferred))
            {
                index += (iEventSize + event.len);
                continue;
            }

            std::string fileName(&readBuffer[index + iEventSize]);
            if (fileName != "redfish")
            {
                index += (iEventSize + event.len);
                continue;
            }

            BMCWEB_LOG_DEBUG("Redfish log file created/deleted. event.name: {}",
                             fileName);
            if (event.mask == IN_CREATE)
            {
                if (fileWatchDesc != -1)
                {
                    BMCWEB_LOG_DEBUG("Remove and Add inotify watcher on "
                                     "redfish event log file");
                    // Remove existing inotify watcher and add
                    // with new redfish event log file.
                    inotify_rm_watch(inotifyConn.native_handle(),
                                     fileWatchDesc);
                    fileWatchDesc = -1;
                }

                fileWatchDesc =
                    inotify_add_watch(inotifyConn.native_handle(),
                                      redfishEventLogFile, IN_MODIFY);
                if (fileWatchDesc == -1)
                {
                    BMCWEB_LOG_ERROR("inotify_add_watch failed for "
                                     "redfish log file.");
                    return;
                }

                resetRedfishFilePosition();
                readEventLogsFromFile();
            }
            else if ((event.mask == IN_DELETE) || (event.mask == IN_MOVED_TO))
            {
                if (fileWatchDesc != -1)
                {
                    inotify_rm_watch(inotifyConn.native_handle(),
                                     fileWatchDesc);
                    fileWatchDesc = -1;
                }
            }
        }
        else if (event.wd == fileWatchDesc)
        {
            if (event.mask == IN_MODIFY)
            {
                readEventLogsFromFile();
            }
        }
        index += (iEventSize + event.len);
    }

    watchRedfishEventLogFile();
}

void FilesystemLogWatcher::watchRedfishEventLogFile()
{
    inotifyConn.async_read_some(
        boost::asio::buffer(readBuffer),
        std::bind_front(&FilesystemLogWatcher::onINotify, this));
}

FilesystemLogWatcher::FilesystemLogWatcher(boost::asio::io_context& ioc) :
    inotifyConn(ioc)
{
    BMCWEB_LOG_DEBUG("starting Event Log Monitor");

    int inotifyFd = inotify_init1(IN_NONBLOCK);
    if (inotifyFd < 0)
    {
        BMCWEB_LOG_ERROR("inotify_init1 failed.");
        return;
    }
    boost::system::error_code ec;
    inotifyConn.assign(inotifyFd, ec);
    if (ec)
    {
        BMCWEB_LOG_ERROR("Failed to assign fd {}", ec.message());
        return;
    }

    // Add watch on directory to handle redfish event log file
    // create/delete.
    dirWatchDesc =
        inotify_add_watch(inotifyConn.native_handle(), redfishEventLogDir,
                          IN_CREATE | IN_MOVED_TO | IN_DELETE);
    if (dirWatchDesc < 0)
    {
        BMCWEB_LOG_ERROR("inotify_add_watch failed for event log directory.");
        return;
    }

    // Watch redfish event log file for modifications.
    fileWatchDesc = inotify_add_watch(inotifyConn.native_handle(),
                                      redfishEventLogFile, IN_MODIFY);
    if (fileWatchDesc < 0)
    {
        BMCWEB_LOG_ERROR("inotify_add_watch failed for redfish log file.");
        // Don't return error if file not exist.
        // Watch on directory will handle create/delete of file.
    }

    // monitor redfish event log file
    watchRedfishEventLogFile();

    if (redfishLogFilePosition != 0)
    {
        cacheRedfishLogFile();
    }
}
} // namespace redfish