compose.go 6.7 KB

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