compose.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. "bytes"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "strings"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/pkg/errors"
  23. "github.com/compose-spec/compose-go/types"
  24. "github.com/docker/cli/cli/command"
  25. "github.com/docker/cli/cli/config/configfile"
  26. "github.com/docker/cli/cli/streams"
  27. moby "github.com/docker/docker/api/types"
  28. "github.com/docker/docker/client"
  29. "github.com/sanathkr/go-yaml"
  30. )
  31. // Separator is used for naming components
  32. var Separator = "-"
  33. // NewComposeService create a local implementation of the compose.Service API
  34. func NewComposeService(dockerCli command.Cli) api.Service {
  35. return &composeService{
  36. dockerCli: dockerCli,
  37. }
  38. }
  39. type composeService struct {
  40. dockerCli command.Cli
  41. }
  42. func (s *composeService) apiClient() client.APIClient {
  43. return s.dockerCli.Client()
  44. }
  45. func (s *composeService) configFile() *configfile.ConfigFile {
  46. return s.dockerCli.ConfigFile()
  47. }
  48. func (s *composeService) stdout() *streams.Out {
  49. return s.dockerCli.Out()
  50. }
  51. func (s *composeService) stdin() *streams.In {
  52. return s.dockerCli.In()
  53. }
  54. func (s *composeService) stderr() io.Writer {
  55. return s.dockerCli.Err()
  56. }
  57. func getCanonicalContainerName(c moby.Container) string {
  58. if len(c.Names) == 0 {
  59. // corner case, sometime happens on removal. return short ID as a safeguard value
  60. return c.ID[:12]
  61. }
  62. // Names return container canonical name /foo + link aliases /linked_by/foo
  63. for _, name := range c.Names {
  64. if strings.LastIndex(name, "/") == 0 {
  65. return name[1:]
  66. }
  67. }
  68. return c.Names[0][1:]
  69. }
  70. func getContainerNameWithoutProject(c moby.Container) string {
  71. name := getCanonicalContainerName(c)
  72. project := c.Labels[api.ProjectLabel]
  73. prefix := fmt.Sprintf("%s_%s_", project, c.Labels[api.ServiceLabel])
  74. if strings.HasPrefix(name, prefix) {
  75. return name[len(project)+1:]
  76. }
  77. return name
  78. }
  79. func (s *composeService) Convert(ctx context.Context, project *types.Project, options api.ConvertOptions) ([]byte, error) {
  80. switch options.Format {
  81. case "json":
  82. marshal, err := json.MarshalIndent(project, "", " ")
  83. if err != nil {
  84. return nil, err
  85. }
  86. return escapeDollarSign(marshal), nil
  87. case "yaml":
  88. marshal, err := yaml.Marshal(project)
  89. if err != nil {
  90. return nil, err
  91. }
  92. return escapeDollarSign(marshal), nil
  93. default:
  94. return nil, fmt.Errorf("unsupported format %q", options)
  95. }
  96. }
  97. func escapeDollarSign(marshal []byte) []byte {
  98. dollar := []byte{'$'}
  99. escDollar := []byte{'$', '$'}
  100. return bytes.ReplaceAll(marshal, dollar, escDollar)
  101. }
  102. // projectFromName builds a types.Project based on actual resources with compose labels set
  103. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  104. project := &types.Project{
  105. Name: projectName,
  106. }
  107. if len(containers) == 0 {
  108. return project, errors.Wrap(api.ErrNotFound, fmt.Sprintf("no container found for project %q", projectName))
  109. }
  110. set := map[string]*types.ServiceConfig{}
  111. for _, c := range containers {
  112. serviceLabel := c.Labels[api.ServiceLabel]
  113. _, ok := set[serviceLabel]
  114. if !ok {
  115. set[serviceLabel] = &types.ServiceConfig{
  116. Name: serviceLabel,
  117. Image: c.Image,
  118. Labels: c.Labels,
  119. }
  120. }
  121. set[serviceLabel].Scale++
  122. }
  123. for _, service := range set {
  124. dependencies := service.Labels[api.DependenciesLabel]
  125. if len(dependencies) > 0 {
  126. service.DependsOn = types.DependsOnConfig{}
  127. for _, dc := range strings.Split(dependencies, ",") {
  128. dcArr := strings.Split(dc, ":")
  129. condition := ServiceConditionRunningOrHealthy
  130. dependency := dcArr[0]
  131. // backward compatibility
  132. if len(dcArr) > 1 {
  133. condition = dcArr[1]
  134. }
  135. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition}
  136. }
  137. }
  138. project.Services = append(project.Services, *service)
  139. }
  140. SERVICES:
  141. for _, qs := range services {
  142. for _, es := range project.Services {
  143. if es.Name == qs {
  144. continue SERVICES
  145. }
  146. }
  147. return project, errors.New("no such service: " + qs)
  148. }
  149. err := project.ForServices(services)
  150. if err != nil {
  151. return project, err
  152. }
  153. return project, nil
  154. }
  155. // actualState list resources labelled by projectName to rebuild compose project model
  156. func (s *composeService) actualState(ctx context.Context, projectName string, services []string) (Containers, *types.Project, error) {
  157. var containers Containers
  158. // don't filter containers by options.Services so projectFromName can rebuild project with all existing resources
  159. containers, err := s.getContainers(ctx, projectName, oneOffInclude, true)
  160. if err != nil {
  161. return nil, nil, err
  162. }
  163. project, err := s.projectFromName(containers, projectName, services...)
  164. if err != nil && !api.IsNotFoundError(err) {
  165. return nil, nil, err
  166. }
  167. if len(services) > 0 {
  168. containers = containers.filter(isService(services...))
  169. }
  170. return containers, project, nil
  171. }