watch.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. "path/filepath"
  18. "strings"
  19. "time"
  20. "github.com/compose-spec/compose-go/types"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/docker/compose/v2/pkg/utils"
  23. "github.com/docker/compose/v2/pkg/watch"
  24. "github.com/jonboulle/clockwork"
  25. "github.com/mitchellh/mapstructure"
  26. "github.com/pkg/errors"
  27. "golang.org/x/sync/errgroup"
  28. )
  29. type DevelopmentConfig struct {
  30. Sync map[string]string `json:"sync,omitempty"`
  31. Excludes []string `json:"excludes,omitempty"`
  32. }
  33. const quietPeriod = 2 * time.Second
  34. func (s *composeService) Watch(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error {
  35. needRebuild := make(chan string)
  36. needSync := make(chan api.CopyOptions, 5)
  37. eg, ctx := errgroup.WithContext(ctx)
  38. eg.Go(func() error {
  39. clock := clockwork.NewRealClock()
  40. debounce(ctx, clock, quietPeriod, needRebuild, s.makeRebuildFn(ctx, project))
  41. return nil
  42. })
  43. eg.Go(s.makeSyncFn(ctx, project, needSync))
  44. err := project.WithServices(services, func(service types.ServiceConfig) error {
  45. config, err := loadDevelopmentConfig(service, project)
  46. if err != nil {
  47. return err
  48. }
  49. if service.Build == nil {
  50. return errors.New("can't watch a service without a build section")
  51. }
  52. context := service.Build.Context
  53. ignore, err := watch.LoadDockerIgnore(context)
  54. if err != nil {
  55. return err
  56. }
  57. watcher, err := watch.NewWatcher([]string{context}, ignore)
  58. if err != nil {
  59. return err
  60. }
  61. fmt.Fprintf(s.stderr(), "watching %s\n", context)
  62. err = watcher.Start()
  63. if err != nil {
  64. return err
  65. }
  66. eg.Go(func() error {
  67. defer watcher.Close() //nolint:errcheck
  68. WATCH:
  69. for {
  70. select {
  71. case <-ctx.Done():
  72. return nil
  73. case event := <-watcher.Events():
  74. fmt.Fprintf(s.stderr(), "change detected on %s\n", event.Path())
  75. for src, dest := range config.Sync {
  76. path := filepath.Clean(event.Path())
  77. src = filepath.Clean(src)
  78. if watch.IsChild(path, src) {
  79. rel, err := filepath.Rel(src, path)
  80. if err != nil {
  81. return err
  82. }
  83. dest = filepath.Join(dest, rel)
  84. needSync <- api.CopyOptions{
  85. Source: path,
  86. Destination: fmt.Sprintf("%s:%s", service.Name, dest),
  87. }
  88. continue WATCH
  89. }
  90. }
  91. needRebuild <- service.Name
  92. case err := <-watcher.Errors():
  93. return err
  94. }
  95. }
  96. })
  97. return nil
  98. })
  99. if err != nil {
  100. return err
  101. }
  102. return eg.Wait()
  103. }
  104. func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (DevelopmentConfig, error) {
  105. var config DevelopmentConfig
  106. if y, ok := service.Extensions["x-develop"]; ok {
  107. err := mapstructure.Decode(y, &config)
  108. if err != nil {
  109. return DevelopmentConfig{}, err
  110. }
  111. for src, dest := range config.Sync {
  112. if !filepath.IsAbs(src) {
  113. delete(config.Sync, src)
  114. src = filepath.Join(project.WorkingDir, src)
  115. config.Sync[src] = dest
  116. }
  117. }
  118. }
  119. return config, nil
  120. }
  121. func (s *composeService) makeRebuildFn(ctx context.Context, project *types.Project) func(services []string) {
  122. return func(services []string) {
  123. fmt.Fprintf(s.stderr(), "Updating %s after changes were detected\n", strings.Join(services, ", "))
  124. imageIds, err := s.build(ctx, project, api.BuildOptions{
  125. Services: services,
  126. })
  127. if err != nil {
  128. fmt.Fprintf(s.stderr(), "Build failed")
  129. }
  130. for i, service := range project.Services {
  131. if id, ok := imageIds[service.Name]; ok {
  132. service.Image = id
  133. }
  134. project.Services[i] = service
  135. }
  136. err = s.Up(ctx, project, api.UpOptions{
  137. Create: api.CreateOptions{
  138. Services: services,
  139. Inherit: true,
  140. },
  141. Start: api.StartOptions{
  142. Services: services,
  143. Project: project,
  144. },
  145. })
  146. if err != nil {
  147. fmt.Fprintf(s.stderr(), "Application failed to start after update")
  148. }
  149. }
  150. }
  151. func (s *composeService) makeSyncFn(ctx context.Context, project *types.Project, needSync chan api.CopyOptions) func() error {
  152. return func() error {
  153. for {
  154. select {
  155. case <-ctx.Done():
  156. return nil
  157. case opt := <-needSync:
  158. err := s.Copy(ctx, project.Name, opt)
  159. if err != nil {
  160. return err
  161. }
  162. fmt.Fprintf(s.stderr(), "%s updated\n", opt.Source)
  163. }
  164. }
  165. }
  166. }
  167. func debounce(ctx context.Context, clock clockwork.Clock, delay time.Duration, input chan string, fn func(services []string)) {
  168. services := utils.Set[string]{}
  169. t := clock.AfterFunc(delay, func() {
  170. if len(services) > 0 {
  171. refresh := services.Elements()
  172. services.Clear()
  173. fn(refresh)
  174. }
  175. })
  176. for {
  177. select {
  178. case <-ctx.Done():
  179. return
  180. case service := <-input:
  181. t.Reset(delay)
  182. services.Add(service)
  183. }
  184. }
  185. }