watch.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. "io/fs"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "strings"
  22. "time"
  23. "github.com/compose-spec/compose-go/types"
  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. "github.com/docker/compose/v2/pkg/api"
  30. "github.com/docker/compose/v2/pkg/utils"
  31. "github.com/docker/compose/v2/pkg/watch"
  32. )
  33. type DevelopmentConfig struct {
  34. Watch []Trigger `json:"watch,omitempty"`
  35. }
  36. const (
  37. WatchActionSync = "sync"
  38. WatchActionRebuild = "rebuild"
  39. )
  40. type Trigger struct {
  41. Path string `json:"path,omitempty"`
  42. Action string `json:"action,omitempty"`
  43. Target string `json:"target,omitempty"`
  44. Ignore []string `json:"ignore,omitempty"`
  45. }
  46. const quietPeriod = 2 * time.Second
  47. // fileMapping contains the Compose service and modified host system path.
  48. //
  49. // For file sync, the container path is also included.
  50. // For rebuild, there is no container path, so it is always empty.
  51. type fileMapping struct {
  52. // Service that the file event is for.
  53. Service string
  54. // HostPath that was created/modified/deleted outside the container.
  55. //
  56. // This is the path as seen from the user's perspective, e.g.
  57. // - C:\Users\moby\Documents\hello-world\main.go
  58. // - /Users/moby/Documents/hello-world/main.go
  59. HostPath string
  60. // ContainerPath for the target file inside the container (only populated
  61. // for sync events, not rebuild).
  62. //
  63. // This is the path as used in Docker CLI commands, e.g.
  64. // - /workdir/main.go
  65. ContainerPath string
  66. }
  67. func (s *composeService) Watch(ctx context.Context, project *types.Project, services []string, _ api.WatchOptions) error { //nolint: gocyclo
  68. needRebuild := make(chan fileMapping)
  69. needSync := make(chan fileMapping)
  70. err := s.prepareProjectForBuild(project, nil)
  71. if err != nil {
  72. return err
  73. }
  74. eg, ctx := errgroup.WithContext(ctx)
  75. eg.Go(func() error {
  76. clock := clockwork.NewRealClock()
  77. debounce(ctx, clock, quietPeriod, needRebuild, s.makeRebuildFn(ctx, project))
  78. return nil
  79. })
  80. eg.Go(s.makeSyncFn(ctx, project, needSync))
  81. ss, err := project.GetServices(services...)
  82. if err != nil {
  83. return err
  84. }
  85. watching := false
  86. for _, service := range ss {
  87. config, err := loadDevelopmentConfig(service, project)
  88. if err != nil {
  89. return err
  90. }
  91. if config != nil && len(config.Watch) > 0 && service.Build == nil {
  92. // service configured with watchers but no build section
  93. return fmt.Errorf("can't watch service %q without a build context", service.Name)
  94. }
  95. if len(services) > 0 && service.Build == nil {
  96. // service explicitly selected for watch has no build section
  97. return fmt.Errorf("can't watch service %q without a build context", service.Name)
  98. }
  99. if len(services) == 0 && service.Build == nil {
  100. continue
  101. }
  102. if config == nil {
  103. config = &DevelopmentConfig{
  104. Watch: []Trigger{
  105. {
  106. Path: service.Build.Context,
  107. Action: WatchActionRebuild,
  108. },
  109. },
  110. }
  111. }
  112. name := service.Name
  113. bc := service.Build.Context
  114. dockerIgnores, err := watch.LoadDockerIgnore(bc)
  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. watcher, err := watch.NewWatcher([]string{bc}, ignore)
  131. if err != nil {
  132. return err
  133. }
  134. fmt.Fprintf(s.stdinfo(), "watching %s\n", bc)
  135. err = watcher.Start()
  136. if err != nil {
  137. return err
  138. }
  139. watching = true
  140. eg.Go(func() error {
  141. defer watcher.Close() //nolint:errcheck
  142. return s.watch(ctx, name, watcher, config.Watch, needSync, needRebuild)
  143. })
  144. }
  145. if !watching {
  146. return fmt.Errorf("none of the selected services is configured for watch, consider setting an 'x-develop' section")
  147. }
  148. return eg.Wait()
  149. }
  150. func (s *composeService) watch(ctx context.Context, name string, watcher watch.Notify, triggers []Trigger, needSync chan fileMapping, needRebuild chan fileMapping) error {
  151. ignores := make([]watch.PathMatcher, len(triggers))
  152. for i, trigger := range triggers {
  153. ignore, err := watch.NewDockerPatternMatcher(trigger.Path, trigger.Ignore)
  154. if err != nil {
  155. return err
  156. }
  157. ignores[i] = ignore
  158. }
  159. WATCH:
  160. for {
  161. select {
  162. case <-ctx.Done():
  163. return nil
  164. case event := <-watcher.Events():
  165. hostPath := event.Path()
  166. for i, trigger := range triggers {
  167. logrus.Debugf("change detected on %s - comparing with %s", hostPath, trigger.Path)
  168. if watch.IsChild(trigger.Path, hostPath) {
  169. match, err := ignores[i].Matches(hostPath)
  170. if err != nil {
  171. return err
  172. }
  173. if match {
  174. logrus.Debugf("%s is matching ignore pattern", hostPath)
  175. continue
  176. }
  177. fmt.Fprintf(s.stdinfo(), "change detected on %s\n", hostPath)
  178. f := fileMapping{
  179. HostPath: hostPath,
  180. Service: name,
  181. }
  182. switch trigger.Action {
  183. case WatchActionSync:
  184. logrus.Debugf("modified file %s triggered sync", hostPath)
  185. rel, err := filepath.Rel(trigger.Path, hostPath)
  186. if err != nil {
  187. return err
  188. }
  189. // always use Unix-style paths for inside the container
  190. f.ContainerPath = path.Join(trigger.Target, rel)
  191. needSync <- f
  192. case WatchActionRebuild:
  193. logrus.Debugf("modified file %s requires image to be rebuilt", hostPath)
  194. needRebuild <- f
  195. default:
  196. return fmt.Errorf("watch action %q is not supported", trigger)
  197. }
  198. continue WATCH
  199. }
  200. }
  201. case err := <-watcher.Errors():
  202. return err
  203. }
  204. }
  205. }
  206. func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (*DevelopmentConfig, error) {
  207. var config DevelopmentConfig
  208. y, ok := service.Extensions["x-develop"]
  209. if !ok {
  210. return nil, nil
  211. }
  212. err := mapstructure.Decode(y, &config)
  213. if err != nil {
  214. return nil, err
  215. }
  216. for i, trigger := range config.Watch {
  217. if !filepath.IsAbs(trigger.Path) {
  218. trigger.Path = filepath.Join(project.WorkingDir, trigger.Path)
  219. }
  220. trigger.Path = filepath.Clean(trigger.Path)
  221. if trigger.Path == "" {
  222. return nil, errors.New("watch rules MUST define a path")
  223. }
  224. if trigger.Action == WatchActionRebuild && service.Build == nil {
  225. return nil, fmt.Errorf("service %s doesn't have a build section, can't apply 'rebuild' on watch", service.Name)
  226. }
  227. config.Watch[i] = trigger
  228. }
  229. return &config, nil
  230. }
  231. func (s *composeService) makeRebuildFn(ctx context.Context, project *types.Project) func(services rebuildServices) {
  232. for i, service := range project.Services {
  233. service.PullPolicy = types.PullPolicyBuild
  234. project.Services[i] = service
  235. }
  236. return func(services rebuildServices) {
  237. serviceNames := make([]string, 0, len(services))
  238. allPaths := make(utils.Set[string])
  239. for serviceName, paths := range services {
  240. serviceNames = append(serviceNames, serviceName)
  241. for p := range paths {
  242. allPaths.Add(p)
  243. }
  244. }
  245. fmt.Fprintf(
  246. s.stdinfo(),
  247. "Rebuilding %s after changes were detected:%s\n",
  248. strings.Join(serviceNames, ", "),
  249. strings.Join(append([]string{""}, allPaths.Elements()...), "\n - "),
  250. )
  251. err := s.Up(ctx, project, api.UpOptions{
  252. Create: api.CreateOptions{
  253. Services: serviceNames,
  254. Inherit: true,
  255. },
  256. Start: api.StartOptions{
  257. Services: serviceNames,
  258. Project: project,
  259. },
  260. })
  261. if err != nil {
  262. fmt.Fprintf(s.stderr(), "Application failed to start after update\n")
  263. }
  264. }
  265. }
  266. func (s *composeService) makeSyncFn(ctx context.Context, project *types.Project, needSync <-chan fileMapping) func() error {
  267. return func() error {
  268. for {
  269. select {
  270. case <-ctx.Done():
  271. return nil
  272. case opt := <-needSync:
  273. if fi, statErr := os.Stat(opt.HostPath); statErr == nil && !fi.IsDir() {
  274. err := s.Copy(ctx, project.Name, api.CopyOptions{
  275. Source: opt.HostPath,
  276. Destination: fmt.Sprintf("%s:%s", opt.Service, opt.ContainerPath),
  277. })
  278. if err != nil {
  279. return err
  280. }
  281. fmt.Fprintf(s.stdinfo(), "%s updated\n", opt.ContainerPath)
  282. } else if errors.Is(statErr, fs.ErrNotExist) {
  283. _, err := s.Exec(ctx, project.Name, api.RunOptions{
  284. Service: opt.Service,
  285. Command: []string{"rm", "-rf", opt.ContainerPath},
  286. Index: 1,
  287. })
  288. if err != nil {
  289. logrus.Warnf("failed to delete %q from %s: %v", opt.ContainerPath, opt.Service, err)
  290. }
  291. fmt.Fprintf(s.stdinfo(), "%s deleted from container\n", opt.ContainerPath)
  292. }
  293. }
  294. }
  295. }
  296. }
  297. type rebuildServices map[string]utils.Set[string]
  298. func debounce(ctx context.Context, clock clockwork.Clock, delay time.Duration, input <-chan fileMapping, fn func(services rebuildServices)) {
  299. services := make(rebuildServices)
  300. t := clock.NewTimer(delay)
  301. defer t.Stop()
  302. for {
  303. select {
  304. case <-ctx.Done():
  305. return
  306. case <-t.Chan():
  307. if len(services) > 0 {
  308. go fn(services)
  309. services = make(rebuildServices)
  310. }
  311. case e := <-input:
  312. t.Reset(delay)
  313. svc, ok := services[e.Service]
  314. if !ok {
  315. svc = make(utils.Set[string])
  316. services[e.Service] = svc
  317. }
  318. svc.Add(e.HostPath)
  319. }
  320. }
  321. }