notify_test.go 14 KB

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