Debian Codegraph @

node/@parcel/watcher/src/watchman/WatchmanBackend.cc

raw
1 #include <string>
2 #include <fstream>
3 #include <stdlib.h>
4 #include <algorithm>
5 #include "../DirTree.hh"
6 #include "../Event.hh"
7 #include "./BSER.hh"
8 #include "./WatchmanBackend.hh"
9
10 #ifdef _WIN32
11 #include "../windows/win_utils.hh"
12 #define S_ISDIR(mode) ((mode & _S_IFDIR) == _S_IFDIR)
13 #define popen _popen
14 #define pclose _pclose
15 #else
16 #include <sys/stat.h>
17 #define normalizePath(dir) dir
18 #endif
19
20 template<typename T>
21 BSER readBSER(T &&do_read) {
22 std::stringstream oss;
23 char buffer[256];
24 size_t r;
25 int64_t len = -1;
26 do {
27 // Start by reading a minimal amount of data in order to decode the length.
28 // After that, attempt to read the remaining length, up to the buffer size.
29 r = do_read(buffer, len == -1 ? 20 : (len < 256 ? len : 256));
30 oss << std::string(buffer, r);
31
32 if (len == -1) {
33 uint64_t l = BSER::decodeLength(oss);
34 len = l + oss.tellg();
35 }
36
37 len -= r;
38 } while (len > 0);
39
40 return BSER(oss);
41 }
42
43 std::string getSockPath() {
44 auto var = getenv("WATCHMAN_SOCK");
45 if (var && *var) {
46 return std::string(var);
47 }
48
49 #ifdef _WIN32
50 FILE *fp = popen("watchman --output-encoding=bser get-sockname", "r");
51 #else
52 FILE *fp = popen("watchman --output-encoding=bser get-sockname 2>/dev/null", "r");
53 #endif
54 if (fp == NULL || errno == ECHILD) {
55 throw std::runtime_error("Failed to execute watchman");
56 }
57
58 BSER b = readBSER([fp] (char *buf, size_t len) {
59 return fread(buf, sizeof(char), len, fp);
60 });
61
62 pclose(fp);
63
64 auto objValue = b.objectValue();
65 auto foundSockname = objValue.find("sockname");
66 if (foundSockname == objValue.end()) {
67 throw std::runtime_error("sockname not found");
68 }
69 return foundSockname->second.stringValue();
70 }
71
72 std::unique_ptr<IPC> watchmanConnect() {
73 std::string path = getSockPath();
74 return std::unique_ptr<IPC>(new IPC(path));
75 }
76
77 BSER watchmanRead(IPC *ipc) {
78 return readBSER([ipc] (char *buf, size_t len) {
79 return ipc->read(buf, len);
80 });
81 }
82
83 BSER::Object WatchmanBackend::watchmanRequest(BSER b) {
84 std::string cmd = b.encode();
85 mIPC->write(cmd);
86 mRequestSignal.notify();
87
88 mResponseSignal.wait();
89 mResponseSignal.reset();
90
91 if (!mError.empty()) {
92 std::runtime_error err = std::runtime_error(mError);
93 mError = std::string();
94 throw err;
95 }
96
97 return mResponse;
98 }
99
100 void WatchmanBackend::watchmanWatch(std::string dir) {
101 std::vector<BSER> cmd;
102 cmd.push_back("watch");
103 cmd.push_back(normalizePath(dir));
104 watchmanRequest(cmd);
105 }
106
107 bool WatchmanBackend::checkAvailable() {
108 try {
109 watchmanConnect();
110 return true;
111 } catch (std::exception&) {
112 return false;
113 }
114 }
115
116 void handleFiles(WatcherRef watcher, BSER::Object obj) {
117 auto found = obj.find("files");
118 if (found == obj.end()) {
119 throw WatcherError("Error reading changes from watchman", watcher);
120 }
121
122 auto files = found->second.arrayValue();
123 for (auto it = files.begin(); it != files.end(); it++) {
124 auto file = it->objectValue();
125 auto name = file.find("name")->second.stringValue();
126 #ifdef _WIN32
127 std::replace(name.begin(), name.end(), '/', '\\');
128 #endif
129 auto mode = file.find("mode")->second.intValue();
130 auto isNew = file.find("new")->second.boolValue();
131 auto exists = file.find("exists")->second.boolValue();
132 auto path = watcher->mDir + DIR_SEP + name;
133 if (watcher->isIgnored(path)) {
134 continue;
135 }
136
137 if (isNew && exists) {
138 watcher->mEvents.create(path);
139 } else if (exists && !S_ISDIR(mode)) {
140 watcher->mEvents.update(path);
141 } else if (!isNew && !exists) {
142 watcher->mEvents.remove(path);
143 }
144 }
145 }
146
147 void WatchmanBackend::handleSubscription(BSER::Object obj) {
148 std::unique_lock<std::mutex> lock(mMutex);
149 auto subscription = obj.find("subscription")->second.stringValue();
150 auto it = mSubscriptions.find(subscription);
151 if (it == mSubscriptions.end()) {
152 return;
153 }
154
155 auto watcher = it->second;
156 try {
157 handleFiles(watcher, obj);
158 watcher->notify();
159 } catch (WatcherError &err) {
160 handleWatcherError(err);
161 }
162 }
163
164 void WatchmanBackend::start() {
165 mIPC = watchmanConnect();
166 notifyStarted();
167
168 while (true) {
169 // If there are no subscriptions we are reading, wait for a request.
170 if (mSubscriptions.size() == 0) {
171 mRequestSignal.wait();
172 mRequestSignal.reset();
173 }
174
175 // Break out of loop if we are stopped.
176 if (mStopped) {
177 break;
178 }
179
180 // Attempt to read from the socket.
181 // If there is an error and we are stopped, break.
182 BSER b;
183 try {
184 b = watchmanRead(&*mIPC);
185 } catch (std::exception &err) {
186 if (mStopped) {
187 break;
188 } else if (mResponseSignal.isWaiting()) {
189 mError = err.what();
190 mResponseSignal.notify();
191 } else {
192 // Throwing causes the backend to be destroyed, but we never reach the code below to notify the signal
193 mEndedSignal.notify();
194 throw;
195 }
196 }
197
198 auto obj = b.objectValue();
199 auto error = obj.find("error");
200 if (error != obj.end()) {
201 mError = error->second.stringValue();
202 mResponseSignal.notify();
203 continue;
204 }
205
206 // If this message is for a subscription, handle it, otherwise notify the request.
207 auto subscription = obj.find("subscription");
208 if (subscription != obj.end()) {
209 handleSubscription(obj);
210 } else {
211 mResponse = obj;
212 mResponseSignal.notify();
213 }
214 }
215
216 mEndedSignal.notify();
217 }
218
219 WatchmanBackend::~WatchmanBackend() {
220 // Mark the watcher as stopped, close the socket, and trigger the lock.
221 // This will cause the read loop to be broken and the thread to exit.
222 mStopped = true;
223 mIPC.reset();
224 mRequestSignal.notify();
225
226 // If not ended yet, wait.
227 mEndedSignal.wait();
228 }
229
230 std::string WatchmanBackend::clock(WatcherRef watcher) {
231 BSER::Array cmd;
232 cmd.push_back("clock");
233 cmd.push_back(normalizePath(watcher->mDir));
234
235 BSER::Object obj = watchmanRequest(cmd);
236 auto found = obj.find("clock");
237 if (found == obj.end()) {
238 throw WatcherError("Error reading clock from watchman", watcher);
239 }
240
241 return found->second.stringValue();
242 }
243
244 void WatchmanBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
245 std::unique_lock<std::mutex> lock(mMutex);
246 watchmanWatch(watcher->mDir);
247
248 std::ofstream ofs(*snapshotPath);
249 ofs << clock(watcher);
250 }
251
252 void WatchmanBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
253 std::unique_lock<std::mutex> lock(mMutex);
254 std::ifstream ifs(*snapshotPath);
255 if (ifs.fail()) {
256 return;
257 }
258
259 watchmanWatch(watcher->mDir);
260
261 std::string clock;
262 ifs >> clock;
263
264 BSER::Array cmd;
265 cmd.push_back("since");
266 cmd.push_back(normalizePath(watcher->mDir));
267 cmd.push_back(clock);
268
269 BSER::Object obj = watchmanRequest(cmd);
270 handleFiles(watcher, obj);
271 }
272
273 std::string getId(WatcherRef watcher) {
274 std::ostringstream id;
275 id << "parcel-";
276 id << static_cast<void*>(watcher.get());
277 return id.str();
278 }
279
280 // This function is called by Backend::watch which takes a lock on mMutex
281 void WatchmanBackend::subscribe(WatcherRef watcher) {
282 watchmanWatch(watcher->mDir);
283
284 std::string id = getId(watcher);
285 BSER::Array cmd;
286 cmd.push_back("subscribe");
287 cmd.push_back(normalizePath(watcher->mDir));
288 cmd.push_back(id);
289
290 BSER::Array fields;
291 fields.push_back("name");
292 fields.push_back("mode");
293 fields.push_back("exists");
294 fields.push_back("new");
295
296 BSER::Object opts;
297 opts.emplace("fields", fields);
298 opts.emplace("since", clock(watcher));
299
300 if (watcher->mIgnorePaths.size() > 0) {
301 BSER::Array ignore;
302 BSER::Array anyOf;
303 anyOf.push_back("anyof");
304
305 for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) {
306 std::string pathStart = watcher->mDir + DIR_SEP;
307 if (it->rfind(pathStart, 0) == 0) {
308 auto relative = it->substr(pathStart.size());
309 BSER::Array dirname;
310 dirname.push_back("dirname");
311 dirname.push_back(relative);
312 anyOf.push_back(dirname);
313 }
314 }
315
316 ignore.push_back("not");
317 ignore.push_back(anyOf);
318
319 opts.emplace("expression", ignore);
320 }
321
322 cmd.push_back(opts);
323 watchmanRequest(cmd);
324
325 mSubscriptions.emplace(id, watcher);
326 mRequestSignal.notify();
327 }
328
329 // This function is called by Backend::unwatch which takes a lock on mMutex
330 void WatchmanBackend::unsubscribe(WatcherRef watcher) {
331 std::string id = getId(watcher);
332 auto erased = mSubscriptions.erase(id);
333
334 if (erased) {
335 BSER::Array cmd;
336 cmd.push_back("unsubscribe");
337 cmd.push_back(normalizePath(watcher->mDir));
338 cmd.push_back(id);
339
340 watchmanRequest(cmd);
341 }
342 }