watch.go 16 KB

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