compose.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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/docker/docker/api/types/volume"
  23. "github.com/jonboulle/clockwork"
  24. "github.com/compose-spec/compose-go/v2/types"
  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. "github.com/docker/compose/v2/pkg/api"
  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. )
  35. var stdioToStdout bool
  36. func init() {
  37. out, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT")
  38. if ok {
  39. stdioToStdout, _ = strconv.ParseBool(out)
  40. }
  41. }
  42. // NewComposeService create a local implementation of the compose.Service API
  43. func NewComposeService(dockerCli command.Cli) api.Service {
  44. return &composeService{
  45. dockerCli: dockerCli,
  46. clock: clockwork.NewRealClock(),
  47. maxConcurrency: -1,
  48. dryRun: false,
  49. }
  50. }
  51. type composeService struct {
  52. dockerCli command.Cli
  53. clock clockwork.Clock
  54. maxConcurrency int
  55. dryRun bool
  56. }
  57. func (s *composeService) apiClient() client.APIClient {
  58. return s.dockerCli.Client()
  59. }
  60. func (s *composeService) configFile() *configfile.ConfigFile {
  61. return s.dockerCli.ConfigFile()
  62. }
  63. func (s *composeService) MaxConcurrency(i int) {
  64. s.maxConcurrency = i
  65. }
  66. func (s *composeService) DryRunMode(ctx context.Context, dryRun bool) (context.Context, error) {
  67. s.dryRun = dryRun
  68. if dryRun {
  69. cli, err := command.NewDockerCli()
  70. if err != nil {
  71. return ctx, err
  72. }
  73. options := flags.NewClientOptions()
  74. options.Context = s.dockerCli.CurrentContext()
  75. err = cli.Initialize(options, command.WithInitializeClient(func(cli *command.DockerCli) (client.APIClient, error) {
  76. return api.NewDryRunClient(s.apiClient(), s.dockerCli)
  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 strings.TrimPrefix(c.Names[0], "/")
  112. }
  113. func getContainerNameWithoutProject(c moby.Container) string {
  114. project := c.Labels[api.ProjectLabel]
  115. defaultName := getDefaultContainerName(project, c.Labels[api.ServiceLabel], c.Labels[api.ContainerNumberLabel])
  116. name := getCanonicalContainerName(c)
  117. if name != defaultName {
  118. // service declares a custom container_name
  119. return name
  120. }
  121. return name[len(project)+1:]
  122. }
  123. // projectFromName builds a types.Project based on actual resources with compose labels set
  124. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  125. project := &types.Project{
  126. Name: projectName,
  127. Services: types.Services{},
  128. }
  129. if len(containers) == 0 {
  130. return project, fmt.Errorf("no container found for project %q: %w", projectName, api.ErrNotFound)
  131. }
  132. set := types.Services{}
  133. for _, c := range containers {
  134. serviceLabel := c.Labels[api.ServiceLabel]
  135. service, ok := set[serviceLabel]
  136. if !ok {
  137. service = types.ServiceConfig{
  138. Name: serviceLabel,
  139. Image: c.Image,
  140. Labels: c.Labels,
  141. }
  142. }
  143. service.Scale = increment(service.Scale)
  144. set[serviceLabel] = service
  145. }
  146. for name, service := range set {
  147. dependencies := service.Labels[api.DependenciesLabel]
  148. if len(dependencies) > 0 {
  149. service.DependsOn = types.DependsOnConfig{}
  150. for _, dc := range strings.Split(dependencies, ",") {
  151. dcArr := strings.Split(dc, ":")
  152. condition := ServiceConditionRunningOrHealthy
  153. // Let's restart the dependency by default if we don't have the info stored in the label
  154. restart := true
  155. required := true
  156. dependency := dcArr[0]
  157. // backward compatibility
  158. if len(dcArr) > 1 {
  159. condition = dcArr[1]
  160. if len(dcArr) > 2 {
  161. restart, _ = strconv.ParseBool(dcArr[2])
  162. }
  163. }
  164. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required}
  165. }
  166. set[name] = service
  167. }
  168. }
  169. project.Services = set
  170. SERVICES:
  171. for _, qs := range services {
  172. for _, es := range project.Services {
  173. if es.Name == qs {
  174. continue SERVICES
  175. }
  176. }
  177. return project, fmt.Errorf("no such service: %q: %w", qs, api.ErrNotFound)
  178. }
  179. project, err := project.WithSelectedServices(services)
  180. if err != nil {
  181. return project, err
  182. }
  183. return project, nil
  184. }
  185. func increment(scale *int) *int {
  186. i := 1
  187. if scale != nil {
  188. i = *scale + 1
  189. }
  190. return &i
  191. }
  192. func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) {
  193. opts := volume.ListOptions{
  194. Filters: filters.NewArgs(projectFilter(projectName)),
  195. }
  196. volumes, err := s.apiClient().VolumeList(ctx, opts)
  197. if err != nil {
  198. return nil, err
  199. }
  200. actual := types.Volumes{}
  201. for _, vol := range volumes.Volumes {
  202. actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{
  203. Name: vol.Name,
  204. Driver: vol.Driver,
  205. Labels: vol.Labels,
  206. }
  207. }
  208. return actual, nil
  209. }
  210. func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) {
  211. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  212. Filters: filters.NewArgs(projectFilter(projectName)),
  213. })
  214. if err != nil {
  215. return nil, err
  216. }
  217. actual := types.Networks{}
  218. for _, net := range networks {
  219. actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{
  220. Name: net.Name,
  221. Driver: net.Driver,
  222. Labels: net.Labels,
  223. }
  224. }
  225. return actual, nil
  226. }
  227. var swarmEnabled = struct {
  228. once sync.Once
  229. val bool
  230. err error
  231. }{}
  232. func (s *composeService) isSWarmEnabled(ctx context.Context) (bool, error) {
  233. swarmEnabled.once.Do(func() {
  234. info, err := s.apiClient().Info(ctx)
  235. if err != nil {
  236. swarmEnabled.err = err
  237. }
  238. switch info.Swarm.LocalNodeState {
  239. case swarm.LocalNodeStateInactive, swarm.LocalNodeStateLocked:
  240. swarmEnabled.val = false
  241. default:
  242. swarmEnabled.val = true
  243. }
  244. })
  245. return swarmEnabled.val, swarmEnabled.err
  246. }
  247. type runtimeVersionCache struct {
  248. once sync.Once
  249. val string
  250. err error
  251. }
  252. var runtimeVersion runtimeVersionCache
  253. func (s *composeService) RuntimeVersion(ctx context.Context) (string, error) {
  254. runtimeVersion.once.Do(func() {
  255. version, err := s.dockerCli.Client().ServerVersion(ctx)
  256. if err != nil {
  257. runtimeVersion.err = err
  258. }
  259. runtimeVersion.val = version.APIVersion
  260. })
  261. return runtimeVersion.val, runtimeVersion.err
  262. }