compose.go 6.5 KB

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