compose.go 7.4 KB

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