convergence.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. "strconv"
  18. "time"
  19. "github.com/compose-spec/compose-go/types"
  20. "github.com/containerd/containerd/platforms"
  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. specs "github.com/opencontainers/image-spec/specs-go/v1"
  25. "golang.org/x/sync/errgroup"
  26. "github.com/docker/compose-cli/api/compose"
  27. "github.com/docker/compose-cli/api/progress"
  28. status "github.com/docker/compose-cli/local/moby"
  29. "github.com/docker/compose-cli/utils"
  30. )
  31. const (
  32. extLifecycle = "x-lifecycle"
  33. forceRecreate = "force_recreate"
  34. doubledContainerNameWarning = "WARNING: The %q service is using the custom container name %q. " +
  35. "Docker requires each container to have a unique name. " +
  36. "Remove the custom name to scale the service.\n"
  37. )
  38. func (s *composeService) ensureScale(ctx context.Context, project *types.Project, service types.ServiceConfig, timeout *time.Duration) (*errgroup.Group, []moby.Container, error) {
  39. cState, err := GetContextContainerState(ctx)
  40. if err != nil {
  41. return nil, nil, err
  42. }
  43. observedState := cState.GetContainers()
  44. actual := observedState.filter(isService(service.Name))
  45. scale, err := getScale(service)
  46. if err != nil {
  47. return nil, nil, err
  48. }
  49. eg, _ := errgroup.WithContext(ctx)
  50. if len(actual) < scale {
  51. next, err := nextContainerNumber(actual)
  52. if err != nil {
  53. return nil, actual, err
  54. }
  55. missing := scale - len(actual)
  56. for i := 0; i < missing; i++ {
  57. number := next + i
  58. name := getContainerName(project.Name, service, number)
  59. eg.Go(func() error {
  60. return s.createContainer(ctx, project, service, name, number, false, true)
  61. })
  62. }
  63. }
  64. if len(actual) > scale {
  65. for i := scale; i < len(actual); i++ {
  66. container := actual[i]
  67. eg.Go(func() error {
  68. err := s.apiClient.ContainerStop(ctx, container.ID, timeout)
  69. if err != nil {
  70. return err
  71. }
  72. return s.apiClient.ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{})
  73. })
  74. }
  75. actual = actual[:scale]
  76. }
  77. return eg, actual, nil
  78. }
  79. func (s *composeService) ensureService(ctx context.Context, project *types.Project, service types.ServiceConfig, recreate string, inherit bool, timeout *time.Duration) error {
  80. eg, actual, err := s.ensureScale(ctx, project, service, timeout)
  81. if err != nil {
  82. return err
  83. }
  84. if recreate == compose.RecreateNever {
  85. return nil
  86. }
  87. expected, err := utils.ServiceHash(service)
  88. if err != nil {
  89. return err
  90. }
  91. for _, container := range actual {
  92. name := getContainerProgressName(container)
  93. diverged := container.Labels[configHashLabel] != expected
  94. if diverged || recreate == compose.RecreateForce || service.Extensions[extLifecycle] == forceRecreate {
  95. eg.Go(func() error {
  96. return s.recreateContainer(ctx, project, service, container, inherit, timeout)
  97. })
  98. continue
  99. }
  100. w := progress.ContextWriter(ctx)
  101. switch container.State {
  102. case status.ContainerRunning:
  103. w.Event(progress.RunningEvent(name))
  104. case status.ContainerCreated:
  105. case status.ContainerRestarting:
  106. case status.ContainerExited:
  107. w.Event(progress.CreatedEvent(name))
  108. default:
  109. eg.Go(func() error {
  110. return s.restartContainer(ctx, container)
  111. })
  112. }
  113. }
  114. return eg.Wait()
  115. }
  116. func getContainerName(projectName string, service types.ServiceConfig, number int) string {
  117. name := fmt.Sprintf("%s_%s_%d", projectName, service.Name, number)
  118. if service.ContainerName != "" {
  119. name = service.ContainerName
  120. }
  121. return name
  122. }
  123. func getContainerProgressName(container moby.Container) string {
  124. return "Container " + getCanonicalContainerName(container)
  125. }
  126. func (s *composeService) waitDependencies(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
  127. eg, _ := errgroup.WithContext(ctx)
  128. for dep, config := range service.DependsOn {
  129. switch config.Condition {
  130. case "service_healthy":
  131. eg.Go(func() error {
  132. ticker := time.NewTicker(500 * time.Millisecond)
  133. defer ticker.Stop()
  134. for {
  135. <-ticker.C
  136. healthy, err := s.isServiceHealthy(ctx, project, dep)
  137. if err != nil {
  138. return err
  139. }
  140. if healthy {
  141. return nil
  142. }
  143. }
  144. })
  145. }
  146. }
  147. return eg.Wait()
  148. }
  149. func nextContainerNumber(containers []moby.Container) (int, error) {
  150. max := 0
  151. for _, c := range containers {
  152. n, err := strconv.Atoi(c.Labels[containerNumberLabel])
  153. if err != nil {
  154. return 0, err
  155. }
  156. if n > max {
  157. max = n
  158. }
  159. }
  160. return max + 1, nil
  161. }
  162. func getScale(config types.ServiceConfig) (int, error) {
  163. scale := 1
  164. var err error
  165. if config.Deploy != nil && config.Deploy.Replicas != nil {
  166. scale = int(*config.Deploy.Replicas)
  167. }
  168. if config.Scale != 0 {
  169. scale = config.Scale
  170. }
  171. if scale > 1 && config.ContainerName != "" {
  172. scale = -1
  173. err = fmt.Errorf(doubledContainerNameWarning,
  174. config.Name,
  175. config.ContainerName)
  176. }
  177. return scale, err
  178. }
  179. func (s *composeService) createContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, name string, number int, autoRemove bool, useNetworkAliases bool) error {
  180. w := progress.ContextWriter(ctx)
  181. eventName := "Container " + name
  182. w.Event(progress.CreatingEvent(eventName))
  183. err := s.createMobyContainer(ctx, project, service, name, number, nil, autoRemove, useNetworkAliases)
  184. if err != nil {
  185. return err
  186. }
  187. w.Event(progress.CreatedEvent(eventName))
  188. return nil
  189. }
  190. func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, container moby.Container, inherit bool, timeout *time.Duration) error {
  191. w := progress.ContextWriter(ctx)
  192. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Working, "Recreate"))
  193. err := s.apiClient.ContainerStop(ctx, container.ID, timeout)
  194. if err != nil {
  195. return err
  196. }
  197. name := getCanonicalContainerName(container)
  198. tmpName := fmt.Sprintf("%s_%s", container.ID[:12], name)
  199. err = s.apiClient.ContainerRename(ctx, container.ID, tmpName)
  200. if err != nil {
  201. return err
  202. }
  203. number, err := strconv.Atoi(container.Labels[containerNumberLabel])
  204. if err != nil {
  205. return err
  206. }
  207. var inherited *moby.Container
  208. if inherit {
  209. inherited = &container
  210. }
  211. err = s.createMobyContainer(ctx, project, service, name, number, inherited, false, true)
  212. if err != nil {
  213. return err
  214. }
  215. err = s.apiClient.ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{})
  216. if err != nil {
  217. return err
  218. }
  219. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Done, "Recreated"))
  220. setDependentLifecycle(project, service.Name, forceRecreate)
  221. return nil
  222. }
  223. // setDependentLifecycle define the Lifecycle strategy for all services to depend on specified service
  224. func setDependentLifecycle(project *types.Project, service string, strategy string) {
  225. for i, s := range project.Services {
  226. if utils.StringContains(s.GetDependencies(), service) {
  227. if s.Extensions == nil {
  228. s.Extensions = map[string]interface{}{}
  229. }
  230. s.Extensions[extLifecycle] = strategy
  231. project.Services[i] = s
  232. }
  233. }
  234. }
  235. func (s *composeService) restartContainer(ctx context.Context, container moby.Container) error {
  236. w := progress.ContextWriter(ctx)
  237. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Working, "Restart"))
  238. err := s.apiClient.ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  239. if err != nil {
  240. return err
  241. }
  242. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Done, "Restarted"))
  243. return nil
  244. }
  245. func (s *composeService) createMobyContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, name string, number int,
  246. inherit *moby.Container,
  247. autoRemove bool,
  248. useNetworkAliases bool) error {
  249. cState, err := GetContextContainerState(ctx)
  250. if err != nil {
  251. return err
  252. }
  253. containerConfig, hostConfig, networkingConfig, err := s.getCreateOptions(ctx, project, service, number, inherit, autoRemove)
  254. if err != nil {
  255. return err
  256. }
  257. var plat *specs.Platform
  258. if service.Platform != "" {
  259. p, err := platforms.Parse(service.Platform)
  260. if err != nil {
  261. return err
  262. }
  263. plat = &p
  264. }
  265. created, err := s.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, plat, name)
  266. if err != nil {
  267. return err
  268. }
  269. createdContainer := moby.Container{
  270. ID: created.ID,
  271. Labels: containerConfig.Labels,
  272. }
  273. cState.Add(createdContainer)
  274. for netName, cfg := range service.Networks {
  275. netwrk := project.Networks[netName]
  276. aliases := []string{getContainerName(project.Name, service, number)}
  277. if useNetworkAliases {
  278. aliases = append(aliases, service.Name)
  279. if cfg != nil {
  280. aliases = append(aliases, cfg.Aliases...)
  281. }
  282. }
  283. err = s.connectContainerToNetwork(ctx, created.ID, netwrk.Name, aliases...)
  284. if err != nil {
  285. return err
  286. }
  287. }
  288. return nil
  289. }
  290. func (s *composeService) connectContainerToNetwork(ctx context.Context, id string, netwrk string, aliases ...string) error {
  291. err := s.apiClient.NetworkConnect(ctx, netwrk, id, &network.EndpointSettings{
  292. Aliases: aliases,
  293. })
  294. if err != nil {
  295. return err
  296. }
  297. return nil
  298. }
  299. func (s *composeService) isServiceHealthy(ctx context.Context, project *types.Project, service string) (bool, error) {
  300. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  301. Filters: filters.NewArgs(
  302. filters.Arg("label", fmt.Sprintf("%s=%s", projectLabel, project.Name)),
  303. filters.Arg("label", fmt.Sprintf("%s=%s", serviceLabel, service)),
  304. ),
  305. })
  306. if err != nil {
  307. return false, err
  308. }
  309. for _, c := range containers {
  310. container, err := s.apiClient.ContainerInspect(ctx, c.ID)
  311. if err != nil {
  312. return false, err
  313. }
  314. if container.State == nil || container.State.Health == nil {
  315. return false, fmt.Errorf("container for service %q has no healthcheck configured", service)
  316. }
  317. switch container.State.Health.Status {
  318. case "starting":
  319. return false, nil
  320. case "unhealthy":
  321. return false, nil
  322. }
  323. }
  324. return true, nil
  325. }
  326. func (s *composeService) startService(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
  327. err := s.waitDependencies(ctx, project, service)
  328. if err != nil {
  329. return err
  330. }
  331. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  332. Filters: filters.NewArgs(
  333. projectFilter(project.Name),
  334. serviceFilter(service.Name),
  335. ),
  336. All: true,
  337. })
  338. if err != nil {
  339. return err
  340. }
  341. w := progress.ContextWriter(ctx)
  342. eg, ctx := errgroup.WithContext(ctx)
  343. for _, c := range containers {
  344. container := c
  345. if container.State == status.ContainerRunning {
  346. continue
  347. }
  348. eg.Go(func() error {
  349. eventName := getContainerProgressName(container)
  350. w.Event(progress.StartingEvent(eventName))
  351. err := s.apiClient.ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  352. if err == nil {
  353. w.Event(progress.StartedEvent(eventName))
  354. }
  355. return err
  356. })
  357. }
  358. return eg.Wait()
  359. }