watch.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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/jonboulle/clockwork"
  22. "github.com/mitchellh/mapstructure"
  23. "github.com/pkg/errors"
  24. "github.com/sirupsen/logrus"
  25. "golang.org/x/sync/errgroup"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/docker/compose/v2/pkg/utils"
  28. "github.com/docker/compose/v2/pkg/watch"
  29. )
  30. type DevelopmentConfig struct {
  31. Watch []Trigger `json:"watch,omitempty"`
  32. }
  33. const (
  34. WatchActionSync = "sync"
  35. WatchActionRebuild = "rebuild"
  36. )
  37. type Trigger struct {
  38. Path string `json:"path,omitempty"`
  39. Action string `json:"action,omitempty"`
  40. Target string `json:"target,omitempty"`
  41. }
  42. const quietPeriod = 2 * time.Second
  43. func (s *composeService) Watch(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error { //nolint:gocyclo
  44. needRebuild := make(chan string)
  45. needSync := make(chan api.CopyOptions, 5)
  46. eg, ctx := errgroup.WithContext(ctx)
  47. eg.Go(func() error {
  48. clock := clockwork.NewRealClock()
  49. debounce(ctx, clock, quietPeriod, needRebuild, s.makeRebuildFn(ctx, project))
  50. return nil
  51. })
  52. eg.Go(s.makeSyncFn(ctx, project, needSync))
  53. ss, err := project.GetServices(services...)
  54. if err != nil {
  55. return err
  56. }
  57. for _, service := range ss {
  58. config, err := loadDevelopmentConfig(service, project)
  59. if err != nil {
  60. return err
  61. }
  62. name := service.Name
  63. if service.Build == nil {
  64. if len(services) != 0 || len(config.Watch) != 0 {
  65. // watch explicitly requested on service, but no build section set
  66. return fmt.Errorf("service %s doesn't have a build section", name)
  67. }
  68. logrus.Infof("service %s ignored. Can't watch a service without a build section", name)
  69. continue
  70. }
  71. bc := service.Build.Context
  72. dockerIgnores, err := watch.LoadDockerIgnore(bc)
  73. if err != nil {
  74. return err
  75. }
  76. // add a hardcoded set of ignores on top of what came from .dockerignore
  77. // some of this should likely be configurable (e.g. there could be cases
  78. // where you want `.git` to be synced) but this is suitable for now
  79. dotGitIgnore, err := watch.NewDockerPatternMatcher("/", []string{".git/"})
  80. if err != nil {
  81. return err
  82. }
  83. ignore := watch.NewCompositeMatcher(
  84. dockerIgnores,
  85. watch.EphemeralPathMatcher,
  86. dotGitIgnore,
  87. )
  88. watcher, err := watch.NewWatcher([]string{bc}, ignore)
  89. if err != nil {
  90. return err
  91. }
  92. fmt.Fprintf(s.stderr(), "watching %s\n", bc)
  93. err = watcher.Start()
  94. if err != nil {
  95. return err
  96. }
  97. eg.Go(func() error {
  98. defer watcher.Close() //nolint:errcheck
  99. WATCH:
  100. for {
  101. select {
  102. case <-ctx.Done():
  103. return nil
  104. case event := <-watcher.Events():
  105. path := event.Path()
  106. for _, trigger := range config.Watch {
  107. logrus.Debugf("change detected on %s - comparing with %s", path, trigger.Path)
  108. if watch.IsChild(trigger.Path, path) {
  109. fmt.Fprintf(s.stderr(), "change detected on %s\n", path)
  110. switch trigger.Action {
  111. case WatchActionSync:
  112. logrus.Debugf("modified file %s triggered sync", path)
  113. rel, err := filepath.Rel(trigger.Path, path)
  114. if err != nil {
  115. return err
  116. }
  117. dest := filepath.Join(trigger.Target, rel)
  118. needSync <- api.CopyOptions{
  119. Source: path,
  120. Destination: fmt.Sprintf("%s:%s", name, dest),
  121. }
  122. case WatchActionRebuild:
  123. logrus.Debugf("modified file %s requires image to be rebuilt", path)
  124. needRebuild <- name
  125. default:
  126. return fmt.Errorf("watch action %q is not supported", trigger)
  127. }
  128. continue WATCH
  129. }
  130. }
  131. // default
  132. needRebuild <- name
  133. case err := <-watcher.Errors():
  134. return err
  135. }
  136. }
  137. })
  138. }
  139. return eg.Wait()
  140. }
  141. func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (DevelopmentConfig, error) {
  142. var config DevelopmentConfig
  143. if y, ok := service.Extensions["x-develop"]; ok {
  144. err := mapstructure.Decode(y, &config)
  145. if err != nil {
  146. return config, err
  147. }
  148. for i, trigger := range config.Watch {
  149. if !filepath.IsAbs(trigger.Path) {
  150. trigger.Path = filepath.Join(project.WorkingDir, trigger.Path)
  151. }
  152. trigger.Path = filepath.Clean(trigger.Path)
  153. if trigger.Path == "" {
  154. return config, errors.New("watch rules MUST define a path")
  155. }
  156. config.Watch[i] = trigger
  157. }
  158. }
  159. return config, nil
  160. }
  161. func (s *composeService) makeRebuildFn(ctx context.Context, project *types.Project) func(services []string) {
  162. return func(services []string) {
  163. fmt.Fprintf(s.stderr(), "Updating %s after changes were detected\n", strings.Join(services, ", "))
  164. imageIds, err := s.build(ctx, project, api.BuildOptions{
  165. Services: services,
  166. })
  167. if err != nil {
  168. fmt.Fprintf(s.stderr(), "Build failed\n")
  169. }
  170. for i, service := range project.Services {
  171. if id, ok := imageIds[service.Name]; ok {
  172. service.Image = id
  173. }
  174. project.Services[i] = service
  175. }
  176. err = s.Up(ctx, project, api.UpOptions{
  177. Create: api.CreateOptions{
  178. Services: services,
  179. Inherit: true,
  180. },
  181. Start: api.StartOptions{
  182. Services: services,
  183. Project: project,
  184. },
  185. })
  186. if err != nil {
  187. fmt.Fprintf(s.stderr(), "Application failed to start after update\n")
  188. }
  189. }
  190. }
  191. func (s *composeService) makeSyncFn(ctx context.Context, project *types.Project, needSync chan api.CopyOptions) func() error {
  192. return func() error {
  193. for {
  194. select {
  195. case <-ctx.Done():
  196. return nil
  197. case opt := <-needSync:
  198. err := s.Copy(ctx, project.Name, opt)
  199. if err != nil {
  200. return err
  201. }
  202. fmt.Fprintf(s.stderr(), "%s updated\n", opt.Destination)
  203. }
  204. }
  205. }
  206. }
  207. func debounce(ctx context.Context, clock clockwork.Clock, delay time.Duration, input chan string, fn func(services []string)) {
  208. services := utils.Set[string]{}
  209. t := clock.AfterFunc(delay, func() {
  210. if len(services) > 0 {
  211. refresh := services.Elements()
  212. services.Clear()
  213. fn(refresh)
  214. }
  215. })
  216. for {
  217. select {
  218. case <-ctx.Done():
  219. return
  220. case service := <-input:
  221. t.Reset(delay)
  222. services.Add(service)
  223. }
  224. }
  225. }