compose.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. "bytes"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "strings"
  21. "github.com/compose-spec/compose-go/types"
  22. "github.com/docker/cli/cli/command"
  23. "github.com/docker/cli/cli/config/configfile"
  24. "github.com/docker/cli/cli/streams"
  25. "github.com/docker/compose/v2/pkg/api"
  26. moby "github.com/docker/docker/api/types"
  27. "github.com/docker/docker/api/types/filters"
  28. "github.com/docker/docker/client"
  29. "github.com/pkg/errors"
  30. "github.com/sanathkr/go-yaml"
  31. )
  32. // Separator is used for naming components
  33. var Separator = "-"
  34. // NewComposeService create a local implementation of the compose.Service API
  35. func NewComposeService(dockerCli command.Cli) api.Service {
  36. return &composeService{
  37. dockerCli: dockerCli,
  38. }
  39. }
  40. type composeService struct {
  41. dockerCli command.Cli
  42. }
  43. func (s *composeService) apiClient() client.APIClient {
  44. return s.dockerCli.Client()
  45. }
  46. func (s *composeService) configFile() *configfile.ConfigFile {
  47. return s.dockerCli.ConfigFile()
  48. }
  49. func (s *composeService) stdout() *streams.Out {
  50. return s.dockerCli.Out()
  51. }
  52. func (s *composeService) stdin() *streams.In {
  53. return s.dockerCli.In()
  54. }
  55. func (s *composeService) stderr() io.Writer {
  56. return s.dockerCli.Err()
  57. }
  58. func getCanonicalContainerName(c moby.Container) string {
  59. if len(c.Names) == 0 {
  60. // corner case, sometime happens on removal. return short ID as a safeguard value
  61. return c.ID[:12]
  62. }
  63. // Names return container canonical name /foo + link aliases /linked_by/foo
  64. for _, name := range c.Names {
  65. if strings.LastIndex(name, "/") == 0 {
  66. return name[1:]
  67. }
  68. }
  69. return c.Names[0][1:]
  70. }
  71. func getContainerNameWithoutProject(c moby.Container) string {
  72. name := getCanonicalContainerName(c)
  73. project := c.Labels[api.ProjectLabel]
  74. prefix := fmt.Sprintf("%s_%s_", project, c.Labels[api.ServiceLabel])
  75. if strings.HasPrefix(name, prefix) {
  76. return name[len(project)+1:]
  77. }
  78. return name
  79. }
  80. func (s *composeService) Convert(ctx context.Context, project *types.Project, options api.ConvertOptions) ([]byte, error) {
  81. switch options.Format {
  82. case "json":
  83. marshal, err := json.MarshalIndent(project, "", " ")
  84. if err != nil {
  85. return nil, err
  86. }
  87. return escapeDollarSign(marshal), nil
  88. case "yaml":
  89. marshal, err := yaml.Marshal(project)
  90. if err != nil {
  91. return nil, err
  92. }
  93. return escapeDollarSign(marshal), nil
  94. default:
  95. return nil, fmt.Errorf("unsupported format %q", options)
  96. }
  97. }
  98. func escapeDollarSign(marshal []byte) []byte {
  99. dollar := []byte{'$'}
  100. escDollar := []byte{'$', '$'}
  101. return bytes.ReplaceAll(marshal, dollar, escDollar)
  102. }
  103. // projectFromName builds a types.Project based on actual resources with compose labels set
  104. func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) {
  105. project := &types.Project{
  106. Name: projectName,
  107. }
  108. if len(containers) == 0 {
  109. return project, errors.Wrap(api.ErrNotFound, fmt.Sprintf("no container found for project %q", projectName))
  110. }
  111. set := map[string]*types.ServiceConfig{}
  112. for _, c := range containers {
  113. serviceLabel := c.Labels[api.ServiceLabel]
  114. _, ok := set[serviceLabel]
  115. if !ok {
  116. set[serviceLabel] = &types.ServiceConfig{
  117. Name: serviceLabel,
  118. Image: c.Image,
  119. Labels: c.Labels,
  120. }
  121. }
  122. set[serviceLabel].Scale++
  123. }
  124. for _, service := range set {
  125. dependencies := service.Labels[api.DependenciesLabel]
  126. if len(dependencies) > 0 {
  127. service.DependsOn = types.DependsOnConfig{}
  128. for _, dc := range strings.Split(dependencies, ",") {
  129. dcArr := strings.Split(dc, ":")
  130. condition := ServiceConditionRunningOrHealthy
  131. dependency := dcArr[0]
  132. // backward compatibility
  133. if len(dcArr) > 1 {
  134. condition = dcArr[1]
  135. }
  136. service.DependsOn[dependency] = types.ServiceDependency{Condition: condition}
  137. }
  138. }
  139. project.Services = append(project.Services, *service)
  140. }
  141. SERVICES:
  142. for _, qs := range services {
  143. for _, es := range project.Services {
  144. if es.Name == qs {
  145. continue SERVICES
  146. }
  147. }
  148. return project, errors.Wrapf(api.ErrNotFound, "no such service: %q", qs)
  149. }
  150. err := project.ForServices(services)
  151. if err != nil {
  152. return project, err
  153. }
  154. return project, nil
  155. }
  156. // actualState list resources labelled by projectName to rebuild compose project model
  157. func (s *composeService) actualState(ctx context.Context, projectName string, services []string) (Containers, *types.Project, error) {
  158. var containers Containers
  159. // don't filter containers by options.Services so projectFromName can rebuild project with all existing resources
  160. containers, err := s.getContainers(ctx, projectName, oneOffInclude, true)
  161. if err != nil {
  162. return nil, nil, err
  163. }
  164. project, err := s.projectFromName(containers, projectName, services...)
  165. if err != nil && !api.IsNotFoundError(err) {
  166. return nil, nil, err
  167. }
  168. if len(services) > 0 {
  169. containers = containers.filter(isService(services...))
  170. }
  171. return containers, project, nil
  172. }
  173. func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) {
  174. volumes, err := s.apiClient().VolumeList(ctx, filters.NewArgs(projectFilter(projectName)))
  175. if err != nil {
  176. return nil, err
  177. }
  178. actual := types.Volumes{}
  179. for _, vol := range volumes.Volumes {
  180. actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{
  181. Name: vol.Name,
  182. Driver: vol.Driver,
  183. Labels: vol.Labels,
  184. }
  185. }
  186. return actual, nil
  187. }
  188. func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) {
  189. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  190. Filters: filters.NewArgs(projectFilter(projectName)),
  191. })
  192. if err != nil {
  193. return nil, err
  194. }
  195. actual := types.Networks{}
  196. for _, net := range networks {
  197. actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{
  198. Name: net.Name,
  199. Driver: net.Driver,
  200. Labels: net.Labels,
  201. }
  202. }
  203. return actual, nil
  204. }