basicfs_watch_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // +build !solaris,!darwin solaris,cgo darwin,cgo
  7. package fs
  8. import (
  9. "context"
  10. "errors"
  11. "fmt"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "syscall"
  18. "testing"
  19. "time"
  20. "github.com/syncthing/notify"
  21. )
  22. func TestMain(m *testing.M) {
  23. if err := os.RemoveAll(testDir); err != nil {
  24. panic(err)
  25. }
  26. dir, err := filepath.Abs(".")
  27. if err != nil {
  28. panic("Cannot get absolute path to working dir")
  29. }
  30. dir, err = evalSymlinks(dir)
  31. if err != nil {
  32. panic("Cannot get real path to working dir")
  33. }
  34. testDirAbs = filepath.Join(dir, testDir)
  35. if runtime.GOOS == "windows" {
  36. testDirAbs = longFilenameSupport(testDirAbs)
  37. }
  38. testFs = NewFilesystem(FilesystemTypeBasic, testDirAbs)
  39. backendBuffer = 10
  40. exitCode := m.Run()
  41. backendBuffer = 500
  42. os.RemoveAll(testDir)
  43. os.Exit(exitCode)
  44. }
  45. const (
  46. testDir = "testdata"
  47. failsOnOpenBSD = "Fails on OpenBSD. See https://github.com/rjeczalik/notify/issues/172"
  48. )
  49. var (
  50. testDirAbs string
  51. testFs Filesystem
  52. )
  53. func TestWatchIgnore(t *testing.T) {
  54. if runtime.GOOS == "openbsd" {
  55. t.Skip(failsOnOpenBSD)
  56. }
  57. name := "ignore"
  58. file := "file"
  59. ignored := "ignored"
  60. testCase := func() {
  61. createTestFile(name, file)
  62. createTestFile(name, ignored)
  63. }
  64. expectedEvents := []Event{
  65. {file, NonRemove},
  66. }
  67. allowedEvents := []Event{
  68. {name, NonRemove},
  69. }
  70. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{ignore: filepath.Join(name, ignored), skipIgnoredDirs: true})
  71. }
  72. func TestWatchInclude(t *testing.T) {
  73. if runtime.GOOS == "openbsd" {
  74. t.Skip(failsOnOpenBSD)
  75. }
  76. name := "include"
  77. file := "file"
  78. ignored := "ignored"
  79. testFs.MkdirAll(filepath.Join(name, ignored), 0777)
  80. included := filepath.Join(ignored, "included")
  81. testCase := func() {
  82. createTestFile(name, file)
  83. createTestFile(name, included)
  84. }
  85. expectedEvents := []Event{
  86. {file, NonRemove},
  87. {included, NonRemove},
  88. }
  89. allowedEvents := []Event{
  90. {name, NonRemove},
  91. }
  92. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{ignore: filepath.Join(name, ignored), include: filepath.Join(name, included)})
  93. }
  94. func TestWatchRename(t *testing.T) {
  95. if runtime.GOOS == "openbsd" {
  96. t.Skip(failsOnOpenBSD)
  97. }
  98. name := "rename"
  99. old := createTestFile(name, "oldfile")
  100. new := "newfile"
  101. testCase := func() {
  102. renameTestFile(name, old, new)
  103. }
  104. destEvent := Event{new, Remove}
  105. // Only on these platforms the removed file can be differentiated from
  106. // the created file during renaming
  107. if runtime.GOOS == "windows" || runtime.GOOS == "linux" || runtime.GOOS == "solaris" {
  108. destEvent = Event{new, NonRemove}
  109. }
  110. expectedEvents := []Event{
  111. {old, Remove},
  112. destEvent,
  113. }
  114. allowedEvents := []Event{
  115. {name, NonRemove},
  116. }
  117. // set the "allow others" flag because we might get the create of
  118. // "oldfile" initially
  119. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
  120. }
  121. // TestWatchWinRoot checks that a watch at a drive letter does not panic due to
  122. // out of root event on every event.
  123. // https://github.com/syncthing/syncthing/issues/5695
  124. func TestWatchWinRoot(t *testing.T) {
  125. if runtime.GOOS != "windows" {
  126. t.Skip("Windows specific test")
  127. }
  128. outChan := make(chan Event)
  129. backendChan := make(chan notify.EventInfo, backendBuffer)
  130. errChan := make(chan error)
  131. ctx, cancel := context.WithCancel(context.Background())
  132. // testFs is Filesystem, but we need BasicFilesystem here
  133. root := `D:\`
  134. fs := newBasicFilesystem(root)
  135. watch, roots, err := fs.watchPaths(".")
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. go func() {
  140. defer func() {
  141. if r := recover(); r != nil {
  142. t.Error(r)
  143. }
  144. cancel()
  145. }()
  146. fs.watchLoop(ctx, ".", roots, backendChan, outChan, errChan, fakeMatcher{})
  147. }()
  148. // filepath.Dir as watch has a /... suffix
  149. name := "foo"
  150. backendChan <- fakeEventInfo(filepath.Join(filepath.Dir(watch), name))
  151. select {
  152. case <-time.After(10 * time.Second):
  153. cancel()
  154. t.Errorf("Timed out before receiving event")
  155. case ev := <-outChan:
  156. if ev.Name != name {
  157. t.Errorf("Unexpected event %v, expected %v", ev.Name, name)
  158. }
  159. case err := <-errChan:
  160. t.Error("Received fatal watch error:", err)
  161. case <-ctx.Done():
  162. }
  163. }
  164. // TestWatchOutside checks that no changes from outside the folder make it in
  165. func TestWatchOutside(t *testing.T) {
  166. expectErrorForPath(t, filepath.Join(filepath.Dir(testDirAbs), "outside"))
  167. rootWithoutSlash := strings.TrimRight(filepath.ToSlash(testDirAbs), "/")
  168. expectErrorForPath(t, rootWithoutSlash+"outside")
  169. expectErrorForPath(t, rootWithoutSlash+"outside/thing")
  170. }
  171. func expectErrorForPath(t *testing.T, path string) {
  172. outChan := make(chan Event)
  173. backendChan := make(chan notify.EventInfo, backendBuffer)
  174. errChan := make(chan error)
  175. ctx, cancel := context.WithCancel(context.Background())
  176. defer cancel()
  177. // testFs is Filesystem, but we need BasicFilesystem here
  178. fs := newBasicFilesystem(testDirAbs)
  179. go fs.watchLoop(ctx, ".", []string{testDirAbs}, backendChan, outChan, errChan, fakeMatcher{})
  180. backendChan <- fakeEventInfo(path)
  181. select {
  182. case <-time.After(10 * time.Second):
  183. t.Errorf("Timed out before receiving error")
  184. case e := <-outChan:
  185. t.Errorf("Unexpected passed through event %v", e)
  186. case <-errChan:
  187. case <-ctx.Done():
  188. }
  189. }
  190. func TestWatchSubpath(t *testing.T) {
  191. outChan := make(chan Event)
  192. backendChan := make(chan notify.EventInfo, backendBuffer)
  193. errChan := make(chan error)
  194. ctx, cancel := context.WithCancel(context.Background())
  195. // testFs is Filesystem, but we need BasicFilesystem here
  196. fs := newBasicFilesystem(testDirAbs)
  197. abs, _ := fs.rooted("sub")
  198. go fs.watchLoop(ctx, "sub", []string{testDirAbs}, backendChan, outChan, errChan, fakeMatcher{})
  199. backendChan <- fakeEventInfo(filepath.Join(abs, "file"))
  200. timeout := time.NewTimer(2 * time.Second)
  201. select {
  202. case <-timeout.C:
  203. t.Errorf("Timed out before receiving an event")
  204. cancel()
  205. case ev := <-outChan:
  206. if ev.Name != filepath.Join("sub", "file") {
  207. t.Errorf("While watching a subfolder, received an event with unexpected path %v", ev.Name)
  208. }
  209. case err := <-errChan:
  210. t.Error("Received fatal watch error:", err)
  211. }
  212. cancel()
  213. }
  214. // TestWatchOverflow checks that an event at the root is sent when maxFiles is reached
  215. func TestWatchOverflow(t *testing.T) {
  216. if runtime.GOOS == "openbsd" {
  217. t.Skip(failsOnOpenBSD)
  218. }
  219. name := "overflow"
  220. expectedEvents := []Event{
  221. {".", NonRemove},
  222. }
  223. allowedEvents := []Event{
  224. {name, NonRemove},
  225. }
  226. testCase := func() {
  227. for i := 0; i < 5*backendBuffer; i++ {
  228. file := "file" + strconv.Itoa(i)
  229. createTestFile(name, file)
  230. allowedEvents = append(allowedEvents, Event{file, NonRemove})
  231. }
  232. }
  233. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
  234. }
  235. func TestWatchErrorLinuxInterpretation(t *testing.T) {
  236. if runtime.GOOS != "linux" {
  237. t.Skip("testing of linux specific error codes")
  238. }
  239. var errTooManyFiles = &os.PathError{
  240. Op: "error while traversing",
  241. Path: "foo",
  242. Err: syscall.Errno(24),
  243. }
  244. var errNoSpace = &os.PathError{
  245. Op: "error while traversing",
  246. Path: "bar",
  247. Err: syscall.Errno(28),
  248. }
  249. if !reachedMaxUserWatches(errTooManyFiles) {
  250. t.Error("Underlying error syscall.Errno(24) should be recognised to be about inotify limits.")
  251. }
  252. if !reachedMaxUserWatches(errNoSpace) {
  253. t.Error("Underlying error syscall.Errno(28) should be recognised to be about inotify limits.")
  254. }
  255. err := errors.New("Another error")
  256. if reachedMaxUserWatches(err) {
  257. t.Errorf("This error does not concern inotify limits: %#v", err)
  258. }
  259. }
  260. func TestWatchSymlinkedRoot(t *testing.T) {
  261. if runtime.GOOS == "windows" {
  262. t.Skip("Involves symlinks")
  263. }
  264. name := "symlinkedRoot"
  265. if err := testFs.MkdirAll(name, 0755); err != nil {
  266. panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
  267. }
  268. defer testFs.RemoveAll(name)
  269. root := filepath.Join(name, "root")
  270. if err := testFs.MkdirAll(root, 0777); err != nil {
  271. panic(err)
  272. }
  273. link := filepath.Join(name, "link")
  274. if err := testFs.CreateSymlink(filepath.Join(testFs.URI(), root), link); err != nil {
  275. panic(err)
  276. }
  277. linkedFs := NewFilesystem(FilesystemTypeBasic, filepath.Join(testFs.URI(), link))
  278. ctx, cancel := context.WithCancel(context.Background())
  279. defer cancel()
  280. if _, _, err := linkedFs.Watch(".", fakeMatcher{}, ctx, false); err != nil {
  281. panic(err)
  282. }
  283. if err := linkedFs.MkdirAll("foo", 0777); err != nil {
  284. panic(err)
  285. }
  286. // Give the panic some time to happen
  287. sleepMs(100)
  288. }
  289. func TestUnrootedChecked(t *testing.T) {
  290. fs := newBasicFilesystem(testDirAbs)
  291. if unrooted, err := fs.unrootedChecked("/random/other/path", []string{testDirAbs}); err == nil {
  292. t.Error("unrootedChecked did not return an error on outside path, but returned", unrooted)
  293. }
  294. }
  295. func TestWatchIssue4877(t *testing.T) {
  296. if runtime.GOOS != "windows" {
  297. t.Skip("Windows specific test")
  298. }
  299. name := "Issue4877"
  300. file := "file"
  301. testCase := func() {
  302. createTestFile(name, file)
  303. }
  304. expectedEvents := []Event{
  305. {file, NonRemove},
  306. }
  307. allowedEvents := []Event{
  308. {name, NonRemove},
  309. }
  310. volName := filepath.VolumeName(testDirAbs)
  311. if volName == "" {
  312. t.Fatalf("Failed to get volume name for path %v", testDirAbs)
  313. }
  314. origTestFs := testFs
  315. testFs = NewFilesystem(FilesystemTypeBasic, strings.ToLower(volName)+strings.ToUpper(testDirAbs[len(volName):]))
  316. defer func() {
  317. testFs = origTestFs
  318. }()
  319. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
  320. }
  321. // path relative to folder root, also creates parent dirs if necessary
  322. func createTestFile(name string, file string) string {
  323. joined := filepath.Join(name, file)
  324. if err := testFs.MkdirAll(filepath.Dir(joined), 0755); err != nil {
  325. panic(fmt.Sprintf("Failed to create parent directory for %s: %s", joined, err))
  326. }
  327. handle, err := testFs.Create(joined)
  328. if err != nil {
  329. panic(fmt.Sprintf("Failed to create test file %s: %s", joined, err))
  330. }
  331. handle.Close()
  332. return file
  333. }
  334. func renameTestFile(name string, old string, new string) {
  335. old = filepath.Join(name, old)
  336. new = filepath.Join(name, new)
  337. if err := testFs.Rename(old, new); err != nil {
  338. panic(fmt.Sprintf("Failed to rename %s to %s: %s", old, new, err))
  339. }
  340. }
  341. func sleepMs(ms int) {
  342. time.Sleep(time.Duration(ms) * time.Millisecond)
  343. }
  344. func testScenario(t *testing.T, name string, testCase func(), expectedEvents, allowedEvents []Event, fm fakeMatcher) {
  345. if err := testFs.MkdirAll(name, 0755); err != nil {
  346. panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
  347. }
  348. defer testFs.RemoveAll(name)
  349. ctx, cancel := context.WithCancel(context.Background())
  350. defer cancel()
  351. eventChan, errChan, err := testFs.Watch(name, fm, ctx, false)
  352. if err != nil {
  353. panic(err)
  354. }
  355. go testWatchOutput(t, name, eventChan, expectedEvents, allowedEvents, ctx, cancel)
  356. testCase()
  357. select {
  358. case <-time.After(10 * time.Second):
  359. t.Error("Timed out before receiving all expected events")
  360. case err := <-errChan:
  361. t.Error("Received fatal watch error:", err)
  362. case <-ctx.Done():
  363. }
  364. }
  365. func testWatchOutput(t *testing.T, name string, in <-chan Event, expectedEvents, allowedEvents []Event, ctx context.Context, cancel context.CancelFunc) {
  366. var expected = make(map[Event]struct{})
  367. for _, ev := range expectedEvents {
  368. ev.Name = filepath.Join(name, ev.Name)
  369. expected[ev] = struct{}{}
  370. }
  371. var received Event
  372. var last Event
  373. for {
  374. if len(expected) == 0 {
  375. cancel()
  376. return
  377. }
  378. select {
  379. case <-ctx.Done():
  380. return
  381. case received = <-in:
  382. }
  383. // apparently the backend sometimes sends repeat events
  384. if last == received {
  385. continue
  386. }
  387. if _, ok := expected[received]; !ok {
  388. if len(allowedEvents) > 0 {
  389. sleepMs(100) // To facilitate overflow
  390. continue
  391. }
  392. t.Errorf("Received unexpected event %v expected one of %v", received, expected)
  393. cancel()
  394. return
  395. }
  396. delete(expected, received)
  397. last = received
  398. }
  399. }
  400. // Matches are done via direct comparison against both ignore and include
  401. type fakeMatcher struct {
  402. ignore string
  403. include string
  404. skipIgnoredDirs bool
  405. }
  406. func (fm fakeMatcher) ShouldIgnore(name string) bool {
  407. return name != fm.include && name == fm.ignore
  408. }
  409. func (fm fakeMatcher) SkipIgnoredDirs() bool {
  410. return fm.skipIgnoredDirs
  411. }
  412. type fakeEventInfo string
  413. func (e fakeEventInfo) Path() string {
  414. return string(e)
  415. }
  416. func (e fakeEventInfo) Event() notify.Event {
  417. return notify.Write
  418. }
  419. func (e fakeEventInfo) Sys() interface{} {
  420. return nil
  421. }