compose.go 7.6 KB

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