compose.go 7.5 KB

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