convert.go 6.2 KB

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