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