compose.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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/sirupsen/logrus"
  35. "github.com/docker/compose/v2/pkg/api"
  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. type Option func(service *composeService)
  45. // NewComposeService create a local implementation of the compose.Compose API
  46. func NewComposeService(dockerCli command.Cli, options ...Option) api.Compose {
  47. s := &composeService{
  48. dockerCli: dockerCli,
  49. clock: clockwork.NewRealClock(),
  50. maxConcurrency: -1,
  51. dryRun: false,
  52. }
  53. for _, option := range options {
  54. option(s)
  55. }
  56. if s.prompt == nil {
  57. s.prompt = func(message string, defaultValue bool) (bool, error) {
  58. fmt.Println(message)
  59. logrus.Warning("Compose is running without a 'prompt' component to interact with user")
  60. return defaultValue, nil
  61. }
  62. }
  63. return s
  64. }
  65. // WithPrompt configure a UI component for Compose service to interact with user and confirm actions
  66. func WithPrompt(prompt Prompt) Option {
  67. return func(s *composeService) {
  68. s.prompt = prompt
  69. }
  70. }
  71. type Prompt func(message string, defaultValue bool) (bool, error)
  72. type composeService struct {
  73. dockerCli command.Cli
  74. // prompt is used to interact with user and confirm actions
  75. prompt Prompt
  76. clock clockwork.Clock
  77. maxConcurrency int
  78. dryRun bool
  79. }
  80. // Close releases any connections/resources held by the underlying clients.
  81. //
  82. // In practice, this service has the same lifetime as the process, so everything
  83. // will get cleaned up at about the same time regardless even if not invoked.
  84. func (s *composeService) Close() error {
  85. var errs []error
  86. if s.dockerCli != nil {
  87. errs = append(errs, s.apiClient().Close())
  88. }
  89. return errors.Join(errs...)
  90. }
  91. func (s *composeService) apiClient() client.APIClient {
  92. return s.dockerCli.Client()
  93. }
  94. func (s *composeService) configFile() *configfile.ConfigFile {
  95. return s.dockerCli.ConfigFile()
  96. }
  97. func (s *composeService) MaxConcurrency(i int) {
  98. s.maxConcurrency = i
  99. }
  100. func (s *composeService) DryRunMode(ctx context.Context, dryRun bool) (context.Context, error) {
  101. s.dryRun = dryRun
  102. if dryRun {
  103. cli, err := command.NewDockerCli()
  104. if err != nil {
  105. return ctx, err
  106. }
  107. options := flags.NewClientOptions()
  108. options.Context = s.dockerCli.CurrentContext()
  109. err = cli.Initialize(options, command.WithInitializeClient(func(cli *command.DockerCli) (client.APIClient, error) {
  110. return api.NewDryRunClient(s.apiClient(), s.dockerCli)
  111. }))
  112. if err != nil {
  113. return ctx, err
  114. }
  115. s.dockerCli = cli
  116. }
  117. return context.WithValue(ctx, api.DryRunKey{}, dryRun), nil
  118. }
  119. func (s *composeService) stdout() *streams.Out {
  120. return s.dockerCli.Out()
  121. }
  122. func (s *composeService) stdin() *streams.In {
  123. return s.dockerCli.In()
  124. }
  125. func (s *composeService) stderr() *streams.Out {
  126. return s.dockerCli.Err()
  127. }
  128. func (s *composeService) stdinfo() *streams.Out {
  129. if stdioToStdout {
  130. return s.dockerCli.Out()
  131. }
  132. return s.dockerCli.Err()
  133. }
  134. func getCanonicalContainerName(c container.Summary) string {
  135. if len(c.Names) == 0 {
  136. // corner case, sometime happens on removal. return short ID as a safeguard value
  137. return c.ID[:12]
  138. }
  139. // Names return container canonical name /foo + link aliases /linked_by/foo
  140. for _, name := range c.Names {
  141. if strings.LastIndex(name, "/") == 0 {
  142. return name[1:]
  143. }
  144. }
  145. return strings.TrimPrefix(c.Names[0], "/")
  146. }
  147. func getContainerNameWithoutProject(c container.Summary) string {
  148. project := c.Labels[api.ProjectLabel]
  149. defaultName := getDefaultContainerName(project, c.Labels[api.ServiceLabel], c.Labels[api.ContainerNumberLabel])
  150. name := getCanonicalContainerName(c)
  151. if name != defaultName {
  152. // service declares a custom container_name
  153. return name
  154. }
  155. return name[len(project)+1:]
  156. }
  157. // projectFromName builds a types.Project based on actual resources with compose labels set
  158. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  159. project := &types.Project{
  160. Name: projectName,
  161. Services: types.Services{},
  162. }
  163. if len(containers) == 0 {
  164. return project, fmt.Errorf("no container found for project %q: %w", projectName, api.ErrNotFound)
  165. }
  166. set := types.Services{}
  167. for _, c := range containers {
  168. serviceLabel, ok := c.Labels[api.ServiceLabel]
  169. if !ok {
  170. serviceLabel = getCanonicalContainerName(c)
  171. }
  172. service, ok := set[serviceLabel]
  173. if !ok {
  174. service = types.ServiceConfig{
  175. Name: serviceLabel,
  176. Image: c.Image,
  177. Labels: c.Labels,
  178. }
  179. }
  180. service.Scale = increment(service.Scale)
  181. set[serviceLabel] = service
  182. }
  183. for name, service := range set {
  184. dependencies := service.Labels[api.DependenciesLabel]
  185. if dependencies != "" {
  186. service.DependsOn = types.DependsOnConfig{}
  187. for _, dc := range strings.Split(dependencies, ",") {
  188. dcArr := strings.Split(dc, ":")
  189. condition := ServiceConditionRunningOrHealthy
  190. // Let's restart the dependency by default if we don't have the info stored in the label
  191. restart := true
  192. required := true
  193. dependency := dcArr[0]
  194. // backward compatibility
  195. if len(dcArr) > 1 {
  196. condition = dcArr[1]
  197. if len(dcArr) > 2 {
  198. restart, _ = strconv.ParseBool(dcArr[2])
  199. }
  200. }
  201. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required}
  202. }
  203. set[name] = service
  204. }
  205. }
  206. project.Services = set
  207. SERVICES:
  208. for _, qs := range services {
  209. for _, es := range project.Services {
  210. if es.Name == qs {
  211. continue SERVICES
  212. }
  213. }
  214. return project, fmt.Errorf("no such service: %q: %w", qs, api.ErrNotFound)
  215. }
  216. project, err := project.WithSelectedServices(services)
  217. if err != nil {
  218. return project, err
  219. }
  220. return project, nil
  221. }
  222. func increment(scale *int) *int {
  223. i := 1
  224. if scale != nil {
  225. i = *scale + 1
  226. }
  227. return &i
  228. }
  229. func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) {
  230. opts := volume.ListOptions{
  231. Filters: filters.NewArgs(projectFilter(projectName)),
  232. }
  233. volumes, err := s.apiClient().VolumeList(ctx, opts)
  234. if err != nil {
  235. return nil, err
  236. }
  237. actual := types.Volumes{}
  238. for _, vol := range volumes.Volumes {
  239. actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{
  240. Name: vol.Name,
  241. Driver: vol.Driver,
  242. Labels: vol.Labels,
  243. }
  244. }
  245. return actual, nil
  246. }
  247. func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) {
  248. networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{
  249. Filters: filters.NewArgs(projectFilter(projectName)),
  250. })
  251. if err != nil {
  252. return nil, err
  253. }
  254. actual := types.Networks{}
  255. for _, net := range networks {
  256. actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{
  257. Name: net.Name,
  258. Driver: net.Driver,
  259. Labels: net.Labels,
  260. }
  261. }
  262. return actual, nil
  263. }
  264. var swarmEnabled = struct {
  265. once sync.Once
  266. val bool
  267. err error
  268. }{}
  269. func (s *composeService) isSWarmEnabled(ctx context.Context) (bool, error) {
  270. swarmEnabled.once.Do(func() {
  271. info, err := s.apiClient().Info(ctx)
  272. if err != nil {
  273. swarmEnabled.err = err
  274. }
  275. switch info.Swarm.LocalNodeState {
  276. case swarm.LocalNodeStateInactive, swarm.LocalNodeStateLocked:
  277. swarmEnabled.val = false
  278. default:
  279. swarmEnabled.val = true
  280. }
  281. })
  282. return swarmEnabled.val, swarmEnabled.err
  283. }
  284. type runtimeVersionCache struct {
  285. once sync.Once
  286. val string
  287. err error
  288. }
  289. var runtimeVersion runtimeVersionCache
  290. func (s *composeService) RuntimeVersion(ctx context.Context) (string, error) {
  291. runtimeVersion.once.Do(func() {
  292. version, err := s.apiClient().ServerVersion(ctx)
  293. if err != nil {
  294. runtimeVersion.err = err
  295. }
  296. runtimeVersion.val = version.APIVersion
  297. })
  298. return runtimeVersion.val, runtimeVersion.err
  299. }