watch.go 15 KB

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