oci.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 remote
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "github.com/compose-spec/compose-go/v2/loader"
  23. "github.com/distribution/reference"
  24. "github.com/docker/buildx/store/storeutil"
  25. "github.com/docker/buildx/util/imagetools"
  26. "github.com/docker/cli/cli/command"
  27. "github.com/docker/compose/v2/internal/ocipush"
  28. v1 "github.com/opencontainers/image-spec/specs-go/v1"
  29. )
  30. const (
  31. OCI_REMOTE_ENABLED = "COMPOSE_EXPERIMENTAL_OCI_REMOTE"
  32. OciPrefix = "oci://"
  33. )
  34. func ociRemoteLoaderEnabled() (bool, error) {
  35. if v := os.Getenv(OCI_REMOTE_ENABLED); v != "" {
  36. enabled, err := strconv.ParseBool(v)
  37. if err != nil {
  38. return false, fmt.Errorf("COMPOSE_EXPERIMENTAL_OCI_REMOTE environment variable expects boolean value: %w", err)
  39. }
  40. return enabled, err
  41. }
  42. return false, nil
  43. }
  44. func NewOCIRemoteLoader(dockerCli command.Cli, offline bool) loader.ResourceLoader {
  45. return ociRemoteLoader{
  46. dockerCli: dockerCli,
  47. offline: offline,
  48. known: map[string]string{},
  49. }
  50. }
  51. type ociRemoteLoader struct {
  52. dockerCli command.Cli
  53. offline bool
  54. known map[string]string
  55. }
  56. func (g ociRemoteLoader) Accept(path string) bool {
  57. return strings.HasPrefix(path, OciPrefix)
  58. }
  59. func (g ociRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  60. enabled, err := ociRemoteLoaderEnabled()
  61. if err != nil {
  62. return "", err
  63. }
  64. if !enabled {
  65. return "", fmt.Errorf("experimental OCI remote resource is disabled. %q must be set", OCI_REMOTE_ENABLED)
  66. }
  67. if g.offline {
  68. return "", nil
  69. }
  70. local, ok := g.known[path]
  71. if !ok {
  72. ref, err := reference.ParseDockerRef(path[len(OciPrefix):])
  73. if err != nil {
  74. return "", err
  75. }
  76. opt, err := storeutil.GetImageConfig(g.dockerCli, nil)
  77. if err != nil {
  78. return "", err
  79. }
  80. resolver := imagetools.New(opt)
  81. content, descriptor, err := resolver.Get(ctx, ref.String())
  82. if err != nil {
  83. return "", err
  84. }
  85. cache, err := cacheDir()
  86. if err != nil {
  87. return "", fmt.Errorf("initializing remote resource cache: %w", err)
  88. }
  89. local = filepath.Join(cache, descriptor.Digest.Hex())
  90. composeFile := filepath.Join(local, "compose.yaml")
  91. if _, err = os.Stat(local); os.IsNotExist(err) {
  92. var manifest v1.Manifest
  93. err = json.Unmarshal(content, &manifest)
  94. if err != nil {
  95. return "", err
  96. }
  97. err2 := g.pullComposeFiles(ctx, local, composeFile, manifest, ref, resolver)
  98. if err2 != nil {
  99. // we need to clean up the directory to be sure we won't let empty files present
  100. _ = os.RemoveAll(local)
  101. return "", err2
  102. }
  103. }
  104. g.known[path] = local
  105. }
  106. return filepath.Join(local, "compose.yaml"), nil
  107. }
  108. func (g ociRemoteLoader) Dir(path string) string {
  109. return g.known[path]
  110. }
  111. func (g ociRemoteLoader) pullComposeFiles(ctx context.Context, local string, composeFile string, manifest v1.Manifest, ref reference.Named, resolver *imagetools.Resolver) error {
  112. err := os.MkdirAll(local, 0o700)
  113. if err != nil {
  114. return err
  115. }
  116. f, err := os.Create(composeFile)
  117. if err != nil {
  118. return err
  119. }
  120. defer f.Close() //nolint:errcheck
  121. if (manifest.ArtifactType != "" && manifest.ArtifactType != ocipush.ComposeProjectArtifactType) ||
  122. (manifest.ArtifactType == "" && manifest.Config.MediaType != ocipush.ComposeEmptyConfigMediaType) {
  123. return fmt.Errorf("%s is not a compose project OCI artifact, but %s", ref.String(), manifest.ArtifactType)
  124. }
  125. for i, layer := range manifest.Layers {
  126. digested, err := reference.WithDigest(ref, layer.Digest)
  127. if err != nil {
  128. return err
  129. }
  130. content, _, err := resolver.Get(ctx, digested.String())
  131. if err != nil {
  132. return err
  133. }
  134. switch layer.MediaType {
  135. case ocipush.ComposeYAMLMediaType:
  136. if err := writeComposeFile(layer, i, f, content); err != nil {
  137. return err
  138. }
  139. case ocipush.ComposeEnvFileMediaType:
  140. if err := writeEnvFile(layer, local, content); err != nil {
  141. return err
  142. }
  143. case ocipush.ComposeEmptyConfigMediaType:
  144. }
  145. }
  146. return nil
  147. }
  148. func writeComposeFile(layer v1.Descriptor, i int, f *os.File, content []byte) error {
  149. if _, ok := layer.Annotations["com.docker.compose.file"]; i > 0 && ok {
  150. _, err := f.Write([]byte("\n---\n"))
  151. if err != nil {
  152. return err
  153. }
  154. }
  155. _, err := f.Write(content)
  156. return err
  157. }
  158. func writeEnvFile(layer v1.Descriptor, local string, content []byte) error {
  159. envfilePath, ok := layer.Annotations["com.docker.compose.envfile"]
  160. if !ok {
  161. return fmt.Errorf("missing annotation com.docker.compose.envfile in layer %q", layer.Digest)
  162. }
  163. otherFile, err := os.Create(filepath.Join(local, envfilePath))
  164. if err != nil {
  165. return err
  166. }
  167. _, err = otherFile.Write(content)
  168. if err != nil {
  169. return err
  170. }
  171. return nil
  172. }
  173. var _ loader.ResourceLoader = ociRemoteLoader{}