notify_test.go 15 KB

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