basicfs_watch_test.go 10 KB

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