watch.go 16 KB

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