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
|
#include "config.h"
#include "watch.hpp"
#include "item_updater_ubi.hpp"
#include <sys/inotify.h>
#include <unistd.h>
#include <cstddef>
#include <cstring>
#include <experimental/filesystem>
#include <functional>
#include <phosphor-logging/log.hpp>
#include <stdexcept>
#include <string>
namespace openpower
{
namespace software
{
namespace updater
{
using namespace phosphor::logging;
namespace fs = std::experimental::filesystem;
Watch::Watch(sd_event* loop,
std::function<void(const std::string&)> functionalCallback) :
functionalCallback(functionalCallback),
fd(inotifyInit())
{
// Create PNOR_ACTIVE_PATH if doesn't exist.
if (!fs::is_directory(PNOR_ACTIVE_PATH))
{
fs::create_directories(PNOR_ACTIVE_PATH);
}
wd = inotify_add_watch(fd(), PNOR_ACTIVE_PATH, IN_CREATE);
if (-1 == wd)
{
auto error = errno;
throw std::system_error(error, std::generic_category(),
"Error occurred during the inotify_init1");
}
decltype(eventSource.get()) sourcePtr = nullptr;
auto rc = sd_event_add_io(loop, &sourcePtr, fd(), EPOLLIN, callback, this);
eventSource.reset(sourcePtr);
if (0 > rc)
{
throw std::system_error(-rc, std::generic_category(),
"Error occurred during the inotify_init1");
}
}
Watch::~Watch()
{
if ((-1 != fd()) && (-1 != wd))
{
inotify_rm_watch(fd(), wd);
}
}
int Watch::callback(sd_event_source* s, int fd, uint32_t revents,
void* userdata)
{
if (!(revents & EPOLLIN))
{
return 0;
}
constexpr auto maxBytes = 1024;
uint8_t buffer[maxBytes];
auto bytes = read(fd, buffer, maxBytes);
if (0 > bytes)
{
auto error = errno;
throw std::system_error(error, std::generic_category(),
"failed to read inotify event");
}
auto offset = 0;
while (offset < bytes)
{
auto event = reinterpret_cast<inotify_event*>(&buffer[offset]);
// Update the functional association on a RO
// active image symlink change
fs::path path(PNOR_ACTIVE_PATH);
path /= event->name;
if (fs::equivalent(path, PNOR_RO_ACTIVE_PATH))
{
auto id = ItemUpdaterUbi::determineId(path);
static_cast<Watch*>(userdata)->functionalCallback(id);
}
offset += offsetof(inotify_event, name) + event->len;
}
return 0;
}
int Watch::inotifyInit()
{
auto fd = inotify_init1(IN_NONBLOCK);
if (-1 == fd)
{
auto error = errno;
throw std::system_error(error, std::generic_category(),
"Error occurred during the inotify_init1");
}
return fd;
}
} // namespace updater
} // namespace software
} // namespace openpower
|