compose.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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/v2/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. )
  37. var stdioToStdout bool
  38. func init() {
  39. out, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT")
  40. if ok {
  41. stdioToStdout, _ = strconv.ParseBool(out)
  42. }
  43. }
  44. // NewComposeService create a local implementation of the compose.Service API
  45. func NewComposeService(dockerCli command.Cli) api.Service {
  46. return &composeService{
  47. dockerCli: dockerCli,
  48. clock: clockwork.NewRealClock(),
  49. maxConcurrency: -1,
  50. dryRun: false,
  51. }
  52. }
  53. type composeService struct {
  54. dockerCli command.Cli
  55. clock clockwork.Clock
  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. project := c.Labels[api.ProjectLabel]
  117. defaultName := getDefaultContainerName(project, c.Labels[api.ServiceLabel], c.Labels[api.ContainerNumberLabel])
  118. name := getCanonicalContainerName(c)
  119. if name != defaultName {
  120. // service declares a custom container_name
  121. return name
  122. }
  123. return name[len(project)+1:]
  124. }
  125. func (s *composeService) Config(ctx context.Context, project *types.Project, options api.ConfigOptions) ([]byte, error) {
  126. if options.ResolveImageDigests {
  127. var err error
  128. project, err = project.WithImagesResolved(func(named reference.Named) (digest.Digest, error) {
  129. auth, err := encodedAuth(named, s.configFile())
  130. if err != nil {
  131. return "", err
  132. }
  133. inspect, err := s.apiClient().DistributionInspect(ctx, named.String(), auth)
  134. if err != nil {
  135. return "", err
  136. }
  137. return inspect.Descriptor.Digest, nil
  138. })
  139. if err != nil {
  140. return nil, err
  141. }
  142. }
  143. switch options.Format {
  144. case "json":
  145. return project.MarshalJSON()
  146. case "yaml":
  147. return project.MarshalYAML()
  148. default:
  149. return nil, fmt.Errorf("unsupported format %q", options.Format)
  150. }
  151. }
  152. // projectFromName builds a types.Project based on actual resources with compose labels set
  153. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  154. project := &types.Project{
  155. Name: projectName,
  156. Services: types.Services{},
  157. }
  158. if len(containers) == 0 {
  159. return project, fmt.Errorf("no container found for project %q: %w", projectName, api.ErrNotFound)
  160. }
  161. set := types.Services{}
  162. for _, c := range containers {
  163. serviceLabel := c.Labels[api.ServiceLabel]
  164. service, ok := set[serviceLabel]
  165. if !ok {
  166. service = types.ServiceConfig{
  167. Name: serviceLabel,
  168. Image: c.Image,
  169. Labels: c.Labels,
  170. }
  171. }
  172. service.Scale = increment(service.Scale)
  173. set[serviceLabel] = service
  174. }
  175. for name, service := range set {
  176. dependencies := service.Labels[api.DependenciesLabel]
  177. if len(dependencies) > 0 {
  178. service.DependsOn = types.DependsOnConfig{}
  179. for _, dc := range strings.Split(dependencies, ",") {
  180. dcArr := strings.Split(dc, ":")
  181. condition := ServiceConditionRunningOrHealthy
  182. // Let's restart the dependency by default if we don't have the info stored in the label
  183. restart := true
  184. required := true
  185. dependency := dcArr[0]
  186. // backward compatibility
  187. if len(dcArr) > 1 {
  188. condition = dcArr[1]
  189. if len(dcArr) > 2 {
  190. restart, _ = strconv.ParseBool(dcArr[2])
  191. }
  192. }
  193. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required}
  194. }
  195. set[name] = service
  196. }
  197. }
  198. project.Services = set
  199. SERVICES:
  200. for _, qs := range services {
  201. for _, es := range project.Services {
  202. if es.Name == qs {
  203. continue SERVICES
  204. }
  205. }
  206. return project, fmt.Errorf("no such service: %q: %w", qs, api.ErrNotFound)
  207. }
  208. project, err := project.WithSelectedServices(services)
  209. if err != nil {
  210. return project, err
  211. }
  212. return project, nil
  213. }
  214. func increment(scale *int) *int {
  215. i := 1
  216. if scale != nil {
  217. i = *scale + 1
  218. }
  219. return &i
  220. }
  221. func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) {
  222. opts := volume.ListOptions{
  223. Filters: filters.NewArgs(projectFilter(projectName)),
  224. }
  225. volumes, err := s.apiClient().VolumeList(ctx, opts)
  226. if err != nil {
  227. return nil, err
  228. }
  229. actual := types.Volumes{}
  230. for _, vol := range volumes.Volumes {
  231. actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{
  232. Name: vol.Name,
  233. Driver: vol.Driver,
  234. Labels: vol.Labels,
  235. }
  236. }
  237. return actual, nil
  238. }
  239. func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) {
  240. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  241. Filters: filters.NewArgs(projectFilter(projectName)),
  242. })
  243. if err != nil {
  244. return nil, err
  245. }
  246. actual := types.Networks{}
  247. for _, net := range networks {
  248. actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{
  249. Name: net.Name,
  250. Driver: net.Driver,
  251. Labels: net.Labels,
  252. }
  253. }
  254. return actual, nil
  255. }
  256. var swarmEnabled = struct {
  257. once sync.Once
  258. val bool
  259. err error
  260. }{}
  261. func (s *composeService) isSWarmEnabled(ctx context.Context) (bool, error) {
  262. swarmEnabled.once.Do(func() {
  263. info, err := s.apiClient().Info(ctx)
  264. if err != nil {
  265. swarmEnabled.err = err
  266. }
  267. switch info.Swarm.LocalNodeState {
  268. case swarm.LocalNodeStateInactive, swarm.LocalNodeStateLocked:
  269. swarmEnabled.val = false
  270. default:
  271. swarmEnabled.val = true
  272. }
  273. })
  274. return swarmEnabled.val, swarmEnabled.err
  275. }
  276. var runtimeVersion = struct {
  277. once sync.Once
  278. val string
  279. err error
  280. }{}
  281. func (s *composeService) RuntimeVersion(ctx context.Context) (string, error) {
  282. runtimeVersion.once.Do(func() {
  283. version, err := s.dockerCli.Client().ServerVersion(ctx)
  284. if err != nil {
  285. runtimeVersion.err = err
  286. }
  287. runtimeVersion.val = version.APIVersion
  288. })
  289. return runtimeVersion.val, runtimeVersion.err
  290. }