basicfs_watch_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. "syscall"
  17. "testing"
  18. "time"
  19. "github.com/syncthing/notify"
  20. )
  21. func TestMain(m *testing.M) {
  22. if err := os.RemoveAll(testDir); err != nil {
  23. panic(err)
  24. }
  25. dir, err := filepath.Abs(".")
  26. if err != nil {
  27. panic("Cannot get absolute path to working dir")
  28. }
  29. dir, err = filepath.EvalSymlinks(dir)
  30. if err != nil {
  31. panic("Cannot get real path to working dir")
  32. }
  33. testDirAbs = filepath.Join(dir, testDir)
  34. testFs = NewFilesystem(FilesystemTypeBasic, testDirAbs)
  35. backendBuffer = 10
  36. defer func() {
  37. backendBuffer = 500
  38. os.RemoveAll(testDir)
  39. }()
  40. os.Exit(m.Run())
  41. }
  42. const (
  43. testDir = "temporary_test_root"
  44. )
  45. var (
  46. testDirAbs string
  47. testFs Filesystem
  48. )
  49. func TestWatchIgnore(t *testing.T) {
  50. name := "ignore"
  51. file := "file"
  52. ignored := "ignored"
  53. testCase := func() {
  54. createTestFile(name, file)
  55. createTestFile(name, ignored)
  56. }
  57. expectedEvents := []Event{
  58. {file, NonRemove},
  59. }
  60. allowedEvents := []Event{
  61. {name, NonRemove},
  62. }
  63. testScenario(t, name, testCase, expectedEvents, allowedEvents, ignored)
  64. }
  65. func TestWatchRename(t *testing.T) {
  66. name := "rename"
  67. old := createTestFile(name, "oldfile")
  68. new := "newfile"
  69. testCase := func() {
  70. renameTestFile(name, old, new)
  71. }
  72. destEvent := Event{new, Remove}
  73. // Only on these platforms the removed file can be differentiated from
  74. // the created file during renaming
  75. if runtime.GOOS == "windows" || runtime.GOOS == "linux" || runtime.GOOS == "solaris" {
  76. destEvent = Event{new, NonRemove}
  77. }
  78. expectedEvents := []Event{
  79. {old, Remove},
  80. destEvent,
  81. }
  82. allowedEvents := []Event{
  83. {name, NonRemove},
  84. }
  85. // set the "allow others" flag because we might get the create of
  86. // "oldfile" initially
  87. testScenario(t, name, testCase, expectedEvents, allowedEvents, "")
  88. }
  89. // TestWatchOutside checks that no changes from outside the folder make it in
  90. func TestWatchOutside(t *testing.T) {
  91. outChan := make(chan Event)
  92. backendChan := make(chan notify.EventInfo, backendBuffer)
  93. ctx, cancel := context.WithCancel(context.Background())
  94. // testFs is Filesystem, but we need BasicFilesystem here
  95. fs := newBasicFilesystem(testDirAbs)
  96. go func() {
  97. defer func() {
  98. if recover() == nil {
  99. t.Fatalf("Watch did not panic on receiving event outside of folder")
  100. }
  101. cancel()
  102. }()
  103. fs.watchLoop(".", testDirAbs, backendChan, outChan, fakeMatcher{}, ctx)
  104. }()
  105. backendChan <- fakeEventInfo(filepath.Join(filepath.Dir(testDirAbs), "outside"))
  106. }
  107. func TestWatchSubpath(t *testing.T) {
  108. outChan := make(chan Event)
  109. backendChan := make(chan notify.EventInfo, backendBuffer)
  110. ctx, cancel := context.WithCancel(context.Background())
  111. // testFs is Filesystem, but we need BasicFilesystem here
  112. fs := newBasicFilesystem(testDirAbs)
  113. abs, _ := fs.rooted("sub")
  114. go fs.watchLoop("sub", abs, backendChan, outChan, fakeMatcher{}, ctx)
  115. backendChan <- fakeEventInfo(filepath.Join(abs, "file"))
  116. timeout := time.NewTimer(2 * time.Second)
  117. select {
  118. case <-timeout.C:
  119. t.Errorf("Timed out before receiving an event")
  120. cancel()
  121. case ev := <-outChan:
  122. if ev.Name != filepath.Join("sub", "file") {
  123. t.Errorf("While watching a subfolder, received an event with unexpected path %v", ev.Name)
  124. }
  125. }
  126. cancel()
  127. }
  128. // TestWatchOverflow checks that an event at the root is sent when maxFiles is reached
  129. func TestWatchOverflow(t *testing.T) {
  130. name := "overflow"
  131. expectedEvents := []Event{
  132. {".", NonRemove},
  133. }
  134. allowedEvents := []Event{
  135. {name, NonRemove},
  136. }
  137. testCase := func() {
  138. for i := 0; i < 5*backendBuffer; i++ {
  139. file := "file" + strconv.Itoa(i)
  140. createTestFile(name, file)
  141. allowedEvents = append(allowedEvents, Event{file, NonRemove})
  142. }
  143. }
  144. testScenario(t, name, testCase, expectedEvents, allowedEvents, "")
  145. }
  146. func TestWatchErrorLinuxInterpretation(t *testing.T) {
  147. if runtime.GOOS != "linux" {
  148. t.Skip("testing of linux specific error codes")
  149. }
  150. var errTooManyFiles = &os.PathError{
  151. Op: "error while traversing",
  152. Path: "foo",
  153. Err: syscall.Errno(24),
  154. }
  155. var errNoSpace = &os.PathError{
  156. Op: "error while traversing",
  157. Path: "bar",
  158. Err: syscall.Errno(28),
  159. }
  160. if !reachedMaxUserWatches(errTooManyFiles) {
  161. t.Error("Underlying error syscall.Errno(24) should be recognised to be about inotify limits.")
  162. }
  163. if !reachedMaxUserWatches(errNoSpace) {
  164. t.Error("Underlying error syscall.Errno(28) should be recognised to be about inotify limits.")
  165. }
  166. err := errors.New("Another error")
  167. if reachedMaxUserWatches(err) {
  168. t.Errorf("This error does not concern inotify limits: %#v", err)
  169. }
  170. }
  171. // path relative to folder root, also creates parent dirs if necessary
  172. func createTestFile(name string, file string) string {
  173. joined := filepath.Join(name, file)
  174. if err := testFs.MkdirAll(filepath.Dir(joined), 0755); err != nil {
  175. panic(fmt.Sprintf("Failed to create parent directory for %s: %s", joined, err))
  176. }
  177. handle, err := testFs.Create(joined)
  178. if err != nil {
  179. panic(fmt.Sprintf("Failed to create test file %s: %s", joined, err))
  180. }
  181. handle.Close()
  182. return file
  183. }
  184. func renameTestFile(name string, old string, new string) {
  185. old = filepath.Join(name, old)
  186. new = filepath.Join(name, new)
  187. if err := testFs.Rename(old, new); err != nil {
  188. panic(fmt.Sprintf("Failed to rename %s to %s: %s", old, new, err))
  189. }
  190. }
  191. func sleepMs(ms int) {
  192. time.Sleep(time.Duration(ms) * time.Millisecond)
  193. }
  194. func testScenario(t *testing.T, name string, testCase func(), expectedEvents, allowedEvents []Event, ignored string) {
  195. if err := testFs.MkdirAll(name, 0755); err != nil {
  196. panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
  197. }
  198. defer testFs.RemoveAll(name)
  199. ctx, cancel := context.WithCancel(context.Background())
  200. defer cancel()
  201. if ignored != "" {
  202. ignored = filepath.Join(name, ignored)
  203. }
  204. eventChan, err := testFs.Watch(name, fakeMatcher{ignored}, ctx, false)
  205. if err != nil {
  206. panic(err)
  207. }
  208. go testWatchOutput(t, name, eventChan, expectedEvents, allowedEvents, ctx, cancel)
  209. testCase()
  210. select {
  211. case <-time.NewTimer(time.Minute).C:
  212. t.Errorf("Timed out before receiving all expected events")
  213. case <-ctx.Done():
  214. }
  215. }
  216. func testWatchOutput(t *testing.T, name string, in <-chan Event, expectedEvents, allowedEvents []Event, ctx context.Context, cancel context.CancelFunc) {
  217. var expected = make(map[Event]struct{})
  218. for _, ev := range expectedEvents {
  219. ev.Name = filepath.Join(name, ev.Name)
  220. expected[ev] = struct{}{}
  221. }
  222. var received Event
  223. var last Event
  224. for {
  225. if len(expected) == 0 {
  226. cancel()
  227. return
  228. }
  229. select {
  230. case <-ctx.Done():
  231. return
  232. case received = <-in:
  233. }
  234. // apparently the backend sometimes sends repeat events
  235. if last == received {
  236. continue
  237. }
  238. if _, ok := expected[received]; !ok {
  239. if len(allowedEvents) > 0 {
  240. sleepMs(100) // To facilitate overflow
  241. continue
  242. }
  243. t.Errorf("Received unexpected event %v expected one of %v", received, expected)
  244. cancel()
  245. return
  246. }
  247. delete(expected, received)
  248. last = received
  249. }
  250. }
  251. type fakeMatcher struct{ match string }
  252. func (fm fakeMatcher) ShouldIgnore(name string) bool {
  253. return name == fm.match
  254. }
  255. type fakeEventInfo string
  256. func (e fakeEventInfo) Path() string {
  257. return string(e)
  258. }
  259. func (e fakeEventInfo) Event() notify.Event {
  260. return notify.Write
  261. }
  262. func (e fakeEventInfo) Sys() interface{} {
  263. return nil
  264. }