notify_test.go 12 KB

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