watch.go 14 KB

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