basicfs_watch_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. // TestWatchOutside checks that no changes from outside the folder make it in
  122. func TestWatchOutside(t *testing.T) {
  123. outChan := make(chan Event)
  124. backendChan := make(chan notify.EventInfo, backendBuffer)
  125. ctx, cancel := context.WithCancel(context.Background())
  126. // testFs is Filesystem, but we need BasicFilesystem here
  127. fs := newBasicFilesystem(testDirAbs)
  128. go func() {
  129. defer func() {
  130. if recover() == nil {
  131. select {
  132. case <-ctx.Done(): // timed out
  133. default:
  134. t.Fatalf("Watch did not panic on receiving event outside of folder")
  135. }
  136. }
  137. cancel()
  138. }()
  139. fs.watchLoop(".", testDirAbs, backendChan, outChan, fakeMatcher{}, ctx)
  140. }()
  141. backendChan <- fakeEventInfo(filepath.Join(filepath.Dir(testDirAbs), "outside"))
  142. select {
  143. case <-time.After(10 * time.Second):
  144. cancel()
  145. t.Errorf("Timed out before panicing")
  146. case <-ctx.Done():
  147. }
  148. }
  149. func TestWatchSubpath(t *testing.T) {
  150. outChan := make(chan Event)
  151. backendChan := make(chan notify.EventInfo, backendBuffer)
  152. ctx, cancel := context.WithCancel(context.Background())
  153. // testFs is Filesystem, but we need BasicFilesystem here
  154. fs := newBasicFilesystem(testDirAbs)
  155. abs, _ := fs.rooted("sub")
  156. go fs.watchLoop("sub", testDirAbs, backendChan, outChan, fakeMatcher{}, ctx)
  157. backendChan <- fakeEventInfo(filepath.Join(abs, "file"))
  158. timeout := time.NewTimer(2 * time.Second)
  159. select {
  160. case <-timeout.C:
  161. t.Errorf("Timed out before receiving an event")
  162. cancel()
  163. case ev := <-outChan:
  164. if ev.Name != filepath.Join("sub", "file") {
  165. t.Errorf("While watching a subfolder, received an event with unexpected path %v", ev.Name)
  166. }
  167. }
  168. cancel()
  169. }
  170. // TestWatchOverflow checks that an event at the root is sent when maxFiles is reached
  171. func TestWatchOverflow(t *testing.T) {
  172. if runtime.GOOS == "openbsd" {
  173. t.Skip(failsOnOpenBSD)
  174. }
  175. name := "overflow"
  176. expectedEvents := []Event{
  177. {".", NonRemove},
  178. }
  179. allowedEvents := []Event{
  180. {name, NonRemove},
  181. }
  182. testCase := func() {
  183. for i := 0; i < 5*backendBuffer; i++ {
  184. file := "file" + strconv.Itoa(i)
  185. createTestFile(name, file)
  186. allowedEvents = append(allowedEvents, Event{file, NonRemove})
  187. }
  188. }
  189. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
  190. }
  191. func TestWatchErrorLinuxInterpretation(t *testing.T) {
  192. if runtime.GOOS != "linux" {
  193. t.Skip("testing of linux specific error codes")
  194. }
  195. var errTooManyFiles = &os.PathError{
  196. Op: "error while traversing",
  197. Path: "foo",
  198. Err: syscall.Errno(24),
  199. }
  200. var errNoSpace = &os.PathError{
  201. Op: "error while traversing",
  202. Path: "bar",
  203. Err: syscall.Errno(28),
  204. }
  205. if !reachedMaxUserWatches(errTooManyFiles) {
  206. t.Error("Underlying error syscall.Errno(24) should be recognised to be about inotify limits.")
  207. }
  208. if !reachedMaxUserWatches(errNoSpace) {
  209. t.Error("Underlying error syscall.Errno(28) should be recognised to be about inotify limits.")
  210. }
  211. err := errors.New("Another error")
  212. if reachedMaxUserWatches(err) {
  213. t.Errorf("This error does not concern inotify limits: %#v", err)
  214. }
  215. }
  216. func TestWatchSymlinkedRoot(t *testing.T) {
  217. if runtime.GOOS == "windows" {
  218. t.Skip("Involves symlinks")
  219. }
  220. name := "symlinkedRoot"
  221. if err := testFs.MkdirAll(name, 0755); err != nil {
  222. panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
  223. }
  224. defer testFs.RemoveAll(name)
  225. root := filepath.Join(name, "root")
  226. if err := testFs.MkdirAll(root, 0777); err != nil {
  227. panic(err)
  228. }
  229. link := filepath.Join(name, "link")
  230. if err := testFs.CreateSymlink(filepath.Join(testFs.URI(), root), link); err != nil {
  231. panic(err)
  232. }
  233. linkedFs := NewFilesystem(FilesystemTypeBasic, filepath.Join(testFs.URI(), link))
  234. ctx, cancel := context.WithCancel(context.Background())
  235. defer cancel()
  236. if _, err := linkedFs.Watch(".", fakeMatcher{}, ctx, false); err != nil {
  237. panic(err)
  238. }
  239. if err := linkedFs.MkdirAll("foo", 0777); err != nil {
  240. panic(err)
  241. }
  242. // Give the panic some time to happen
  243. sleepMs(100)
  244. }
  245. func TestUnrootedChecked(t *testing.T) {
  246. var unrooted string
  247. defer func() {
  248. if recover() == nil {
  249. t.Fatal("unrootedChecked did not panic on outside path, but returned", unrooted)
  250. }
  251. }()
  252. fs := newBasicFilesystem(testDirAbs)
  253. unrooted = fs.unrootedChecked("/random/other/path", testDirAbs)
  254. }
  255. func TestWatchIssue4877(t *testing.T) {
  256. if runtime.GOOS != "windows" {
  257. t.Skip("Windows specific test")
  258. }
  259. name := "Issue4877"
  260. file := "file"
  261. testCase := func() {
  262. createTestFile(name, file)
  263. }
  264. expectedEvents := []Event{
  265. {file, NonRemove},
  266. }
  267. allowedEvents := []Event{
  268. {name, NonRemove},
  269. }
  270. volName := filepath.VolumeName(testDirAbs)
  271. if volName == "" {
  272. t.Fatalf("Failed to get volume name for path %v", testDirAbs)
  273. }
  274. origTestFs := testFs
  275. testFs = NewFilesystem(FilesystemTypeBasic, strings.ToLower(volName)+strings.ToUpper(testDirAbs[len(volName):]))
  276. defer func() {
  277. testFs = origTestFs
  278. }()
  279. testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
  280. }
  281. // path relative to folder root, also creates parent dirs if necessary
  282. func createTestFile(name string, file string) string {
  283. joined := filepath.Join(name, file)
  284. if err := testFs.MkdirAll(filepath.Dir(joined), 0755); err != nil {
  285. panic(fmt.Sprintf("Failed to create parent directory for %s: %s", joined, err))
  286. }
  287. handle, err := testFs.Create(joined)
  288. if err != nil {
  289. panic(fmt.Sprintf("Failed to create test file %s: %s", joined, err))
  290. }
  291. handle.Close()
  292. return file
  293. }
  294. func renameTestFile(name string, old string, new string) {
  295. old = filepath.Join(name, old)
  296. new = filepath.Join(name, new)
  297. if err := testFs.Rename(old, new); err != nil {
  298. panic(fmt.Sprintf("Failed to rename %s to %s: %s", old, new, err))
  299. }
  300. }
  301. func sleepMs(ms int) {
  302. time.Sleep(time.Duration(ms) * time.Millisecond)
  303. }
  304. func testScenario(t *testing.T, name string, testCase func(), expectedEvents, allowedEvents []Event, fm fakeMatcher) {
  305. if err := testFs.MkdirAll(name, 0755); err != nil {
  306. panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
  307. }
  308. defer testFs.RemoveAll(name)
  309. ctx, cancel := context.WithCancel(context.Background())
  310. defer cancel()
  311. eventChan, err := testFs.Watch(name, fm, ctx, false)
  312. if err != nil {
  313. panic(err)
  314. }
  315. go testWatchOutput(t, name, eventChan, expectedEvents, allowedEvents, ctx, cancel)
  316. testCase()
  317. select {
  318. case <-time.After(time.Minute):
  319. t.Errorf("Timed out before receiving all expected events")
  320. case <-ctx.Done():
  321. }
  322. }
  323. func testWatchOutput(t *testing.T, name string, in <-chan Event, expectedEvents, allowedEvents []Event, ctx context.Context, cancel context.CancelFunc) {
  324. var expected = make(map[Event]struct{})
  325. for _, ev := range expectedEvents {
  326. ev.Name = filepath.Join(name, ev.Name)
  327. expected[ev] = struct{}{}
  328. }
  329. var received Event
  330. var last Event
  331. for {
  332. if len(expected) == 0 {
  333. cancel()
  334. return
  335. }
  336. select {
  337. case <-ctx.Done():
  338. return
  339. case received = <-in:
  340. }
  341. // apparently the backend sometimes sends repeat events
  342. if last == received {
  343. continue
  344. }
  345. if _, ok := expected[received]; !ok {
  346. if len(allowedEvents) > 0 {
  347. sleepMs(100) // To facilitate overflow
  348. continue
  349. }
  350. t.Errorf("Received unexpected event %v expected one of %v", received, expected)
  351. cancel()
  352. return
  353. }
  354. delete(expected, received)
  355. last = received
  356. }
  357. }
  358. // Matches are done via direct comparison against both ignore and include
  359. type fakeMatcher struct {
  360. ignore string
  361. include string
  362. skipIgnoredDirs bool
  363. }
  364. func (fm fakeMatcher) ShouldIgnore(name string) bool {
  365. return name != fm.include && name == fm.ignore
  366. }
  367. func (fm fakeMatcher) SkipIgnoredDirs() bool {
  368. return fm.skipIgnoredDirs
  369. }
  370. type fakeEventInfo string
  371. func (e fakeEventInfo) Path() string {
  372. return string(e)
  373. }
  374. func (e fakeEventInfo) Event() notify.Event {
  375. return notify.Write
  376. }
  377. func (e fakeEventInfo) Sys() interface{} {
  378. return nil
  379. }