compose.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. // Names return container canonical name /foo + link aliases /linked_by/foo
  59. for _, name := range c.Names {
  60. if strings.LastIndex(name, "/") == 0 {
  61. return name[1:]
  62. }
  63. }
  64. return c.Names[0][1:]
  65. }
  66. func getContainerNameWithoutProject(c moby.Container) string {
  67. name := getCanonicalContainerName(c)
  68. project := c.Labels[api.ProjectLabel]
  69. prefix := fmt.Sprintf("%s_%s_", project, c.Labels[api.ServiceLabel])
  70. if strings.HasPrefix(name, prefix) {
  71. return name[len(project)+1:]
  72. }
  73. return name
  74. }
  75. func (s *composeService) Convert(ctx context.Context, project *types.Project, options api.ConvertOptions) ([]byte, error) {
  76. switch options.Format {
  77. case "json":
  78. marshal, err := json.MarshalIndent(project, "", " ")
  79. if err != nil {
  80. return nil, err
  81. }
  82. return escapeDollarSign(marshal), nil
  83. case "yaml":
  84. marshal, err := yaml.Marshal(project)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return escapeDollarSign(marshal), nil
  89. default:
  90. return nil, fmt.Errorf("unsupported format %q", options)
  91. }
  92. }
  93. func escapeDollarSign(marshal []byte) []byte {
  94. dollar := []byte{'$'}
  95. escDollar := []byte{'$', '$'}
  96. return bytes.ReplaceAll(marshal, dollar, escDollar)
  97. }
  98. // projectFromName builds a types.Project based on actual resources with compose labels set
  99. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  100. project := &types.Project{
  101. Name: projectName,
  102. }
  103. if len(containers) == 0 {
  104. return project, errors.New("no such project: " + projectName)
  105. }
  106. set := map[string]*types.ServiceConfig{}
  107. for _, c := range containers {
  108. serviceLabel := c.Labels[api.ServiceLabel]
  109. _, ok := set[serviceLabel]
  110. if !ok {
  111. set[serviceLabel] = &types.ServiceConfig{
  112. Name: serviceLabel,
  113. Image: c.Image,
  114. Labels: c.Labels,
  115. }
  116. }
  117. set[serviceLabel].Scale++
  118. }
  119. for _, service := range set {
  120. dependencies := service.Labels[api.DependenciesLabel]
  121. if len(dependencies) > 0 {
  122. service.DependsOn = types.DependsOnConfig{}
  123. for _, dc := range strings.Split(dependencies, ",") {
  124. dcArr := strings.Split(dc, ":")
  125. condition := ServiceConditionRunningOrHealthy
  126. dependency := dcArr[0]
  127. // backward compatibility
  128. if len(dcArr) > 1 {
  129. condition = dcArr[1]
  130. }
  131. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition}
  132. }
  133. }
  134. project.Services = append(project.Services, *service)
  135. }
  136. SERVICES:
  137. for _, qs := range services {
  138. for _, es := range project.Services {
  139. if es.Name == qs {
  140. continue SERVICES
  141. }
  142. }
  143. return project, errors.New("no such service: " + qs)
  144. }
  145. err := project.ForServices(services)
  146. if err != nil {
  147. return project, err
  148. }
  149. return project, nil
  150. }