convergence.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // +build local
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package local
  15. import (
  16. "context"
  17. "fmt"
  18. "strconv"
  19. "time"
  20. "github.com/compose-spec/compose-go/types"
  21. moby "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/api/types/filters"
  23. "github.com/docker/docker/api/types/network"
  24. "golang.org/x/sync/errgroup"
  25. "github.com/docker/compose-cli/progress"
  26. )
  27. const (
  28. extLifecycle = "x-lifecycle"
  29. forceRecreate = "force_recreate"
  30. )
  31. func (s *composeService) ensureService(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
  32. err := s.waitDependencies(ctx, project, service)
  33. if err != nil {
  34. return err
  35. }
  36. actual, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  37. Filters: filters.NewArgs(
  38. filters.Arg("label", fmt.Sprintf("%s=%s", projectLabel, project.Name)),
  39. filters.Arg("label", fmt.Sprintf("%s=%s", serviceLabel, service.Name)),
  40. ),
  41. })
  42. if err != nil {
  43. return err
  44. }
  45. scale := getScale(service)
  46. eg, _ := errgroup.WithContext(ctx)
  47. if len(actual) < scale {
  48. next, err := nextContainerNumber(actual)
  49. if err != nil {
  50. return err
  51. }
  52. missing := scale - len(actual)
  53. for i := 0; i < missing; i++ {
  54. number := next + i
  55. name := fmt.Sprintf("%s_%s_%d", project.Name, service.Name, number)
  56. eg.Go(func() error {
  57. return s.createContainer(ctx, project, service, name, number)
  58. })
  59. }
  60. }
  61. if len(actual) > scale {
  62. for i := scale; i < len(actual); i++ {
  63. container := actual[i]
  64. eg.Go(func() error {
  65. err := s.apiClient.ContainerStop(ctx, container.ID, nil)
  66. if err != nil {
  67. return err
  68. }
  69. return s.apiClient.ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{})
  70. })
  71. }
  72. actual = actual[:scale]
  73. }
  74. expected, err := jsonHash(service)
  75. if err != nil {
  76. return err
  77. }
  78. for _, container := range actual {
  79. container := container
  80. diverged := container.Labels[configHashLabel] != expected
  81. if diverged || service.Extensions[extLifecycle] == forceRecreate {
  82. eg.Go(func() error {
  83. return s.recreateContainer(ctx, project, service, container)
  84. })
  85. continue
  86. }
  87. if container.State == "running" {
  88. // already running, skip
  89. continue
  90. }
  91. eg.Go(func() error {
  92. return s.restartContainer(ctx, service, container)
  93. })
  94. }
  95. return eg.Wait()
  96. }
  97. func (s *composeService) waitDependencies(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
  98. eg, _ := errgroup.WithContext(ctx)
  99. for dep, config := range service.DependsOn {
  100. switch config.Condition {
  101. case "service_healthy":
  102. eg.Go(func() error {
  103. ticker := time.NewTicker(500 * time.Millisecond)
  104. defer ticker.Stop()
  105. for {
  106. <-ticker.C
  107. healthy, err := s.isServiceHealthy(ctx, project, dep)
  108. if err != nil {
  109. return err
  110. }
  111. if healthy {
  112. return nil
  113. }
  114. }
  115. })
  116. }
  117. }
  118. return eg.Wait()
  119. }
  120. func nextContainerNumber(containers []moby.Container) (int, error) {
  121. max := 0
  122. for _, c := range containers {
  123. n, err := strconv.Atoi(c.Labels[containerNumberLabel])
  124. if err != nil {
  125. return 0, err
  126. }
  127. if n > max {
  128. max = n
  129. }
  130. }
  131. return max + 1, nil
  132. }
  133. func getScale(config types.ServiceConfig) int {
  134. if config.Deploy != nil && config.Deploy.Replicas != nil {
  135. return int(*config.Deploy.Replicas)
  136. }
  137. if config.Scale != 0 {
  138. return config.Scale
  139. }
  140. return 1
  141. }
  142. func (s *composeService) createContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, name string, number int) error {
  143. eventName := fmt.Sprintf("Service %q", service.Name)
  144. w := progress.ContextWriter(ctx)
  145. w.Event(progress.CreatingEvent(eventName))
  146. err := s.runContainer(ctx, project, service, name, number, nil)
  147. if err != nil {
  148. return err
  149. }
  150. w.Event(progress.CreatedEvent(eventName))
  151. return nil
  152. }
  153. func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, container moby.Container) error {
  154. w := progress.ContextWriter(ctx)
  155. eventName := fmt.Sprintf("Service %q", service.Name)
  156. w.Event(progress.NewEvent(eventName, progress.Working, "Recreate"))
  157. err := s.apiClient.ContainerStop(ctx, container.ID, nil)
  158. if err != nil {
  159. return err
  160. }
  161. name := getContainerName(container)
  162. tmpName := fmt.Sprintf("%s_%s", container.ID[:12], name)
  163. err = s.apiClient.ContainerRename(ctx, container.ID, tmpName)
  164. if err != nil {
  165. return err
  166. }
  167. number, err := strconv.Atoi(container.Labels[containerNumberLabel])
  168. if err != nil {
  169. return err
  170. }
  171. err = s.runContainer(ctx, project, service, name, number, &container)
  172. if err != nil {
  173. return err
  174. }
  175. err = s.apiClient.ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{})
  176. if err != nil {
  177. return err
  178. }
  179. w.Event(progress.NewEvent(eventName, progress.Done, "Recreated"))
  180. setDependentLifecycle(project, service.Name, forceRecreate)
  181. return nil
  182. }
  183. // setDependentLifecycle define the Lifecycle strategy for all services to depend on specified service
  184. func setDependentLifecycle(project *types.Project, service string, strategy string) {
  185. for i, s := range project.Services {
  186. if contains(s.GetDependencies(), service) {
  187. if s.Extensions == nil {
  188. s.Extensions = map[string]interface{}{}
  189. }
  190. s.Extensions[extLifecycle] = strategy
  191. project.Services[i] = s
  192. }
  193. }
  194. }
  195. func (s *composeService) restartContainer(ctx context.Context, service types.ServiceConfig, container moby.Container) error {
  196. w := progress.ContextWriter(ctx)
  197. eventName := fmt.Sprintf("Service %q", service.Name)
  198. w.Event(progress.NewEvent(eventName, progress.Working, "Restart"))
  199. err := s.apiClient.ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  200. if err != nil {
  201. return err
  202. }
  203. w.Event(progress.NewEvent(eventName, progress.Done, "Restarted"))
  204. return nil
  205. }
  206. func (s *composeService) runContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, name string, number int, container *moby.Container) error {
  207. containerConfig, hostConfig, networkingConfig, err := getContainerCreateOptions(project, service, number, container)
  208. if err != nil {
  209. return err
  210. }
  211. created, err := s.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, name)
  212. if err != nil {
  213. return err
  214. }
  215. id := created.ID
  216. for netName := range service.Networks {
  217. network := project.Networks[netName]
  218. err = s.connectContainerToNetwork(ctx, id, service.Name, network.Name)
  219. if err != nil {
  220. return err
  221. }
  222. }
  223. err = s.apiClient.ContainerStart(ctx, id, moby.ContainerStartOptions{})
  224. if err != nil {
  225. return err
  226. }
  227. return nil
  228. }
  229. func (s *composeService) connectContainerToNetwork(ctx context.Context, id string, service string, n string) error {
  230. err := s.apiClient.NetworkConnect(ctx, n, id, &network.EndpointSettings{
  231. Aliases: []string{service},
  232. })
  233. if err != nil {
  234. return err
  235. }
  236. return nil
  237. }
  238. func (s *composeService) isServiceHealthy(ctx context.Context, project *types.Project, service string) (bool, error) {
  239. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  240. Filters: filters.NewArgs(
  241. filters.Arg("label", fmt.Sprintf("%s=%s", projectLabel, project.Name)),
  242. filters.Arg("label", fmt.Sprintf("%s=%s", serviceLabel, service)),
  243. ),
  244. })
  245. if err != nil {
  246. return false, err
  247. }
  248. for _, c := range containers {
  249. container, err := s.apiClient.ContainerInspect(ctx, c.ID)
  250. if err != nil {
  251. return false, err
  252. }
  253. if container.State == nil || container.State.Health == nil {
  254. return false, fmt.Errorf("container for service %q has no healthcheck configured", service)
  255. }
  256. switch container.State.Health.Status {
  257. case "starting":
  258. return false, nil
  259. case "unhealthy":
  260. return false, nil
  261. }
  262. }
  263. return true, nil
  264. }