compose.go 6.9 KB

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