convert.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 bridge
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "os"
  19. "os/user"
  20. "path/filepath"
  21. "strconv"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/docker/cli/cli/command"
  24. cli "github.com/docker/cli/cli/command/container"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/docker/compose/v2/pkg/utils"
  27. "github.com/docker/docker/api/types/container"
  28. "github.com/docker/docker/api/types/image"
  29. "github.com/docker/docker/api/types/network"
  30. "github.com/docker/docker/errdefs"
  31. "github.com/docker/docker/pkg/jsonmessage"
  32. "gopkg.in/yaml.v3"
  33. )
  34. type ConvertOptions struct {
  35. Output string
  36. Templates string
  37. Transformations []string
  38. }
  39. func Convert(ctx context.Context, dockerCli command.Cli, project *types.Project, opts ConvertOptions) error {
  40. if len(opts.Transformations) == 0 {
  41. opts.Transformations = []string{DefaultTransformerImage}
  42. }
  43. // Load image references, secrets and configs, also expose ports
  44. project, err := LoadAdditionalResources(ctx, dockerCli, project)
  45. if err != nil {
  46. return err
  47. }
  48. // for user to rely on compose.yaml attribute names, not go struct ones, we marshall back into YAML
  49. raw, err := project.MarshalYAML(types.WithSecretContent)
  50. // Marshall to YAML
  51. if err != nil {
  52. return fmt.Errorf("cannot render project into yaml: %w", err)
  53. }
  54. var model map[string]any
  55. err = yaml.Unmarshal(raw, &model)
  56. if err != nil {
  57. return fmt.Errorf("cannot render project into yaml: %w", err)
  58. }
  59. if opts.Output != "" {
  60. _ = os.RemoveAll(opts.Output)
  61. err := os.MkdirAll(opts.Output, 0o744)
  62. if err != nil && !os.IsExist(err) {
  63. return fmt.Errorf("cannot create output folder: %w", err)
  64. }
  65. }
  66. // Run Transformers images
  67. return convert(ctx, dockerCli, model, opts)
  68. }
  69. func convert(ctx context.Context, dockerCli command.Cli, model map[string]any, opts ConvertOptions) error {
  70. raw, err := yaml.Marshal(model)
  71. if err != nil {
  72. return err
  73. }
  74. dir := os.TempDir()
  75. composeYaml := filepath.Join(dir, "compose.yaml")
  76. err = os.WriteFile(composeYaml, raw, 0o600)
  77. if err != nil {
  78. return err
  79. }
  80. out, err := filepath.Abs(opts.Output)
  81. if err != nil {
  82. return err
  83. }
  84. binds := []string{
  85. fmt.Sprintf("%s:%s", dir, "/in"),
  86. fmt.Sprintf("%s:%s", out, "/out"),
  87. }
  88. if opts.Templates != "" {
  89. templateDir, err := filepath.Abs(opts.Templates)
  90. if err != nil {
  91. return err
  92. }
  93. binds = append(binds, fmt.Sprintf("%s:%s", templateDir, "/templates"))
  94. }
  95. for _, transformation := range opts.Transformations {
  96. _, err = inspectWithPull(ctx, dockerCli, transformation)
  97. if err != nil {
  98. return err
  99. }
  100. user, err := user.Current()
  101. if err != nil {
  102. return err
  103. }
  104. created, err := dockerCli.Client().ContainerCreate(ctx, &container.Config{
  105. Image: transformation,
  106. Env: []string{"LICENSE_AGREEMENT=true"},
  107. User: user.Uid,
  108. }, &container.HostConfig{
  109. AutoRemove: true,
  110. Binds: binds,
  111. }, &network.NetworkingConfig{}, nil, "")
  112. if err != nil {
  113. return err
  114. }
  115. err = cli.RunStart(ctx, dockerCli, &cli.StartOptions{
  116. Attach: true,
  117. Containers: []string{created.ID},
  118. })
  119. if err != nil {
  120. return err
  121. }
  122. }
  123. return nil
  124. }
  125. // LoadAdditionalResources loads additional resources from the project, such as image references, secrets, configs and exposed ports
  126. func LoadAdditionalResources(ctx context.Context, cli command.Cli, project *types.Project) (*types.Project, error) {
  127. for name, service := range project.Services {
  128. imageName := api.GetImageNameOrDefault(service, project.Name)
  129. inspect, err := inspectWithPull(ctx, cli, imageName)
  130. if err != nil {
  131. return nil, err
  132. }
  133. service.Image = imageName
  134. exposed := utils.Set[string]{}
  135. exposed.AddAll(service.Expose...)
  136. for port := range inspect.Config.ExposedPorts {
  137. exposed.Add(port.Port())
  138. }
  139. for _, port := range service.Ports {
  140. exposed.Add(strconv.Itoa(int(port.Target)))
  141. }
  142. service.Expose = exposed.Elements()
  143. project.Services[name] = service
  144. }
  145. for name, secret := range project.Secrets {
  146. f, err := loadFileObject(types.FileObjectConfig(secret))
  147. if err != nil {
  148. return nil, err
  149. }
  150. project.Secrets[name] = types.SecretConfig(f)
  151. }
  152. for name, config := range project.Configs {
  153. f, err := loadFileObject(types.FileObjectConfig(config))
  154. if err != nil {
  155. return nil, err
  156. }
  157. project.Configs[name] = types.ConfigObjConfig(f)
  158. }
  159. return project, nil
  160. }
  161. func loadFileObject(conf types.FileObjectConfig) (types.FileObjectConfig, error) {
  162. if !conf.External {
  163. switch {
  164. case conf.Environment != "":
  165. conf.Content = os.Getenv(conf.Environment)
  166. case conf.File != "":
  167. bytes, err := os.ReadFile(conf.File)
  168. if err != nil {
  169. return conf, err
  170. }
  171. conf.Content = string(bytes)
  172. }
  173. }
  174. return conf, nil
  175. }
  176. func inspectWithPull(ctx context.Context, dockerCli command.Cli, imageName string) (image.InspectResponse, error) {
  177. inspect, err := dockerCli.Client().ImageInspect(ctx, imageName)
  178. if errdefs.IsNotFound(err) {
  179. var stream io.ReadCloser
  180. stream, err = dockerCli.Client().ImagePull(ctx, imageName, image.PullOptions{})
  181. if err != nil {
  182. return image.InspectResponse{}, err
  183. }
  184. defer func() { _ = stream.Close() }()
  185. err = jsonmessage.DisplayJSONMessagesToStream(stream, dockerCli.Out(), nil)
  186. if err != nil {
  187. return image.InspectResponse{}, err
  188. }
  189. if inspect, err = dockerCli.Client().ImageInspect(ctx, imageName); err != nil {
  190. return image.InspectResponse{}, err
  191. }
  192. }
  193. return inspect, err
  194. }