watcher_naive.go 7.9 KB

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