watch.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/compose-spec/compose-go/types"
  26. "github.com/docker/compose/v2/internal/sync"
  27. "github.com/docker/compose/v2/pkg/api"
  28. "github.com/docker/compose/v2/pkg/watch"
  29. moby "github.com/docker/docker/api/types"
  30. "github.com/jonboulle/clockwork"
  31. "github.com/mitchellh/mapstructure"
  32. "github.com/pkg/errors"
  33. "github.com/sirupsen/logrus"
  34. "golang.org/x/sync/errgroup"
  35. )
  36. const quietPeriod = 500 * time.Millisecond
  37. // fileEvent contains the Compose service and modified host system path.
  38. type fileEvent struct {
  39. sync.PathMapping
  40. Action types.WatchAction
  41. }
  42. // getSyncImplementation returns the the tar-based syncer unless it has been explicitly
  43. // disabled with `COMPOSE_EXPERIMENTAL_WATCH_TAR=0`. Note that the absence of the env
  44. // var means enabled.
  45. func (s *composeService) getSyncImplementation(project *types.Project) sync.Syncer {
  46. var useTar bool
  47. if useTarEnv, ok := os.LookupEnv("COMPOSE_EXPERIMENTAL_WATCH_TAR"); ok {
  48. useTar, _ = strconv.ParseBool(useTarEnv)
  49. } else {
  50. useTar = true
  51. }
  52. if useTar {
  53. return sync.NewTar(project.Name, tarDockerClient{s: s})
  54. }
  55. return sync.NewDockerCopy(project.Name, s, s.stdinfo())
  56. }
  57. func (s *composeService) Watch(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error { //nolint: gocyclo
  58. if err := project.ForServices(services); err != nil {
  59. return err
  60. }
  61. syncer := s.getSyncImplementation(project)
  62. eg, ctx := errgroup.WithContext(ctx)
  63. watching := false
  64. for i := range project.Services {
  65. service := project.Services[i]
  66. config, err := loadDevelopmentConfig(service, project)
  67. if err != nil {
  68. return err
  69. }
  70. if service.Develop != nil {
  71. config = service.Develop
  72. }
  73. if config == nil {
  74. continue
  75. }
  76. if len(config.Watch) > 0 && service.Build == nil {
  77. // service configured with watchers but no build section
  78. return fmt.Errorf("can't watch service %q without a build context", service.Name)
  79. }
  80. if len(services) > 0 && service.Build == nil {
  81. // service explicitly selected for watch has no build section
  82. return fmt.Errorf("can't watch service %q without a build context", service.Name)
  83. }
  84. if len(services) == 0 && service.Build == nil {
  85. continue
  86. }
  87. // set the service to always be built - watch triggers `Up()` when it receives a rebuild event
  88. service.PullPolicy = types.PullPolicyBuild
  89. project.Services[i] = service
  90. dockerIgnores, err := watch.LoadDockerIgnore(service.Build.Context)
  91. if err != nil {
  92. return err
  93. }
  94. // add a hardcoded set of ignores on top of what came from .dockerignore
  95. // some of this should likely be configurable (e.g. there could be cases
  96. // where you want `.git` to be synced) but this is suitable for now
  97. dotGitIgnore, err := watch.NewDockerPatternMatcher("/", []string{".git/"})
  98. if err != nil {
  99. return err
  100. }
  101. ignore := watch.NewCompositeMatcher(
  102. dockerIgnores,
  103. watch.EphemeralPathMatcher(),
  104. dotGitIgnore,
  105. )
  106. var paths []string
  107. for _, trigger := range config.Watch {
  108. if checkIfPathAlreadyBindMounted(trigger.Path, service.Volumes) {
  109. logrus.Warnf("path '%s' also declared by a bind mount volume, this path won't be monitored!\n", trigger.Path)
  110. continue
  111. }
  112. paths = append(paths, trigger.Path)
  113. }
  114. watcher, err := watch.NewWatcher(paths, ignore)
  115. if err != nil {
  116. return err
  117. }
  118. fmt.Fprintf(s.stdinfo(), "watching %s\n", paths)
  119. err = watcher.Start()
  120. if err != nil {
  121. return err
  122. }
  123. watching = true
  124. eg.Go(func() error {
  125. defer watcher.Close() //nolint:errcheck
  126. return s.watch(ctx, project, service.Name, options, watcher, syncer, config.Watch)
  127. })
  128. }
  129. if !watching {
  130. return fmt.Errorf("none of the selected services is configured for watch, consider setting an 'develop' section")
  131. }
  132. return eg.Wait()
  133. }
  134. func (s *composeService) watch(ctx context.Context, project *types.Project, name string, options api.WatchOptions, watcher watch.Notify, syncer sync.Syncer, triggers []types.Trigger) error {
  135. ctx, cancel := context.WithCancel(ctx)
  136. defer cancel()
  137. ignores := make([]watch.PathMatcher, len(triggers))
  138. for i, trigger := range triggers {
  139. ignore, err := watch.NewDockerPatternMatcher(trigger.Path, trigger.Ignore)
  140. if err != nil {
  141. return err
  142. }
  143. ignores[i] = ignore
  144. }
  145. events := make(chan fileEvent)
  146. batchEvents := batchDebounceEvents(ctx, s.clock, quietPeriod, events)
  147. go func() {
  148. for {
  149. select {
  150. case <-ctx.Done():
  151. return
  152. case batch := <-batchEvents:
  153. start := time.Now()
  154. logrus.Debugf("batch start: service[%s] count[%d]", name, len(batch))
  155. if err := s.handleWatchBatch(ctx, project, name, options.Build, batch, syncer); err != nil {
  156. logrus.Warnf("Error handling changed files for service %s: %v", name, err)
  157. }
  158. logrus.Debugf("batch complete: service[%s] duration[%s] count[%d]",
  159. name, time.Since(start), len(batch))
  160. }
  161. }
  162. }()
  163. for {
  164. select {
  165. case <-ctx.Done():
  166. return nil
  167. case err := <-watcher.Errors():
  168. return err
  169. case event := <-watcher.Events():
  170. hostPath := event.Path()
  171. for i, trigger := range triggers {
  172. logrus.Debugf("change for %s - comparing with %s", hostPath, trigger.Path)
  173. if fileEvent := maybeFileEvent(trigger, hostPath, ignores[i]); fileEvent != nil {
  174. events <- *fileEvent
  175. }
  176. }
  177. }
  178. }
  179. }
  180. // maybeFileEvent returns a file event object if hostPath is valid for the provided trigger and ignore
  181. // rules.
  182. //
  183. // Any errors are logged as warnings and nil (no file event) is returned.
  184. func maybeFileEvent(trigger types.Trigger, hostPath string, ignore watch.PathMatcher) *fileEvent {
  185. if !watch.IsChild(trigger.Path, hostPath) {
  186. return nil
  187. }
  188. isIgnored, err := ignore.Matches(hostPath)
  189. if err != nil {
  190. logrus.Warnf("error ignore matching %q: %v", hostPath, err)
  191. return nil
  192. }
  193. if isIgnored {
  194. logrus.Debugf("%s is matching ignore pattern", hostPath)
  195. return nil
  196. }
  197. var containerPath string
  198. if trigger.Target != "" {
  199. rel, err := filepath.Rel(trigger.Path, hostPath)
  200. if err != nil {
  201. logrus.Warnf("error making %s relative to %s: %v", hostPath, trigger.Path, err)
  202. return nil
  203. }
  204. // always use Unix-style paths for inside the container
  205. containerPath = path.Join(trigger.Target, rel)
  206. }
  207. return &fileEvent{
  208. Action: trigger.Action,
  209. PathMapping: sync.PathMapping{
  210. HostPath: hostPath,
  211. ContainerPath: containerPath,
  212. },
  213. }
  214. }
  215. func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (*types.DevelopConfig, error) {
  216. var config types.DevelopConfig
  217. y, ok := service.Extensions["x-develop"]
  218. if !ok {
  219. return nil, nil
  220. }
  221. logrus.Warnf("x-develop is DEPRECATED, please use the official `develop` attribute")
  222. err := mapstructure.Decode(y, &config)
  223. if err != nil {
  224. return nil, err
  225. }
  226. baseDir, err := filepath.EvalSymlinks(project.WorkingDir)
  227. if err != nil {
  228. return nil, fmt.Errorf("resolving symlink for %q: %w", project.WorkingDir, err)
  229. }
  230. for i, trigger := range config.Watch {
  231. if !filepath.IsAbs(trigger.Path) {
  232. trigger.Path = filepath.Join(baseDir, trigger.Path)
  233. }
  234. if p, err := filepath.EvalSymlinks(trigger.Path); err == nil {
  235. // this might fail because the path doesn't exist, etc.
  236. trigger.Path = p
  237. }
  238. trigger.Path = filepath.Clean(trigger.Path)
  239. if trigger.Path == "" {
  240. return nil, errors.New("watch rules MUST define a path")
  241. }
  242. if trigger.Action == types.WatchActionRebuild && service.Build == nil {
  243. return nil, fmt.Errorf("service %s doesn't have a build section, can't apply 'rebuild' on watch", service.Name)
  244. }
  245. config.Watch[i] = trigger
  246. }
  247. return &config, nil
  248. }
  249. // batchDebounceEvents groups identical file events within a sliding time window and writes the results to the returned
  250. // channel.
  251. //
  252. // The returned channel is closed when the debouncer is stopped via context cancellation or by closing the input channel.
  253. func batchDebounceEvents(ctx context.Context, clock clockwork.Clock, delay time.Duration, input <-chan fileEvent) <-chan []fileEvent {
  254. out := make(chan []fileEvent)
  255. go func() {
  256. defer close(out)
  257. seen := make(map[fileEvent]time.Time)
  258. flushEvents := func() {
  259. if len(seen) == 0 {
  260. return
  261. }
  262. events := make([]fileEvent, 0, len(seen))
  263. for e := range seen {
  264. events = append(events, e)
  265. }
  266. // sort batch by oldest -> newest
  267. // (if an event is seen > 1 per batch, it gets the latest timestamp)
  268. sort.SliceStable(events, func(i, j int) bool {
  269. x := events[i]
  270. y := events[j]
  271. return seen[x].Before(seen[y])
  272. })
  273. out <- events
  274. seen = make(map[fileEvent]time.Time)
  275. }
  276. t := clock.NewTicker(delay)
  277. defer t.Stop()
  278. for {
  279. select {
  280. case <-ctx.Done():
  281. return
  282. case <-t.Chan():
  283. flushEvents()
  284. case e, ok := <-input:
  285. if !ok {
  286. // input channel was closed
  287. flushEvents()
  288. return
  289. }
  290. seen[e] = time.Now()
  291. t.Reset(delay)
  292. }
  293. }
  294. }()
  295. return out
  296. }
  297. func checkIfPathAlreadyBindMounted(watchPath string, volumes []types.ServiceVolumeConfig) bool {
  298. for _, volume := range volumes {
  299. if volume.Bind != nil && strings.HasPrefix(watchPath, volume.Source) {
  300. return true
  301. }
  302. }
  303. return false
  304. }
  305. type tarDockerClient struct {
  306. s *composeService
  307. }
  308. func (t tarDockerClient) ContainersForService(ctx context.Context, projectName string, serviceName string) ([]moby.Container, error) {
  309. containers, err := t.s.getContainers(ctx, projectName, oneOffExclude, true, serviceName)
  310. if err != nil {
  311. return nil, err
  312. }
  313. return containers, nil
  314. }
  315. func (t tarDockerClient) Exec(ctx context.Context, containerID string, cmd []string, in io.Reader) error {
  316. execCfg := moby.ExecConfig{
  317. Cmd: cmd,
  318. AttachStdout: false,
  319. AttachStderr: true,
  320. AttachStdin: in != nil,
  321. Tty: false,
  322. }
  323. execCreateResp, err := t.s.apiClient().ContainerExecCreate(ctx, containerID, execCfg)
  324. if err != nil {
  325. return err
  326. }
  327. startCheck := moby.ExecStartCheck{Tty: false, Detach: false}
  328. conn, err := t.s.apiClient().ContainerExecAttach(ctx, execCreateResp.ID, startCheck)
  329. if err != nil {
  330. return err
  331. }
  332. defer conn.Close()
  333. var eg errgroup.Group
  334. if in != nil {
  335. eg.Go(func() error {
  336. defer func() {
  337. _ = conn.CloseWrite()
  338. }()
  339. _, err := io.Copy(conn.Conn, in)
  340. return err
  341. })
  342. }
  343. eg.Go(func() error {
  344. _, err := io.Copy(t.s.stdinfo(), conn.Reader)
  345. return err
  346. })
  347. err = t.s.apiClient().ContainerExecStart(ctx, execCreateResp.ID, startCheck)
  348. if err != nil {
  349. return err
  350. }
  351. // although the errgroup is not tied directly to the context, the operations
  352. // in it are reading/writing to the connection, which is tied to the context,
  353. // so they won't block indefinitely
  354. if err := eg.Wait(); err != nil {
  355. return err
  356. }
  357. execResult, err := t.s.apiClient().ContainerExecInspect(ctx, execCreateResp.ID)
  358. if err != nil {
  359. return err
  360. }
  361. if execResult.Running {
  362. return errors.New("process still running")
  363. }
  364. if execResult.ExitCode != 0 {
  365. return fmt.Errorf("exit code %d", execResult.ExitCode)
  366. }
  367. return nil
  368. }
  369. func (s *composeService) handleWatchBatch(ctx context.Context, project *types.Project, serviceName string, build api.BuildOptions, batch []fileEvent, syncer sync.Syncer) error {
  370. pathMappings := make([]sync.PathMapping, len(batch))
  371. for i := range batch {
  372. if batch[i].Action == types.WatchActionRebuild {
  373. fmt.Fprintf(
  374. s.stdinfo(),
  375. "Rebuilding %s after changes were detected:%s\n",
  376. serviceName,
  377. strings.Join(append([]string{""}, batch[i].HostPath), "\n - "),
  378. )
  379. // restrict the build to ONLY this service, not any of its dependencies
  380. build.Services = []string{serviceName}
  381. err := s.Up(ctx, project, api.UpOptions{
  382. Create: api.CreateOptions{
  383. Build: &build,
  384. Services: []string{serviceName},
  385. Inherit: true,
  386. },
  387. Start: api.StartOptions{
  388. Services: []string{serviceName},
  389. Project: project,
  390. },
  391. })
  392. if err != nil {
  393. fmt.Fprintf(s.stderr(), "Application failed to start after update\n")
  394. }
  395. return nil
  396. }
  397. pathMappings[i] = batch[i].PathMapping
  398. }
  399. writeWatchSyncMessage(s.stdinfo(), serviceName, pathMappings)
  400. service, err := project.GetService(serviceName)
  401. if err != nil {
  402. return err
  403. }
  404. if err := syncer.Sync(ctx, service, pathMappings); err != nil {
  405. return err
  406. }
  407. return nil
  408. }
  409. // writeWatchSyncMessage prints out a message about the sync for the changed paths.
  410. func writeWatchSyncMessage(w io.Writer, serviceName string, pathMappings []sync.PathMapping) {
  411. const maxPathsToShow = 10
  412. if len(pathMappings) <= maxPathsToShow || logrus.IsLevelEnabled(logrus.DebugLevel) {
  413. hostPathsToSync := make([]string, len(pathMappings))
  414. for i := range pathMappings {
  415. hostPathsToSync[i] = pathMappings[i].HostPath
  416. }
  417. fmt.Fprintf(
  418. w,
  419. "Syncing %s after changes were detected:%s\n",
  420. serviceName,
  421. strings.Join(append([]string{""}, hostPathsToSync...), "\n - "),
  422. )
  423. } else {
  424. hostPathsToSync := make([]string, len(pathMappings))
  425. for i := range pathMappings {
  426. hostPathsToSync[i] = pathMappings[i].HostPath
  427. }
  428. fmt.Fprintf(
  429. w,
  430. "Syncing %s after %d changes were detected\n",
  431. serviceName,
  432. len(pathMappings),
  433. )
  434. }
  435. }