compose.go 7.7 KB

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