convert.go 6.4 KB

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