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