convergence.go 12 KB

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