watcher_naive.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. //go:build !darwin
  2. // +build !darwin
  3. /*
  4. Copyright 2020 Docker Compose CLI authors
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. */
  15. package watch
  16. import (
  17. "fmt"
  18. "io/fs"
  19. "os"
  20. "path/filepath"
  21. "runtime"
  22. "strings"
  23. "github.com/sirupsen/logrus"
  24. "github.com/tilt-dev/fsnotify"
  25. )
  26. // A naive file watcher that uses the plain fsnotify API.
  27. // Used on all non-Darwin systems (including Windows & Linux).
  28. //
  29. // All OS-specific codepaths are handled by fsnotify.
  30. type naiveNotify struct {
  31. // Paths that we're watching that should be passed up to the caller.
  32. // Note that we may have to watch ancestors of these paths
  33. // in order to fulfill the API promise.
  34. //
  35. // We often need to check if paths are a child of a path in
  36. // the notify list. It might be better to store this in a tree
  37. // structure, so we can filter the list quickly.
  38. notifyList map[string]bool
  39. ignore PathMatcher
  40. isWatcherRecursive bool
  41. watcher *fsnotify.Watcher
  42. events chan fsnotify.Event
  43. wrappedEvents chan FileEvent
  44. errors chan error
  45. numWatches int64
  46. }
  47. func (d *naiveNotify) Start() error {
  48. if len(d.notifyList) == 0 {
  49. return nil
  50. }
  51. pathsToWatch := []string{}
  52. for path := range d.notifyList {
  53. pathsToWatch = append(pathsToWatch, path)
  54. }
  55. pathsToWatch, err := greatestExistingAncestors(pathsToWatch)
  56. if err != nil {
  57. return err
  58. }
  59. if d.isWatcherRecursive {
  60. pathsToWatch = dedupePathsForRecursiveWatcher(pathsToWatch)
  61. }
  62. for _, name := range pathsToWatch {
  63. fi, err := os.Stat(name)
  64. if err != nil && !os.IsNotExist(err) {
  65. return fmt.Errorf("notify.Add(%q): %w", name, err)
  66. }
  67. // if it's a file that doesn't exist,
  68. // we should have caught that above, let's just skip it.
  69. if os.IsNotExist(err) {
  70. continue
  71. }
  72. if fi.IsDir() {
  73. err = d.watchRecursively(name)
  74. if err != nil {
  75. return fmt.Errorf("notify.Add(%q): %w", name, err)
  76. }
  77. } else {
  78. err = d.add(filepath.Dir(name))
  79. if err != nil {
  80. return fmt.Errorf("notify.Add(%q): %w", filepath.Dir(name), err)
  81. }
  82. }
  83. }
  84. go d.loop()
  85. return nil
  86. }
  87. func (d *naiveNotify) watchRecursively(dir string) error {
  88. if d.isWatcherRecursive {
  89. err := d.add(dir)
  90. if err == nil || os.IsNotExist(err) {
  91. return nil
  92. }
  93. return fmt.Errorf("watcher.Add(%q): %w", dir, err)
  94. }
  95. return filepath.WalkDir(dir, func(path string, info fs.DirEntry, err error) error {
  96. if err != nil {
  97. return err
  98. }
  99. if !info.IsDir() {
  100. return nil
  101. }
  102. shouldSkipDir, err := d.shouldSkipDir(path)
  103. if err != nil {
  104. return err
  105. }
  106. if shouldSkipDir {
  107. logrus.Debugf("Ignoring directory and its contents (recursively): %s", path)
  108. return filepath.SkipDir
  109. }
  110. err = d.add(path)
  111. if err != nil {
  112. if os.IsNotExist(err) {
  113. return nil
  114. }
  115. return fmt.Errorf("watcher.Add(%q): %w", path, err)
  116. }
  117. return nil
  118. })
  119. }
  120. func (d *naiveNotify) Close() error {
  121. numberOfWatches.Add(-d.numWatches)
  122. d.numWatches = 0
  123. return d.watcher.Close()
  124. }
  125. func (d *naiveNotify) Events() chan FileEvent {
  126. return d.wrappedEvents
  127. }
  128. func (d *naiveNotify) Errors() chan error {
  129. return d.errors
  130. }
  131. func (d *naiveNotify) loop() { //nolint:gocyclo
  132. defer close(d.wrappedEvents)
  133. for e := range d.events {
  134. // The Windows fsnotify event stream sometimes gets events with empty names
  135. // that are also sent to the error stream. Hmmmm...
  136. if e.Name == "" {
  137. continue
  138. }
  139. if e.Op&fsnotify.Create != fsnotify.Create {
  140. if d.shouldNotify(e.Name) {
  141. d.wrappedEvents <- FileEvent{e.Name}
  142. }
  143. continue
  144. }
  145. if d.isWatcherRecursive {
  146. if d.shouldNotify(e.Name) {
  147. d.wrappedEvents <- FileEvent{e.Name}
  148. }
  149. continue
  150. }
  151. // If the watcher is not recursive, we have to walk the tree
  152. // and add watches manually. We fire the event while we're walking the tree.
  153. // because it's a bit more elegant that way.
  154. //
  155. // TODO(dbentley): if there's a delete should we call d.watcher.Remove to prevent leaking?
  156. err := filepath.WalkDir(e.Name, func(path string, info fs.DirEntry, err error) error {
  157. if err != nil {
  158. return err
  159. }
  160. if d.shouldNotify(path) {
  161. d.wrappedEvents <- FileEvent{path}
  162. }
  163. // TODO(dmiller): symlinks 😭
  164. shouldWatch := false
  165. if info.IsDir() {
  166. // watch directories unless we can skip them entirely
  167. shouldSkipDir, err := d.shouldSkipDir(path)
  168. if err != nil {
  169. return err
  170. }
  171. if shouldSkipDir {
  172. return filepath.SkipDir
  173. }
  174. shouldWatch = true
  175. } else {
  176. // watch files that are explicitly named, but don't watch others
  177. _, ok := d.notifyList[path]
  178. if ok {
  179. shouldWatch = true
  180. }
  181. }
  182. if shouldWatch {
  183. err := d.add(path)
  184. if err != nil && !os.IsNotExist(err) {
  185. logrus.Infof("Error watching path %s: %s", e.Name, err)
  186. }
  187. }
  188. return nil
  189. })
  190. if err != nil && !os.IsNotExist(err) {
  191. logrus.Infof("Error walking directory %s: %s", e.Name, err)
  192. }
  193. }
  194. }
  195. func (d *naiveNotify) shouldNotify(path string) bool {
  196. ignore, err := d.ignore.Matches(path)
  197. if err != nil {
  198. logrus.Infof("Error matching path %q: %v", path, err)
  199. } else if ignore {
  200. logrus.Tracef("Ignoring event for path: %v", path)
  201. return false
  202. }
  203. if _, ok := d.notifyList[path]; ok {
  204. // We generally don't care when directories change at the root of an ADD
  205. stat, err := os.Lstat(path)
  206. isDir := err == nil && stat.IsDir()
  207. return !isDir
  208. }
  209. for root := range d.notifyList {
  210. if IsChild(root, path) {
  211. return true
  212. }
  213. }
  214. return false
  215. }
  216. func (d *naiveNotify) shouldSkipDir(path string) (bool, error) {
  217. // If path is directly in the notifyList, we should always watch it.
  218. if d.notifyList[path] {
  219. return false, nil
  220. }
  221. skip, err := d.ignore.MatchesEntireDir(path)
  222. if err != nil {
  223. return false, fmt.Errorf("shouldSkipDir: %w", err)
  224. }
  225. if skip {
  226. return true, nil
  227. }
  228. // Suppose we're watching
  229. // /src/.tiltignore
  230. // but the .tiltignore file doesn't exist.
  231. //
  232. // Our watcher will create an inotify watch on /src/.
  233. //
  234. // But then we want to make sure we don't recurse from /src/ down to /src/node_modules.
  235. //
  236. // To handle this case, we only want to traverse dirs that are:
  237. // - A child of a directory that's in our notify list, or
  238. // - A parent of a directory that's in our notify list
  239. // (i.e., to cover the "path doesn't exist" case).
  240. for root := range d.notifyList {
  241. if IsChild(root, path) || IsChild(path, root) {
  242. return false, nil
  243. }
  244. }
  245. return true, nil
  246. }
  247. func (d *naiveNotify) add(path string) error {
  248. err := d.watcher.Add(path)
  249. if err != nil {
  250. return err
  251. }
  252. d.numWatches++
  253. numberOfWatches.Add(1)
  254. return nil
  255. }
  256. func newWatcher(paths []string, ignore PathMatcher) (Notify, error) {
  257. if ignore == nil {
  258. return nil, fmt.Errorf("newWatcher: ignore is nil")
  259. }
  260. fsw, err := fsnotify.NewWatcher()
  261. if err != nil {
  262. if strings.Contains(err.Error(), "too many open files") && runtime.GOOS == "linux" {
  263. return nil, fmt.Errorf("Hit OS limits creating a watcher.\n" +
  264. "Run 'sysctl fs.inotify.max_user_instances' to check your inotify limits.\n" +
  265. "To raise them, run 'sudo sysctl fs.inotify.max_user_instances=1024'")
  266. }
  267. return nil, fmt.Errorf("creating file watcher: %w", err)
  268. }
  269. MaybeIncreaseBufferSize(fsw)
  270. err = fsw.SetRecursive()
  271. isWatcherRecursive := err == nil
  272. wrappedEvents := make(chan FileEvent)
  273. notifyList := make(map[string]bool, len(paths))
  274. if isWatcherRecursive {
  275. paths = dedupePathsForRecursiveWatcher(paths)
  276. }
  277. for _, path := range paths {
  278. path, err := filepath.Abs(path)
  279. if err != nil {
  280. return nil, fmt.Errorf("newWatcher: %w", err)
  281. }
  282. notifyList[path] = true
  283. }
  284. wmw := &naiveNotify{
  285. notifyList: notifyList,
  286. ignore: ignore,
  287. watcher: fsw,
  288. events: fsw.Events,
  289. wrappedEvents: wrappedEvents,
  290. errors: fsw.Errors,
  291. isWatcherRecursive: isWatcherRecursive,
  292. }
  293. return wmw, nil
  294. }
  295. var _ Notify = &naiveNotify{}
  296. func greatestExistingAncestors(paths []string) ([]string, error) {
  297. result := []string{}
  298. for _, p := range paths {
  299. newP, err := greatestExistingAncestor(p)
  300. if err != nil {
  301. return nil, fmt.Errorf("Finding ancestor of %s: %w", p, err)
  302. }
  303. result = append(result, newP)
  304. }
  305. return result, nil
  306. }