1 //===- unittests/DirectoryWatcher/DirectoryWatcherTest.cpp ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/DirectoryWatcher/DirectoryWatcher.h"
10 #include "llvm/Support/FileSystem.h"
11 #include "llvm/Support/Mutex.h"
12 #include "llvm/Support/Path.h"
13 #include "llvm/Support/raw_ostream.h"
14 #include "gtest/gtest.h"
15 #include <condition_variable>
16 #include <future>
17 #include <mutex>
18 #include <thread>
19 
20 using namespace llvm;
21 using namespace llvm::sys;
22 using namespace llvm::sys::fs;
23 using namespace clang;
24 
25 namespace clang {
26 static bool operator==(const DirectoryWatcher::Event &lhs,
27                        const DirectoryWatcher::Event &rhs) {
28   return lhs.Filename == rhs.Filename &&
29          static_cast<int>(lhs.Kind) == static_cast<int>(rhs.Kind);
30 }
31 } // namespace clang
32 
33 namespace {
34 
35 typedef DirectoryWatcher::Event::EventKind EventKind;
36 
37 struct DirectoryWatcherTestFixture {
38   std::string TestRootDir;
39   std::string TestWatchedDir;
40 
41   DirectoryWatcherTestFixture() {
42     SmallString<128> pathBuf;
43 #ifndef NDEBUG
44     std::error_code UniqDirRes =
45 #endif
46     createUniqueDirectory("dirwatcher", pathBuf);
47     assert(!UniqDirRes);
48     TestRootDir = pathBuf.str();
49     path::append(pathBuf, "watch");
50     TestWatchedDir = pathBuf.str();
51 #ifndef NDEBUG
52     std::error_code CreateDirRes =
53 #endif
54     create_directory(TestWatchedDir, false);
55     assert(!CreateDirRes);
56   }
57 
58   ~DirectoryWatcherTestFixture() { remove_directories(TestRootDir); }
59 
60   SmallString<128> getPathInWatched(const std::string &testFile) {
61     SmallString<128> pathBuf;
62     pathBuf = TestWatchedDir;
63     path::append(pathBuf, testFile);
64     return pathBuf;
65   }
66 
67   void addFile(const std::string &testFile) {
68     Expected<file_t> ft = openNativeFileForWrite(getPathInWatched(testFile),
69                                                  CD_CreateNew, OF_None);
70     if (ft) {
71       closeFile(*ft);
72     } else {
73       llvm::errs() << llvm::toString(ft.takeError()) << "\n";
74       llvm::errs() << getPathInWatched(testFile) << "\n";
75       llvm_unreachable("Couldn't create test file.");
76     }
77   }
78 
79   void deleteFile(const std::string &testFile) {
80     std::error_code EC =
81         remove(getPathInWatched(testFile), /*IgnoreNonExisting=*/false);
82     ASSERT_FALSE(EC);
83   }
84 };
85 
86 std::string eventKindToString(const EventKind K) {
87   switch (K) {
88   case EventKind::Removed:
89     return "Removed";
90   case EventKind::Modified:
91     return "Modified";
92   case EventKind::WatchedDirRemoved:
93     return "WatchedDirRemoved";
94   case EventKind::WatcherGotInvalidated:
95     return "WatcherGotInvalidated";
96   }
97   llvm_unreachable("unknown event kind");
98 }
99 
100 struct VerifyingConsumer {
101   std::vector<DirectoryWatcher::Event> ExpectedInitial;
102   const std::vector<DirectoryWatcher::Event> ExpectedInitialCopy;
103   std::vector<DirectoryWatcher::Event> ExpectedNonInitial;
104   const std::vector<DirectoryWatcher::Event> ExpectedNonInitialCopy;
105   std::vector<DirectoryWatcher::Event> OptionalNonInitial;
106   std::vector<DirectoryWatcher::Event> UnexpectedInitial;
107   std::vector<DirectoryWatcher::Event> UnexpectedNonInitial;
108   std::mutex Mtx;
109   std::condition_variable ResultIsReady;
110 
111   VerifyingConsumer(
112       const std::vector<DirectoryWatcher::Event> &ExpectedInitial,
113       const std::vector<DirectoryWatcher::Event> &ExpectedNonInitial,
114       const std::vector<DirectoryWatcher::Event> &OptionalNonInitial = {})
115       : ExpectedInitial(ExpectedInitial), ExpectedInitialCopy(ExpectedInitial),
116         ExpectedNonInitial(ExpectedNonInitial), ExpectedNonInitialCopy(ExpectedNonInitial),
117         OptionalNonInitial(OptionalNonInitial) {}
118 
119   // This method is used by DirectoryWatcher.
120   void consume(DirectoryWatcher::Event E, bool IsInitial) {
121     if (IsInitial)
122       consumeInitial(E);
123     else
124       consumeNonInitial(E);
125   }
126 
127   void consumeInitial(DirectoryWatcher::Event E) {
128     std::unique_lock<std::mutex> L(Mtx);
129     auto It = std::find(ExpectedInitial.begin(), ExpectedInitial.end(), E);
130     if (It == ExpectedInitial.end()) {
131       UnexpectedInitial.push_back(E);
132     } else {
133       ExpectedInitial.erase(It);
134     }
135     if (result())
136       ResultIsReady.notify_one();
137   }
138 
139   void consumeNonInitial(DirectoryWatcher::Event E) {
140     std::unique_lock<std::mutex> L(Mtx);
141     auto It =
142         std::find(ExpectedNonInitial.begin(), ExpectedNonInitial.end(), E);
143     if (It == ExpectedNonInitial.end()) {
144       auto OptIt =
145           std::find(OptionalNonInitial.begin(), OptionalNonInitial.end(), E);
146       if (OptIt != OptionalNonInitial.end()) {
147         OptionalNonInitial.erase(OptIt);
148       } else {
149         UnexpectedNonInitial.push_back(E);
150       }
151     } else {
152       ExpectedNonInitial.erase(It);
153     }
154     if (result())
155       ResultIsReady.notify_one();
156   }
157 
158   // This method is used by DirectoryWatcher.
159   void consume(llvm::ArrayRef<DirectoryWatcher::Event> Es, bool IsInitial) {
160     for (const auto &E : Es)
161       consume(E, IsInitial);
162   }
163 
164   // Not locking - caller has to lock Mtx.
165   llvm::Optional<bool> result() const {
166     if (ExpectedInitial.empty() && ExpectedNonInitial.empty() &&
167         UnexpectedInitial.empty() && UnexpectedNonInitial.empty())
168       return true;
169     if (!UnexpectedInitial.empty() || !UnexpectedNonInitial.empty())
170       return false;
171     return llvm::None;
172   }
173 
174   // This method is used by tests.
175   // \returns true on success
176   bool blockUntilResult() {
177     std::unique_lock<std::mutex> L(Mtx);
178     while (true) {
179       if (result())
180         return *result();
181 
182       ResultIsReady.wait(L, [this]() { return result().hasValue(); });
183     }
184     return false; // Just to make compiler happy.
185   }
186 
187   void printUnmetExpectations(llvm::raw_ostream &OS) {
188     // If there was any issue, print the expected state
189     if (
190       !ExpectedInitial.empty()
191       ||
192       !ExpectedNonInitial.empty()
193       ||
194       !UnexpectedInitial.empty()
195       ||
196       !UnexpectedNonInitial.empty()
197     ) {
198       OS << "Expected initial events: \n";
199       for (const auto &E : ExpectedInitialCopy) {
200         OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
201       }
202       OS << "Expected non-initial events: \n";
203       for (const auto &E : ExpectedNonInitialCopy) {
204         OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
205       }
206     }
207 
208     if (!ExpectedInitial.empty()) {
209       OS << "Expected but not seen initial events: \n";
210       for (const auto &E : ExpectedInitial) {
211         OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
212       }
213     }
214     if (!ExpectedNonInitial.empty()) {
215       OS << "Expected but not seen non-initial events: \n";
216       for (const auto &E : ExpectedNonInitial) {
217         OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
218       }
219     }
220     if (!UnexpectedInitial.empty()) {
221       OS << "Unexpected initial events seen: \n";
222       for (const auto &E : UnexpectedInitial) {
223         OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
224       }
225     }
226     if (!UnexpectedNonInitial.empty()) {
227       OS << "Unexpected non-initial events seen: \n";
228       for (const auto &E : UnexpectedNonInitial) {
229         OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
230       }
231     }
232   }
233 };
234 
235 void checkEventualResultWithTimeout(VerifyingConsumer &TestConsumer) {
236   std::packaged_task<int(void)> task(
237       [&TestConsumer]() { return TestConsumer.blockUntilResult(); });
238   std::future<int> WaitForExpectedStateResult = task.get_future();
239   std::thread worker(std::move(task));
240   worker.detach();
241 
242   EXPECT_TRUE(WaitForExpectedStateResult.wait_for(std::chrono::seconds(3)) ==
243               std::future_status::ready)
244       << "The expected result state wasn't reached before the time-out.";
245   std::unique_lock<std::mutex> L(TestConsumer.Mtx);
246   EXPECT_TRUE(TestConsumer.result().hasValue());
247   if (TestConsumer.result().hasValue()) {
248     EXPECT_TRUE(*TestConsumer.result());
249   }
250   if ((TestConsumer.result().hasValue() && !TestConsumer.result().getValue()) ||
251       !TestConsumer.result().hasValue())
252     TestConsumer.printUnmetExpectations(llvm::outs());
253 }
254 } // namespace
255 
256 TEST(DirectoryWatcherTest, InitialScanSync) {
257   DirectoryWatcherTestFixture fixture;
258 
259   fixture.addFile("a");
260   fixture.addFile("b");
261   fixture.addFile("c");
262 
263   VerifyingConsumer TestConsumer{
264       {{EventKind::Modified, "a"},
265        {EventKind::Modified, "b"},
266        {EventKind::Modified, "c"}},
267       {},
268       // We have to ignore these as it's a race between the test process
269       // which is scanning the directory and kernel which is sending
270       // notification.
271       {{EventKind::Modified, "a"},
272        {EventKind::Modified, "b"},
273        {EventKind::Modified, "c"}}
274       };
275 
276   auto DW = DirectoryWatcher::create(
277       fixture.TestWatchedDir,
278       [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
279                       bool IsInitial) {
280         TestConsumer.consume(Events, IsInitial);
281       },
282       /*waitForInitialSync=*/true);
283 
284   checkEventualResultWithTimeout(TestConsumer);
285 }
286 
287 TEST(DirectoryWatcherTest, InitialScanAsync) {
288   DirectoryWatcherTestFixture fixture;
289 
290   fixture.addFile("a");
291   fixture.addFile("b");
292   fixture.addFile("c");
293 
294   VerifyingConsumer TestConsumer{
295       {{EventKind::Modified, "a"},
296        {EventKind::Modified, "b"},
297        {EventKind::Modified, "c"}},
298       {},
299       // We have to ignore these as it's a race between the test process
300       // which is scanning the directory and kernel which is sending
301       // notification.
302       {{EventKind::Modified, "a"},
303        {EventKind::Modified, "b"},
304        {EventKind::Modified, "c"}}
305        };
306 
307   auto DW = DirectoryWatcher::create(
308       fixture.TestWatchedDir,
309       [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
310                       bool IsInitial) {
311         TestConsumer.consume(Events, IsInitial);
312       },
313       /*waitForInitialSync=*/false);
314 
315   checkEventualResultWithTimeout(TestConsumer);
316 }
317 
318 TEST(DirectoryWatcherTest, AddFiles) {
319   DirectoryWatcherTestFixture fixture;
320 
321   VerifyingConsumer TestConsumer{
322       {},
323       {{EventKind::Modified, "a"},
324        {EventKind::Modified, "b"},
325        {EventKind::Modified, "c"}}};
326 
327   auto DW = DirectoryWatcher::create(
328       fixture.TestWatchedDir,
329       [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
330                       bool IsInitial) {
331         TestConsumer.consume(Events, IsInitial);
332       },
333       /*waitForInitialSync=*/true);
334 
335   fixture.addFile("a");
336   fixture.addFile("b");
337   fixture.addFile("c");
338 
339   checkEventualResultWithTimeout(TestConsumer);
340 }
341 
342 TEST(DirectoryWatcherTest, ModifyFile) {
343   DirectoryWatcherTestFixture fixture;
344 
345   fixture.addFile("a");
346 
347   VerifyingConsumer TestConsumer{
348       {{EventKind::Modified, "a"}},
349       {{EventKind::Modified, "a"}},
350       {{EventKind::Modified, "a"}}};
351 
352   auto DW = DirectoryWatcher::create(
353       fixture.TestWatchedDir,
354       [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
355                       bool IsInitial) {
356         TestConsumer.consume(Events, IsInitial);
357       },
358       /*waitForInitialSync=*/true);
359 
360   // modify the file
361   {
362     std::error_code error;
363     llvm::raw_fd_ostream bStream(fixture.getPathInWatched("a"), error,
364                                  CD_OpenExisting);
365     assert(!error);
366     bStream << "foo";
367   }
368 
369   checkEventualResultWithTimeout(TestConsumer);
370 }
371 
372 TEST(DirectoryWatcherTest, DeleteFile) {
373   DirectoryWatcherTestFixture fixture;
374 
375   fixture.addFile("a");
376 
377   VerifyingConsumer TestConsumer{
378       {{EventKind::Modified, "a"}},
379       {{EventKind::Removed, "a"}},
380       {{EventKind::Modified, "a"}}};
381 
382   auto DW = DirectoryWatcher::create(
383       fixture.TestWatchedDir,
384       [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
385                       bool IsInitial) {
386         TestConsumer.consume(Events, IsInitial);
387       },
388       /*waitForInitialSync=*/true);
389 
390   fixture.deleteFile("a");
391 
392   checkEventualResultWithTimeout(TestConsumer);
393 }
394 
395 TEST(DirectoryWatcherTest, DeleteWatchedDir) {
396   DirectoryWatcherTestFixture fixture;
397 
398   VerifyingConsumer TestConsumer{
399       {},
400       {{EventKind::WatchedDirRemoved, ""},
401        {EventKind::WatcherGotInvalidated, ""}}};
402 
403   auto DW = DirectoryWatcher::create(
404       fixture.TestWatchedDir,
405       [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
406                       bool IsInitial) {
407         TestConsumer.consume(Events, IsInitial);
408       },
409       /*waitForInitialSync=*/true);
410 
411   remove_directories(fixture.TestWatchedDir);
412 
413   checkEventualResultWithTimeout(TestConsumer);
414 }
415 
416 TEST(DirectoryWatcherTest, InvalidatedWatcher) {
417   DirectoryWatcherTestFixture fixture;
418 
419   VerifyingConsumer TestConsumer{
420       {}, {{EventKind::WatcherGotInvalidated, ""}}};
421 
422   {
423     auto DW = DirectoryWatcher::create(
424         fixture.TestWatchedDir,
425         [&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
426                         bool IsInitial) {
427           TestConsumer.consume(Events, IsInitial);
428         },
429         /*waitForInitialSync=*/true);
430   } // DW is destructed here.
431 
432   checkEventualResultWithTimeout(TestConsumer);
433 }