watch.go 13 KB

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