compose.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. "errors"
  17. "fmt"
  18. "os"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/docker/cli/cli/command"
  24. "github.com/docker/cli/cli/config/configfile"
  25. "github.com/docker/cli/cli/flags"
  26. "github.com/docker/cli/cli/streams"
  27. "github.com/docker/docker/api/types/container"
  28. "github.com/docker/docker/api/types/filters"
  29. "github.com/docker/docker/api/types/network"
  30. "github.com/docker/docker/api/types/swarm"
  31. "github.com/docker/docker/api/types/volume"
  32. "github.com/docker/docker/client"
  33. "github.com/jonboulle/clockwork"
  34. "github.com/docker/compose/v2/pkg/api"
  35. )
  36. var stdioToStdout bool
  37. func init() {
  38. out, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT")
  39. if ok {
  40. stdioToStdout, _ = strconv.ParseBool(out)
  41. }
  42. }
  43. type Option func(service *composeService)
  44. // NewComposeService create a local implementation of the compose.Compose API
  45. func NewComposeService(dockerCli command.Cli, options ...Option) api.Compose {
  46. s := &composeService{
  47. dockerCli: dockerCli,
  48. clock: clockwork.NewRealClock(),
  49. maxConcurrency: -1,
  50. dryRun: false,
  51. }
  52. for _, option := range options {
  53. option(s)
  54. }
  55. return s
  56. }
  57. // WithPrompt configure a UI component for Compose service to interact with user and confirm actions
  58. func WithPrompt(prompt Prompt) Option {
  59. return func(s *composeService) {
  60. s.prompt = prompt
  61. }
  62. }
  63. type Prompt func(message string, defaultValue bool) (bool, error)
  64. type composeService struct {
  65. dockerCli command.Cli
  66. // prompt is used to interact with user and confirm actions
  67. prompt Prompt
  68. clock clockwork.Clock
  69. maxConcurrency int
  70. dryRun bool
  71. }
  72. // Close releases any connections/resources held by the underlying clients.
  73. //
  74. // In practice, this service has the same lifetime as the process, so everything
  75. // will get cleaned up at about the same time regardless even if not invoked.
  76. func (s *composeService) Close() error {
  77. var errs []error
  78. if s.dockerCli != nil {
  79. errs = append(errs, s.dockerCli.Client().Close())
  80. }
  81. return errors.Join(errs...)
  82. }
  83. func (s *composeService) apiClient() client.APIClient {
  84. return s.dockerCli.Client()
  85. }
  86. func (s *composeService) configFile() *configfile.ConfigFile {
  87. return s.dockerCli.ConfigFile()
  88. }
  89. func (s *composeService) MaxConcurrency(i int) {
  90. s.maxConcurrency = i
  91. }
  92. func (s *composeService) DryRunMode(ctx context.Context, dryRun bool) (context.Context, error) {
  93. s.dryRun = dryRun
  94. if dryRun {
  95. cli, err := command.NewDockerCli()
  96. if err != nil {
  97. return ctx, err
  98. }
  99. options := flags.NewClientOptions()
  100. options.Context = s.dockerCli.CurrentContext()
  101. err = cli.Initialize(options, command.WithInitializeClient(func(cli *command.DockerCli) (client.APIClient, error) {
  102. return api.NewDryRunClient(s.apiClient(), s.dockerCli)
  103. }))
  104. if err != nil {
  105. return ctx, err
  106. }
  107. s.dockerCli = cli
  108. }
  109. return context.WithValue(ctx, api.DryRunKey{}, dryRun), nil
  110. }
  111. func (s *composeService) stdout() *streams.Out {
  112. return s.dockerCli.Out()
  113. }
  114. func (s *composeService) stdin() *streams.In {
  115. return s.dockerCli.In()
  116. }
  117. func (s *composeService) stderr() *streams.Out {
  118. return s.dockerCli.Err()
  119. }
  120. func (s *composeService) stdinfo() *streams.Out {
  121. if stdioToStdout {
  122. return s.dockerCli.Out()
  123. }
  124. return s.dockerCli.Err()
  125. }
  126. func getCanonicalContainerName(c container.Summary) string {
  127. if len(c.Names) == 0 {
  128. // corner case, sometime happens on removal. return short ID as a safeguard value
  129. return c.ID[:12]
  130. }
  131. // Names return container canonical name /foo + link aliases /linked_by/foo
  132. for _, name := range c.Names {
  133. if strings.LastIndex(name, "/") == 0 {
  134. return name[1:]
  135. }
  136. }
  137. return strings.TrimPrefix(c.Names[0], "/")
  138. }
  139. func getContainerNameWithoutProject(c container.Summary) string {
  140. project := c.Labels[api.ProjectLabel]
  141. defaultName := getDefaultContainerName(project, c.Labels[api.ServiceLabel], c.Labels[api.ContainerNumberLabel])
  142. name := getCanonicalContainerName(c)
  143. if name != defaultName {
  144. // service declares a custom container_name
  145. return name
  146. }
  147. return name[len(project)+1:]
  148. }
  149. // projectFromName builds a types.Project based on actual resources with compose labels set
  150. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  151. project := &types.Project{
  152. Name: projectName,
  153. Services: types.Services{},
  154. }
  155. if len(containers) == 0 {
  156. return project, fmt.Errorf("no container found for project %q: %w", projectName, api.ErrNotFound)
  157. }
  158. set := types.Services{}
  159. for _, c := range containers {
  160. serviceLabel, ok := c.Labels[api.ServiceLabel]
  161. if !ok {
  162. serviceLabel = getCanonicalContainerName(c)
  163. }
  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 dependencies != "" {
  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, network.ListOptions{
  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. type runtimeVersionCache struct {
  277. once sync.Once
  278. val string
  279. err error
  280. }
  281. var runtimeVersion runtimeVersionCache
  282. func (s *composeService) RuntimeVersion(ctx context.Context) (string, error) {
  283. runtimeVersion.once.Do(func() {
  284. version, err := s.dockerCli.Client().ServerVersion(ctx)
  285. if err != nil {
  286. runtimeVersion.err = err
  287. }
  288. runtimeVersion.val = version.APIVersion
  289. })
  290. return runtimeVersion.val, runtimeVersion.err
  291. }