watch.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 {
  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 {
  92. if service.Build == nil {
  93. continue
  94. }
  95. config = &DevelopmentConfig{
  96. Watch: []Trigger{
  97. {
  98. Path: service.Build.Context,
  99. Action: WatchActionRebuild,
  100. },
  101. },
  102. }
  103. }
  104. name := service.Name
  105. bc := service.Build.Context
  106. dockerIgnores, err := watch.LoadDockerIgnore(bc)
  107. if err != nil {
  108. return err
  109. }
  110. // add a hardcoded set of ignores on top of what came from .dockerignore
  111. // some of this should likely be configurable (e.g. there could be cases
  112. // where you want `.git` to be synced) but this is suitable for now
  113. dotGitIgnore, err := watch.NewDockerPatternMatcher("/", []string{".git/"})
  114. if err != nil {
  115. return err
  116. }
  117. ignore := watch.NewCompositeMatcher(
  118. dockerIgnores,
  119. watch.EphemeralPathMatcher(),
  120. dotGitIgnore,
  121. )
  122. watcher, err := watch.NewWatcher([]string{bc}, ignore)
  123. if err != nil {
  124. return err
  125. }
  126. fmt.Fprintf(s.stderr(), "watching %s\n", bc)
  127. err = watcher.Start()
  128. if err != nil {
  129. return err
  130. }
  131. watching = true
  132. eg.Go(func() error {
  133. defer watcher.Close() //nolint:errcheck
  134. return s.watch(ctx, name, watcher, config.Watch, needSync, needRebuild)
  135. })
  136. }
  137. if !watching {
  138. return fmt.Errorf("none of the selected services is configured for watch, consider setting an 'x-develop' section")
  139. }
  140. return eg.Wait()
  141. }
  142. func (s *composeService) watch(ctx context.Context, name string, watcher watch.Notify, triggers []Trigger, needSync chan fileMapping, needRebuild chan fileMapping) error {
  143. ignores := make([]watch.PathMatcher, len(triggers))
  144. for i, trigger := range triggers {
  145. ignore, err := watch.NewDockerPatternMatcher(trigger.Path, trigger.Ignore)
  146. if err != nil {
  147. return err
  148. }
  149. ignores[i] = ignore
  150. }
  151. WATCH:
  152. for {
  153. select {
  154. case <-ctx.Done():
  155. return nil
  156. case event := <-watcher.Events():
  157. hostPath := event.Path()
  158. for i, trigger := range triggers {
  159. logrus.Debugf("change detected on %s - comparing with %s", hostPath, trigger.Path)
  160. if watch.IsChild(trigger.Path, hostPath) {
  161. match, err := ignores[i].Matches(hostPath)
  162. if err != nil {
  163. return err
  164. }
  165. if match {
  166. logrus.Debugf("%s is matching ignore pattern", hostPath)
  167. continue
  168. }
  169. fmt.Fprintf(s.stderr(), "change detected on %s\n", hostPath)
  170. f := fileMapping{
  171. HostPath: hostPath,
  172. Service: name,
  173. }
  174. switch trigger.Action {
  175. case WatchActionSync:
  176. logrus.Debugf("modified file %s triggered sync", hostPath)
  177. rel, err := filepath.Rel(trigger.Path, hostPath)
  178. if err != nil {
  179. return err
  180. }
  181. // always use Unix-style paths for inside the container
  182. f.ContainerPath = path.Join(trigger.Target, rel)
  183. needSync <- f
  184. case WatchActionRebuild:
  185. logrus.Debugf("modified file %s requires image to be rebuilt", hostPath)
  186. needRebuild <- f
  187. default:
  188. return fmt.Errorf("watch action %q is not supported", trigger)
  189. }
  190. continue WATCH
  191. }
  192. }
  193. case err := <-watcher.Errors():
  194. return err
  195. }
  196. }
  197. }
  198. func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (*DevelopmentConfig, error) {
  199. var config DevelopmentConfig
  200. y, ok := service.Extensions["x-develop"]
  201. if !ok {
  202. return nil, nil
  203. }
  204. err := mapstructure.Decode(y, &config)
  205. if err != nil {
  206. return nil, err
  207. }
  208. for i, trigger := range config.Watch {
  209. if !filepath.IsAbs(trigger.Path) {
  210. trigger.Path = filepath.Join(project.WorkingDir, trigger.Path)
  211. }
  212. trigger.Path = filepath.Clean(trigger.Path)
  213. if trigger.Path == "" {
  214. return nil, errors.New("watch rules MUST define a path")
  215. }
  216. if trigger.Action == WatchActionRebuild && service.Build == nil {
  217. return nil, fmt.Errorf("service %s doesn't have a build section, can't apply 'rebuild' on watch", service.Name)
  218. }
  219. config.Watch[i] = trigger
  220. }
  221. return &config, nil
  222. }
  223. func (s *composeService) makeRebuildFn(ctx context.Context, project *types.Project) func(services rebuildServices) {
  224. for i, service := range project.Services {
  225. service.PullPolicy = types.PullPolicyBuild
  226. project.Services[i] = service
  227. }
  228. return func(services rebuildServices) {
  229. serviceNames := make([]string, 0, len(services))
  230. allPaths := make(utils.Set[string])
  231. for serviceName, paths := range services {
  232. serviceNames = append(serviceNames, serviceName)
  233. for p := range paths {
  234. allPaths.Add(p)
  235. }
  236. }
  237. fmt.Fprintf(
  238. s.stderr(),
  239. "Rebuilding %s after changes were detected:%s\n",
  240. strings.Join(serviceNames, ", "),
  241. strings.Join(append([]string{""}, allPaths.Elements()...), "\n - "),
  242. )
  243. err := s.Up(ctx, project, api.UpOptions{
  244. Create: api.CreateOptions{
  245. Services: serviceNames,
  246. Inherit: true,
  247. },
  248. Start: api.StartOptions{
  249. Services: serviceNames,
  250. Project: project,
  251. },
  252. })
  253. if err != nil {
  254. fmt.Fprintf(s.stderr(), "Application failed to start after update\n")
  255. }
  256. }
  257. }
  258. func (s *composeService) makeSyncFn(ctx context.Context, project *types.Project, needSync <-chan fileMapping) func() error {
  259. return func() error {
  260. for {
  261. select {
  262. case <-ctx.Done():
  263. return nil
  264. case opt := <-needSync:
  265. if fi, statErr := os.Stat(opt.HostPath); statErr == nil && !fi.IsDir() {
  266. err := s.Copy(ctx, project.Name, api.CopyOptions{
  267. Source: opt.HostPath,
  268. Destination: fmt.Sprintf("%s:%s", opt.Service, opt.ContainerPath),
  269. })
  270. if err != nil {
  271. return err
  272. }
  273. fmt.Fprintf(s.stderr(), "%s updated\n", opt.ContainerPath)
  274. } else if errors.Is(statErr, fs.ErrNotExist) {
  275. _, err := s.Exec(ctx, project.Name, api.RunOptions{
  276. Service: opt.Service,
  277. Command: []string{"rm", "-rf", opt.ContainerPath},
  278. Index: 1,
  279. })
  280. if err != nil {
  281. logrus.Warnf("failed to delete %q from %s: %v", opt.ContainerPath, opt.Service, err)
  282. }
  283. fmt.Fprintf(s.stderr(), "%s deleted from container\n", opt.ContainerPath)
  284. }
  285. }
  286. }
  287. }
  288. }
  289. type rebuildServices map[string]utils.Set[string]
  290. func debounce(ctx context.Context, clock clockwork.Clock, delay time.Duration, input <-chan fileMapping, fn func(services rebuildServices)) {
  291. services := make(rebuildServices)
  292. t := clock.NewTimer(delay)
  293. defer t.Stop()
  294. for {
  295. select {
  296. case <-ctx.Done():
  297. return
  298. case <-t.Chan():
  299. if len(services) > 0 {
  300. go fn(services)
  301. services = make(rebuildServices)
  302. }
  303. case e := <-input:
  304. t.Reset(delay)
  305. svc, ok := services[e.Service]
  306. if !ok {
  307. svc = make(utils.Set[string])
  308. services[e.Service] = svc
  309. }
  310. svc.Add(e.HostPath)
  311. }
  312. }
  313. }