notify_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. package watch
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tilt-dev/tilt/internal/dockerignore"
  16. "github.com/tilt-dev/tilt/internal/testutils/tempdir"
  17. "github.com/tilt-dev/tilt/pkg/logger"
  18. )
  19. // Each implementation of the notify interface should have the same basic
  20. // behavior.
  21. func TestWindowsBufferSize(t *testing.T) {
  22. orig := os.Getenv(WindowsBufferSizeEnvVar)
  23. defer os.Setenv(WindowsBufferSizeEnvVar, orig)
  24. os.Setenv(WindowsBufferSizeEnvVar, "")
  25. assert.Equal(t, defaultBufferSize, DesiredWindowsBufferSize())
  26. os.Setenv(WindowsBufferSizeEnvVar, "a")
  27. assert.Equal(t, defaultBufferSize, DesiredWindowsBufferSize())
  28. os.Setenv(WindowsBufferSizeEnvVar, "10")
  29. assert.Equal(t, 10, DesiredWindowsBufferSize())
  30. }
  31. func TestNoEvents(t *testing.T) {
  32. f := newNotifyFixture(t)
  33. f.assertEvents()
  34. }
  35. func TestNoWatches(t *testing.T) {
  36. f := newNotifyFixture(t)
  37. f.paths = nil
  38. f.rebuildWatcher()
  39. f.assertEvents()
  40. }
  41. func TestEventOrdering(t *testing.T) {
  42. if runtime.GOOS == "windows" {
  43. // https://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw_19.html
  44. t.Skip("Windows doesn't make great guarantees about duplicate/out-of-order events")
  45. return
  46. }
  47. f := newNotifyFixture(t)
  48. count := 8
  49. dirs := make([]string, count)
  50. for i := range dirs {
  51. dir := f.TempDir("watched")
  52. dirs[i] = dir
  53. f.watch(dir)
  54. }
  55. f.fsync()
  56. f.events = nil
  57. var expected []string
  58. for i, dir := range dirs {
  59. base := fmt.Sprintf("%d.txt", i)
  60. p := filepath.Join(dir, base)
  61. err := ioutil.WriteFile(p, []byte(base), os.FileMode(0777))
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. expected = append(expected, filepath.Join(dir, base))
  66. }
  67. f.assertEvents(expected...)
  68. }
  69. // Simulate a git branch switch that creates a bunch
  70. // of directories, creates files in them, then deletes
  71. // them all quickly. Make sure there are no errors.
  72. func TestGitBranchSwitch(t *testing.T) {
  73. f := newNotifyFixture(t)
  74. count := 10
  75. dirs := make([]string, count)
  76. for i := range dirs {
  77. dir := f.TempDir("watched")
  78. dirs[i] = dir
  79. f.watch(dir)
  80. }
  81. f.fsync()
  82. f.events = nil
  83. // consume all the events in the background
  84. ctx, cancel := context.WithCancel(context.Background())
  85. done := f.consumeEventsInBackground(ctx)
  86. for i, dir := range dirs {
  87. for j := 0; j < count; j++ {
  88. base := fmt.Sprintf("x/y/dir-%d/x.txt", j)
  89. p := filepath.Join(dir, base)
  90. f.WriteFile(p, "contents")
  91. }
  92. if i != 0 {
  93. err := os.RemoveAll(dir)
  94. require.NoError(t, err)
  95. }
  96. }
  97. cancel()
  98. err := <-done
  99. if err != nil {
  100. t.Fatal(err)
  101. }
  102. f.fsync()
  103. f.events = nil
  104. // Make sure the watch on the first dir still works.
  105. dir := dirs[0]
  106. path := filepath.Join(dir, "change")
  107. f.WriteFile(path, "hello\n")
  108. f.fsync()
  109. f.assertEvents(path)
  110. // Make sure there are no errors in the out stream
  111. assert.Equal(t, "", f.out.String())
  112. }
  113. func TestWatchesAreRecursive(t *testing.T) {
  114. f := newNotifyFixture(t)
  115. root := f.TempDir("root")
  116. // add a sub directory
  117. subPath := filepath.Join(root, "sub")
  118. f.MkdirAll(subPath)
  119. // watch parent
  120. f.watch(root)
  121. f.fsync()
  122. f.events = nil
  123. // change sub directory
  124. changeFilePath := filepath.Join(subPath, "change")
  125. f.WriteFile(changeFilePath, "change")
  126. f.assertEvents(changeFilePath)
  127. }
  128. func TestNewDirectoriesAreRecursivelyWatched(t *testing.T) {
  129. f := newNotifyFixture(t)
  130. root := f.TempDir("root")
  131. // watch parent
  132. f.watch(root)
  133. f.fsync()
  134. f.events = nil
  135. // add a sub directory
  136. subPath := filepath.Join(root, "sub")
  137. f.MkdirAll(subPath)
  138. // change something inside sub directory
  139. changeFilePath := filepath.Join(subPath, "change")
  140. file, err := os.OpenFile(changeFilePath, os.O_RDONLY|os.O_CREATE, 0666)
  141. if err != nil {
  142. t.Fatal(err)
  143. }
  144. _ = file.Close()
  145. f.assertEvents(subPath, changeFilePath)
  146. }
  147. func TestWatchNonExistentPath(t *testing.T) {
  148. f := newNotifyFixture(t)
  149. root := f.TempDir("root")
  150. path := filepath.Join(root, "change")
  151. f.watch(path)
  152. f.fsync()
  153. d1 := "hello\ngo\n"
  154. f.WriteFile(path, d1)
  155. f.assertEvents(path)
  156. }
  157. func TestWatchNonExistentPathDoesNotFireSiblingEvent(t *testing.T) {
  158. f := newNotifyFixture(t)
  159. root := f.TempDir("root")
  160. watchedFile := filepath.Join(root, "a.txt")
  161. unwatchedSibling := filepath.Join(root, "b.txt")
  162. f.watch(watchedFile)
  163. f.fsync()
  164. d1 := "hello\ngo\n"
  165. f.WriteFile(unwatchedSibling, d1)
  166. f.assertEvents()
  167. }
  168. func TestRemove(t *testing.T) {
  169. f := newNotifyFixture(t)
  170. root := f.TempDir("root")
  171. path := filepath.Join(root, "change")
  172. d1 := "hello\ngo\n"
  173. f.WriteFile(path, d1)
  174. f.watch(path)
  175. f.fsync()
  176. f.events = nil
  177. err := os.Remove(path)
  178. if err != nil {
  179. t.Fatal(err)
  180. }
  181. f.assertEvents(path)
  182. }
  183. func TestRemoveAndAddBack(t *testing.T) {
  184. f := newNotifyFixture(t)
  185. path := filepath.Join(f.paths[0], "change")
  186. d1 := []byte("hello\ngo\n")
  187. err := ioutil.WriteFile(path, d1, 0644)
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. f.watch(path)
  192. f.assertEvents(path)
  193. err = os.Remove(path)
  194. if err != nil {
  195. t.Fatal(err)
  196. }
  197. f.assertEvents(path)
  198. f.events = nil
  199. err = ioutil.WriteFile(path, d1, 0644)
  200. if err != nil {
  201. t.Fatal(err)
  202. }
  203. f.assertEvents(path)
  204. }
  205. func TestSingleFile(t *testing.T) {
  206. f := newNotifyFixture(t)
  207. root := f.TempDir("root")
  208. path := filepath.Join(root, "change")
  209. d1 := "hello\ngo\n"
  210. f.WriteFile(path, d1)
  211. f.watch(path)
  212. f.fsync()
  213. d2 := []byte("hello\nworld\n")
  214. err := ioutil.WriteFile(path, d2, 0644)
  215. if err != nil {
  216. t.Fatal(err)
  217. }
  218. f.assertEvents(path)
  219. }
  220. func TestWriteBrokenLink(t *testing.T) {
  221. if runtime.GOOS == "windows" {
  222. t.Skip("no user-space symlinks on windows")
  223. }
  224. f := newNotifyFixture(t)
  225. link := filepath.Join(f.paths[0], "brokenLink")
  226. missingFile := filepath.Join(f.paths[0], "missingFile")
  227. err := os.Symlink(missingFile, link)
  228. if err != nil {
  229. t.Fatal(err)
  230. }
  231. f.assertEvents(link)
  232. }
  233. func TestWriteGoodLink(t *testing.T) {
  234. if runtime.GOOS == "windows" {
  235. t.Skip("no user-space symlinks on windows")
  236. }
  237. f := newNotifyFixture(t)
  238. goodFile := filepath.Join(f.paths[0], "goodFile")
  239. err := ioutil.WriteFile(goodFile, []byte("hello"), 0644)
  240. if err != nil {
  241. t.Fatal(err)
  242. }
  243. link := filepath.Join(f.paths[0], "goodFileSymlink")
  244. err = os.Symlink(goodFile, link)
  245. if err != nil {
  246. t.Fatal(err)
  247. }
  248. f.assertEvents(goodFile, link)
  249. }
  250. func TestWatchBrokenLink(t *testing.T) {
  251. if runtime.GOOS == "windows" {
  252. t.Skip("no user-space symlinks on windows")
  253. }
  254. f := newNotifyFixture(t)
  255. newRoot, err := NewDir(t.Name())
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. defer func() {
  260. err := newRoot.TearDown()
  261. if err != nil {
  262. fmt.Printf("error tearing down temp dir: %v\n", err)
  263. }
  264. }()
  265. link := filepath.Join(newRoot.Path(), "brokenLink")
  266. missingFile := filepath.Join(newRoot.Path(), "missingFile")
  267. err = os.Symlink(missingFile, link)
  268. if err != nil {
  269. t.Fatal(err)
  270. }
  271. f.watch(newRoot.Path())
  272. err = os.Remove(link)
  273. require.NoError(t, err)
  274. f.assertEvents(link)
  275. }
  276. func TestMoveAndReplace(t *testing.T) {
  277. f := newNotifyFixture(t)
  278. root := f.TempDir("root")
  279. file := filepath.Join(root, "myfile")
  280. f.WriteFile(file, "hello")
  281. f.watch(file)
  282. tmpFile := filepath.Join(root, ".myfile.swp")
  283. f.WriteFile(tmpFile, "world")
  284. err := os.Rename(tmpFile, file)
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. f.assertEvents(file)
  289. }
  290. func TestWatchBothDirAndFile(t *testing.T) {
  291. f := newNotifyFixture(t)
  292. dir := f.JoinPath("foo")
  293. fileA := f.JoinPath("foo", "a")
  294. fileB := f.JoinPath("foo", "b")
  295. f.WriteFile(fileA, "a")
  296. f.WriteFile(fileB, "b")
  297. f.watch(fileA)
  298. f.watch(dir)
  299. f.fsync()
  300. f.events = nil
  301. f.WriteFile(fileB, "b-new")
  302. f.assertEvents(fileB)
  303. }
  304. func TestWatchNonexistentFileInNonexistentDirectoryCreatedSimultaneously(t *testing.T) {
  305. f := newNotifyFixture(t)
  306. root := f.JoinPath("root")
  307. err := os.Mkdir(root, 0777)
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. file := f.JoinPath("root", "parent", "a")
  312. f.watch(file)
  313. f.fsync()
  314. f.events = nil
  315. f.WriteFile(file, "hello")
  316. f.assertEvents(file)
  317. }
  318. func TestWatchNonexistentDirectory(t *testing.T) {
  319. f := newNotifyFixture(t)
  320. root := f.JoinPath("root")
  321. err := os.Mkdir(root, 0777)
  322. if err != nil {
  323. t.Fatal(err)
  324. }
  325. parent := f.JoinPath("parent")
  326. file := f.JoinPath("parent", "a")
  327. f.watch(parent)
  328. f.fsync()
  329. f.events = nil
  330. err = os.Mkdir(parent, 0777)
  331. if err != nil {
  332. t.Fatal(err)
  333. }
  334. // for directories that were the root of an Add, we don't report creation, cf. watcher_darwin.go
  335. f.assertEvents()
  336. f.events = nil
  337. f.WriteFile(file, "hello")
  338. f.assertEvents(file)
  339. }
  340. func TestWatchNonexistentFileInNonexistentDirectory(t *testing.T) {
  341. f := newNotifyFixture(t)
  342. root := f.JoinPath("root")
  343. err := os.Mkdir(root, 0777)
  344. if err != nil {
  345. t.Fatal(err)
  346. }
  347. parent := f.JoinPath("parent")
  348. file := f.JoinPath("parent", "a")
  349. f.watch(file)
  350. f.assertEvents()
  351. err = os.Mkdir(parent, 0777)
  352. if err != nil {
  353. t.Fatal(err)
  354. }
  355. f.assertEvents()
  356. f.WriteFile(file, "hello")
  357. f.assertEvents(file)
  358. }
  359. func TestWatchCountInnerFile(t *testing.T) {
  360. f := newNotifyFixture(t)
  361. root := f.paths[0]
  362. a := f.JoinPath(root, "a")
  363. b := f.JoinPath(a, "b")
  364. file := f.JoinPath(b, "bigFile")
  365. f.WriteFile(file, "hello")
  366. f.assertEvents(a, b, file)
  367. expectedWatches := 3
  368. if isRecursiveWatcher() {
  369. expectedWatches = 1
  370. }
  371. assert.Equal(t, expectedWatches, int(numberOfWatches.Value()))
  372. }
  373. func TestWatchCountInnerFileWithIgnore(t *testing.T) {
  374. f := newNotifyFixture(t)
  375. root := f.paths[0]
  376. ignore, _ := dockerignore.NewDockerPatternMatcher(root, []string{
  377. "a",
  378. "!a/b",
  379. })
  380. f.setIgnore(ignore)
  381. a := f.JoinPath(root, "a")
  382. b := f.JoinPath(a, "b")
  383. file := f.JoinPath(b, "bigFile")
  384. f.WriteFile(file, "hello")
  385. f.assertEvents(b, file)
  386. expectedWatches := 3
  387. if isRecursiveWatcher() {
  388. expectedWatches = 1
  389. }
  390. assert.Equal(t, expectedWatches, int(numberOfWatches.Value()))
  391. }
  392. func TestIgnoreCreatedDir(t *testing.T) {
  393. f := newNotifyFixture(t)
  394. root := f.paths[0]
  395. ignore, _ := dockerignore.NewDockerPatternMatcher(root, []string{"a/b"})
  396. f.setIgnore(ignore)
  397. a := f.JoinPath(root, "a")
  398. b := f.JoinPath(a, "b")
  399. file := f.JoinPath(b, "bigFile")
  400. f.WriteFile(file, "hello")
  401. f.assertEvents(a)
  402. expectedWatches := 2
  403. if isRecursiveWatcher() {
  404. expectedWatches = 1
  405. }
  406. assert.Equal(t, expectedWatches, int(numberOfWatches.Value()))
  407. }
  408. func TestIgnoreCreatedDirWithExclusions(t *testing.T) {
  409. f := newNotifyFixture(t)
  410. root := f.paths[0]
  411. ignore, _ := dockerignore.NewDockerPatternMatcher(root,
  412. []string{
  413. "a/b",
  414. "c",
  415. "!c/d",
  416. })
  417. f.setIgnore(ignore)
  418. a := f.JoinPath(root, "a")
  419. b := f.JoinPath(a, "b")
  420. file := f.JoinPath(b, "bigFile")
  421. f.WriteFile(file, "hello")
  422. f.assertEvents(a)
  423. expectedWatches := 2
  424. if isRecursiveWatcher() {
  425. expectedWatches = 1
  426. }
  427. assert.Equal(t, expectedWatches, int(numberOfWatches.Value()))
  428. }
  429. func TestIgnoreInitialDir(t *testing.T) {
  430. f := newNotifyFixture(t)
  431. root := f.TempDir("root")
  432. ignore, _ := dockerignore.NewDockerPatternMatcher(root, []string{"a/b"})
  433. f.setIgnore(ignore)
  434. a := f.JoinPath(root, "a")
  435. b := f.JoinPath(a, "b")
  436. file := f.JoinPath(b, "bigFile")
  437. f.WriteFile(file, "hello")
  438. f.watch(root)
  439. f.assertEvents()
  440. expectedWatches := 3
  441. if isRecursiveWatcher() {
  442. expectedWatches = 2
  443. }
  444. assert.Equal(t, expectedWatches, int(numberOfWatches.Value()))
  445. }
  446. func isRecursiveWatcher() bool {
  447. return runtime.GOOS == "darwin" || runtime.GOOS == "windows"
  448. }
  449. type notifyFixture struct {
  450. ctx context.Context
  451. cancel func()
  452. out *bytes.Buffer
  453. *tempdir.TempDirFixture
  454. notify Notify
  455. ignore PathMatcher
  456. paths []string
  457. events []FileEvent
  458. }
  459. func newNotifyFixture(t *testing.T) *notifyFixture {
  460. out := bytes.NewBuffer(nil)
  461. ctx, cancel := context.WithCancel(context.Background())
  462. nf := &notifyFixture{
  463. ctx: ctx,
  464. cancel: cancel,
  465. TempDirFixture: tempdir.NewTempDirFixture(t),
  466. paths: []string{},
  467. ignore: EmptyMatcher{},
  468. out: out,
  469. }
  470. nf.watch(nf.TempDir("watched"))
  471. t.Cleanup(nf.tearDown)
  472. return nf
  473. }
  474. func (f *notifyFixture) setIgnore(ignore PathMatcher) {
  475. f.ignore = ignore
  476. f.rebuildWatcher()
  477. }
  478. func (f *notifyFixture) watch(path string) {
  479. f.paths = append(f.paths, path)
  480. f.rebuildWatcher()
  481. }
  482. func (f *notifyFixture) rebuildWatcher() {
  483. // sync any outstanding events and close the old watcher
  484. if f.notify != nil {
  485. f.fsync()
  486. f.closeWatcher()
  487. }
  488. // create a new watcher
  489. notify, err := NewWatcher(f.paths, f.ignore, logger.NewTestLogger(f.out))
  490. if err != nil {
  491. f.T().Fatal(err)
  492. }
  493. f.notify = notify
  494. err = f.notify.Start()
  495. if err != nil {
  496. f.T().Fatal(err)
  497. }
  498. }
  499. func (f *notifyFixture) assertEvents(expected ...string) {
  500. f.fsync()
  501. if runtime.GOOS == "windows" {
  502. // NOTE(nick): It's unclear to me why an extra fsync() helps
  503. // here, but it makes the I/O way more predictable.
  504. f.fsync()
  505. }
  506. if len(f.events) != len(expected) {
  507. f.T().Fatalf("Got %d events (expected %d): %v %v", len(f.events), len(expected), f.events, expected)
  508. }
  509. for i, actual := range f.events {
  510. e := FileEvent{expected[i]}
  511. if actual != e {
  512. f.T().Fatalf("Got event %v (expected %v)", actual, e)
  513. }
  514. }
  515. }
  516. func (f *notifyFixture) consumeEventsInBackground(ctx context.Context) chan error {
  517. done := make(chan error)
  518. go func() {
  519. for {
  520. select {
  521. case <-f.ctx.Done():
  522. close(done)
  523. return
  524. case <-ctx.Done():
  525. close(done)
  526. return
  527. case err := <-f.notify.Errors():
  528. done <- err
  529. close(done)
  530. return
  531. case <-f.notify.Events():
  532. }
  533. }
  534. }()
  535. return done
  536. }
  537. func (f *notifyFixture) fsync() {
  538. f.fsyncWithRetryCount(3)
  539. }
  540. func (f *notifyFixture) fsyncWithRetryCount(retryCount int) {
  541. if len(f.paths) == 0 {
  542. return
  543. }
  544. syncPathBase := fmt.Sprintf("sync-%d.txt", time.Now().UnixNano())
  545. syncPath := filepath.Join(f.paths[0], syncPathBase)
  546. anySyncPath := filepath.Join(f.paths[0], "sync-")
  547. timeout := time.After(250 * time.Millisecond)
  548. f.WriteFile(syncPath, time.Now().String())
  549. F:
  550. for {
  551. select {
  552. case <-f.ctx.Done():
  553. return
  554. case err := <-f.notify.Errors():
  555. f.T().Fatal(err)
  556. case event := <-f.notify.Events():
  557. if strings.Contains(event.Path(), syncPath) {
  558. break F
  559. }
  560. if strings.Contains(event.Path(), anySyncPath) {
  561. continue
  562. }
  563. // Don't bother tracking duplicate changes to the same path
  564. // for testing.
  565. if len(f.events) > 0 && f.events[len(f.events)-1].Path() == event.Path() {
  566. continue
  567. }
  568. f.events = append(f.events, event)
  569. case <-timeout:
  570. if retryCount <= 0 {
  571. f.T().Fatalf("fsync: timeout")
  572. } else {
  573. f.fsyncWithRetryCount(retryCount - 1)
  574. }
  575. return
  576. }
  577. }
  578. }
  579. func (f *notifyFixture) closeWatcher() {
  580. notify := f.notify
  581. err := notify.Close()
  582. if err != nil {
  583. f.T().Fatal(err)
  584. }
  585. // drain channels from watcher
  586. go func() {
  587. for range notify.Events() {
  588. }
  589. }()
  590. go func() {
  591. for range notify.Errors() {
  592. }
  593. }()
  594. }
  595. func (f *notifyFixture) tearDown() {
  596. f.cancel()
  597. f.closeWatcher()
  598. numberOfWatches.Set(0)
  599. }