compose.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. "encoding/json"
  17. "fmt"
  18. "io"
  19. "strings"
  20. "github.com/compose-spec/compose-go/types"
  21. "github.com/distribution/distribution/v3/reference"
  22. "github.com/docker/cli/cli/command"
  23. "github.com/docker/cli/cli/config/configfile"
  24. "github.com/docker/cli/cli/streams"
  25. moby "github.com/docker/docker/api/types"
  26. "github.com/docker/docker/api/types/filters"
  27. "github.com/docker/docker/client"
  28. "github.com/opencontainers/go-digest"
  29. "github.com/pkg/errors"
  30. "gopkg.in/yaml.v2"
  31. "github.com/docker/compose/v2/pkg/api"
  32. )
  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. maxConcurrency: -1,
  38. }
  39. }
  40. type composeService struct {
  41. dockerCli command.Cli
  42. maxConcurrency int
  43. }
  44. func (s *composeService) apiClient() client.APIClient {
  45. return s.dockerCli.Client()
  46. }
  47. func (s *composeService) configFile() *configfile.ConfigFile {
  48. return s.dockerCli.ConfigFile()
  49. }
  50. func (s *composeService) MaxConcurrency(i int) {
  51. s.maxConcurrency = i
  52. }
  53. func (s *composeService) stdout() *streams.Out {
  54. return s.dockerCli.Out()
  55. }
  56. func (s *composeService) stdin() *streams.In {
  57. return s.dockerCli.In()
  58. }
  59. func (s *composeService) stderr() io.Writer {
  60. return s.dockerCli.Err()
  61. }
  62. func getCanonicalContainerName(c moby.Container) string {
  63. if len(c.Names) == 0 {
  64. // corner case, sometime happens on removal. return short ID as a safeguard value
  65. return c.ID[:12]
  66. }
  67. // Names return container canonical name /foo + link aliases /linked_by/foo
  68. for _, name := range c.Names {
  69. if strings.LastIndex(name, "/") == 0 {
  70. return name[1:]
  71. }
  72. }
  73. return c.Names[0][1:]
  74. }
  75. func getContainerNameWithoutProject(c moby.Container) string {
  76. name := getCanonicalContainerName(c)
  77. project := c.Labels[api.ProjectLabel]
  78. prefix := fmt.Sprintf("%s_%s_", project, c.Labels[api.ServiceLabel])
  79. if strings.HasPrefix(name, prefix) {
  80. return name[len(project)+1:]
  81. }
  82. return name
  83. }
  84. func (s *composeService) Convert(ctx context.Context, project *types.Project, options api.ConvertOptions) ([]byte, error) {
  85. if options.ResolveImageDigests {
  86. info, err := s.apiClient().Info(ctx)
  87. if err != nil {
  88. return nil, err
  89. }
  90. err = project.ResolveImages(func(named reference.Named) (digest.Digest, error) {
  91. auth, err := encodedAuth(named, info, s.configFile())
  92. if err != nil {
  93. return "", err
  94. }
  95. inspect, err := s.apiClient().DistributionInspect(ctx, named.String(), auth)
  96. if err != nil {
  97. return "", err
  98. }
  99. return inspect.Descriptor.Digest, nil
  100. })
  101. if err != nil {
  102. return nil, err
  103. }
  104. }
  105. switch options.Format {
  106. case "json":
  107. return json.MarshalIndent(project, "", " ")
  108. case "yaml":
  109. return yaml.Marshal(project)
  110. default:
  111. return nil, fmt.Errorf("unsupported format %q", options.Format)
  112. }
  113. }
  114. // projectFromName builds a types.Project based on actual resources with compose labels set
  115. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  116. project := &types.Project{
  117. Name: projectName,
  118. }
  119. if len(containers) == 0 {
  120. return project, errors.Wrap(api.ErrNotFound, fmt.Sprintf("no container found for project %q", projectName))
  121. }
  122. set := map[string]*types.ServiceConfig{}
  123. for _, c := range containers {
  124. serviceLabel := c.Labels[api.ServiceLabel]
  125. _, ok := set[serviceLabel]
  126. if !ok {
  127. set[serviceLabel] = &types.ServiceConfig{
  128. Name: serviceLabel,
  129. Image: c.Image,
  130. Labels: c.Labels,
  131. }
  132. }
  133. set[serviceLabel].Scale++
  134. }
  135. for _, service := range set {
  136. dependencies := service.Labels[api.DependenciesLabel]
  137. if len(dependencies) > 0 {
  138. service.DependsOn = types.DependsOnConfig{}
  139. for _, dc := range strings.Split(dependencies, ",") {
  140. dcArr := strings.Split(dc, ":")
  141. condition := ServiceConditionRunningOrHealthy
  142. dependency := dcArr[0]
  143. // backward compatibility
  144. if len(dcArr) > 1 {
  145. condition = dcArr[1]
  146. }
  147. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition}
  148. }
  149. }
  150. project.Services = append(project.Services, *service)
  151. }
  152. SERVICES:
  153. for _, qs := range services {
  154. for _, es := range project.Services {
  155. if es.Name == qs {
  156. continue SERVICES
  157. }
  158. }
  159. return project, errors.Wrapf(api.ErrNotFound, "no such service: %q", qs)
  160. }
  161. err := project.ForServices(services)
  162. if err != nil {
  163. return project, err
  164. }
  165. return project, nil
  166. }
  167. func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) {
  168. volumes, err := s.apiClient().VolumeList(ctx, filters.NewArgs(projectFilter(projectName)))
  169. if err != nil {
  170. return nil, err
  171. }
  172. actual := types.Volumes{}
  173. for _, vol := range volumes.Volumes {
  174. actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{
  175. Name: vol.Name,
  176. Driver: vol.Driver,
  177. Labels: vol.Labels,
  178. }
  179. }
  180. return actual, nil
  181. }
  182. func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) {
  183. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  184. Filters: filters.NewArgs(projectFilter(projectName)),
  185. })
  186. if err != nil {
  187. return nil, err
  188. }
  189. actual := types.Networks{}
  190. for _, net := range networks {
  191. actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{
  192. Name: net.Name,
  193. Driver: net.Driver,
  194. Labels: net.Labels,
  195. }
  196. }
  197. return actual, nil
  198. }