watch.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. "github.com/sirupsen/logrus"
  28. "golang.org/x/sync/errgroup"
  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. ignore, err := watch.LoadDockerIgnore(bc)
  73. if err != nil {
  74. return err
  75. }
  76. watcher, err := watch.NewWatcher([]string{bc}, ignore)
  77. if err != nil {
  78. return err
  79. }
  80. fmt.Fprintf(s.stderr(), "watching %s\n", bc)
  81. err = watcher.Start()
  82. if err != nil {
  83. return err
  84. }
  85. eg.Go(func() error {
  86. defer watcher.Close() //nolint:errcheck
  87. WATCH:
  88. for {
  89. select {
  90. case <-ctx.Done():
  91. return nil
  92. case event := <-watcher.Events():
  93. path := event.Path()
  94. for _, trigger := range config.Watch {
  95. logrus.Debugf("change deteced on %s - comparing with %s", path, trigger.Path)
  96. if watch.IsChild(trigger.Path, path) {
  97. fmt.Fprintf(s.stderr(), "change detected on %s\n", path)
  98. switch trigger.Action {
  99. case WatchActionSync:
  100. logrus.Debugf("modified file %s triggered sync", path)
  101. rel, err := filepath.Rel(trigger.Path, path)
  102. if err != nil {
  103. return err
  104. }
  105. dest := filepath.Join(trigger.Target, rel)
  106. needSync <- api.CopyOptions{
  107. Source: path,
  108. Destination: fmt.Sprintf("%s:%s", name, dest),
  109. }
  110. case WatchActionRebuild:
  111. logrus.Debugf("modified file %s require image to be rebuilt", path)
  112. needRebuild <- name
  113. default:
  114. return fmt.Errorf("watch action %q is not supported", trigger)
  115. }
  116. continue WATCH
  117. }
  118. }
  119. // default
  120. needRebuild <- name
  121. case err := <-watcher.Errors():
  122. return err
  123. }
  124. }
  125. })
  126. }
  127. return eg.Wait()
  128. }
  129. func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (DevelopmentConfig, error) {
  130. var config DevelopmentConfig
  131. if y, ok := service.Extensions["x-develop"]; ok {
  132. err := mapstructure.Decode(y, &config)
  133. if err != nil {
  134. return config, err
  135. }
  136. for i, trigger := range config.Watch {
  137. if !filepath.IsAbs(trigger.Path) {
  138. trigger.Path = filepath.Join(project.WorkingDir, trigger.Path)
  139. }
  140. trigger.Path = filepath.Clean(trigger.Path)
  141. if trigger.Path == "" {
  142. return config, errors.New("watch rules MUST define a path")
  143. }
  144. config.Watch[i] = trigger
  145. }
  146. }
  147. return config, nil
  148. }
  149. func (s *composeService) makeRebuildFn(ctx context.Context, project *types.Project) func(services []string) {
  150. return func(services []string) {
  151. fmt.Fprintf(s.stderr(), "Updating %s after changes were detected\n", strings.Join(services, ", "))
  152. imageIds, err := s.build(ctx, project, api.BuildOptions{
  153. Services: services,
  154. })
  155. if err != nil {
  156. fmt.Fprintf(s.stderr(), "Build failed")
  157. }
  158. for i, service := range project.Services {
  159. if id, ok := imageIds[service.Name]; ok {
  160. service.Image = id
  161. }
  162. project.Services[i] = service
  163. }
  164. err = s.Up(ctx, project, api.UpOptions{
  165. Create: api.CreateOptions{
  166. Services: services,
  167. Inherit: true,
  168. },
  169. Start: api.StartOptions{
  170. Services: services,
  171. Project: project,
  172. },
  173. })
  174. if err != nil {
  175. fmt.Fprintf(s.stderr(), "Application failed to start after update")
  176. }
  177. }
  178. }
  179. func (s *composeService) makeSyncFn(ctx context.Context, project *types.Project, needSync chan api.CopyOptions) func() error {
  180. return func() error {
  181. for {
  182. select {
  183. case <-ctx.Done():
  184. return nil
  185. case opt := <-needSync:
  186. err := s.Copy(ctx, project.Name, opt)
  187. if err != nil {
  188. return err
  189. }
  190. fmt.Fprintf(s.stderr(), "%s updated\n", opt.Source)
  191. }
  192. }
  193. }
  194. }
  195. func debounce(ctx context.Context, clock clockwork.Clock, delay time.Duration, input chan string, fn func(services []string)) {
  196. services := utils.Set[string]{}
  197. t := clock.AfterFunc(delay, func() {
  198. if len(services) > 0 {
  199. refresh := services.Elements()
  200. services.Clear()
  201. fn(refresh)
  202. }
  203. })
  204. for {
  205. select {
  206. case <-ctx.Done():
  207. return
  208. case service := <-input:
  209. t.Reset(delay)
  210. services.Add(service)
  211. }
  212. }
  213. }