convert.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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/moby/moby/api/types/container"
  28. "github.com/moby/moby/api/types/image"
  29. "github.com/moby/moby/api/types/network"
  30. "github.com/moby/moby/client"
  31. "github.com/moby/moby/client/pkg/jsonmessage"
  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, client.ContainerCreateOptions{
  126. Config: containerConfig,
  127. HostConfig: &container.HostConfig{
  128. Binds: binds,
  129. AutoRemove: true,
  130. },
  131. NetworkingConfig: &network.NetworkingConfig{},
  132. })
  133. if err != nil {
  134. return err
  135. }
  136. err = cli.RunStart(ctx, dockerCli, &cli.StartOptions{
  137. Attach: true,
  138. Containers: []string{created.ID},
  139. })
  140. if err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. // LoadAdditionalResources loads additional resources from the project, such as image references, secrets, configs and exposed ports
  147. func LoadAdditionalResources(ctx context.Context, dockerCLI command.Cli, project *types.Project) (*types.Project, error) {
  148. for name, service := range project.Services {
  149. imageName := api.GetImageNameOrDefault(service, project.Name)
  150. inspect, err := inspectWithPull(ctx, dockerCLI, imageName)
  151. if err != nil {
  152. return nil, err
  153. }
  154. service.Image = imageName
  155. exposed := utils.Set[string]{}
  156. exposed.AddAll(service.Expose...)
  157. for port := range inspect.Config.ExposedPorts {
  158. p, err := network.ParsePort(port)
  159. if err != nil {
  160. return nil, err
  161. }
  162. exposed.Add(strconv.Itoa(int(p.Num())))
  163. }
  164. for _, port := range service.Ports {
  165. exposed.Add(strconv.Itoa(int(port.Target)))
  166. }
  167. service.Expose = exposed.Elements()
  168. project.Services[name] = service
  169. }
  170. for name, secret := range project.Secrets {
  171. f, err := loadFileObject(types.FileObjectConfig(secret))
  172. if err != nil {
  173. return nil, err
  174. }
  175. project.Secrets[name] = types.SecretConfig(f)
  176. }
  177. for name, config := range project.Configs {
  178. f, err := loadFileObject(types.FileObjectConfig(config))
  179. if err != nil {
  180. return nil, err
  181. }
  182. project.Configs[name] = types.ConfigObjConfig(f)
  183. }
  184. return project, nil
  185. }
  186. func loadFileObject(conf types.FileObjectConfig) (types.FileObjectConfig, error) {
  187. if !conf.External {
  188. switch {
  189. case conf.Environment != "":
  190. conf.Content = os.Getenv(conf.Environment)
  191. case conf.File != "":
  192. bytes, err := os.ReadFile(conf.File)
  193. if err != nil {
  194. return conf, err
  195. }
  196. conf.Content = string(bytes)
  197. }
  198. }
  199. return conf, nil
  200. }
  201. func inspectWithPull(ctx context.Context, dockerCli command.Cli, imageName string) (image.InspectResponse, error) {
  202. inspect, err := dockerCli.Client().ImageInspect(ctx, imageName)
  203. if errdefs.IsNotFound(err) {
  204. var stream io.ReadCloser
  205. stream, err = dockerCli.Client().ImagePull(ctx, imageName, client.ImagePullOptions{})
  206. if err != nil {
  207. return image.InspectResponse{}, err
  208. }
  209. defer func() { _ = stream.Close() }()
  210. out := dockerCli.Out()
  211. err = jsonmessage.DisplayJSONMessagesStream(stream, out, out.FD(), out.IsTerminal(), nil)
  212. if err != nil {
  213. return image.InspectResponse{}, err
  214. }
  215. if inspect, err = dockerCli.Client().ImageInspect(ctx, imageName); err != nil {
  216. return image.InspectResponse{}, err
  217. }
  218. }
  219. return inspect.InspectResponse, err
  220. }