publish.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 compose
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "github.com/compose-spec/compose-go/v2/types"
  19. "github.com/distribution/reference"
  20. "github.com/docker/buildx/util/imagetools"
  21. "github.com/docker/cli/cli/command"
  22. "github.com/docker/compose/v2/internal/ocipush"
  23. "github.com/docker/compose/v2/pkg/api"
  24. "github.com/docker/compose/v2/pkg/progress"
  25. "github.com/docker/compose/v2/pkg/prompt"
  26. )
  27. func (s *composeService) Publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error {
  28. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  29. return s.publish(ctx, project, repository, options)
  30. }, s.stdinfo(), "Publishing")
  31. }
  32. func (s *composeService) publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error {
  33. accept, err := s.preChecks(project, options)
  34. if err != nil {
  35. return err
  36. }
  37. if !accept {
  38. return nil
  39. }
  40. err = s.Push(ctx, project, api.PushOptions{IgnoreFailures: true, ImageMandatory: true})
  41. if err != nil {
  42. return err
  43. }
  44. named, err := reference.ParseDockerRef(repository)
  45. if err != nil {
  46. return err
  47. }
  48. resolver := imagetools.New(imagetools.Opt{
  49. Auth: s.configFile(),
  50. })
  51. var layers []ocipush.Pushable
  52. for _, file := range project.ComposeFiles {
  53. f, err := os.ReadFile(file)
  54. if err != nil {
  55. return err
  56. }
  57. layerDescriptor := ocipush.DescriptorForComposeFile(file, f)
  58. layers = append(layers, ocipush.Pushable{
  59. Descriptor: layerDescriptor,
  60. Data: f,
  61. })
  62. }
  63. if options.WithEnvironment {
  64. layers = append(layers, envFileLayers(project)...)
  65. }
  66. if options.ResolveImageDigests {
  67. yaml, err := s.generateImageDigestsOverride(ctx, project)
  68. if err != nil {
  69. return err
  70. }
  71. layerDescriptor := ocipush.DescriptorForComposeFile("image-digests.yaml", yaml)
  72. layers = append(layers, ocipush.Pushable{
  73. Descriptor: layerDescriptor,
  74. Data: yaml,
  75. })
  76. }
  77. w := progress.ContextWriter(ctx)
  78. w.Event(progress.Event{
  79. ID: repository,
  80. Text: "publishing",
  81. Status: progress.Working,
  82. })
  83. if !s.dryRun {
  84. err = ocipush.PushManifest(ctx, resolver, named, layers, options.OCIVersion)
  85. if err != nil {
  86. w.Event(progress.Event{
  87. ID: repository,
  88. Text: "publishing",
  89. Status: progress.Error,
  90. })
  91. return err
  92. }
  93. }
  94. w.Event(progress.Event{
  95. ID: repository,
  96. Text: "published",
  97. Status: progress.Done,
  98. })
  99. return nil
  100. }
  101. func (s *composeService) generateImageDigestsOverride(ctx context.Context, project *types.Project) ([]byte, error) {
  102. project, err := project.WithProfiles([]string{"*"})
  103. if err != nil {
  104. return nil, err
  105. }
  106. project, err = project.WithImagesResolved(ImageDigestResolver(ctx, s.configFile(), s.apiClient()))
  107. if err != nil {
  108. return nil, err
  109. }
  110. override := types.Project{
  111. Services: types.Services{},
  112. }
  113. for name, service := range project.Services {
  114. override.Services[name] = types.ServiceConfig{
  115. Image: service.Image,
  116. }
  117. }
  118. return override.MarshalYAML()
  119. }
  120. func (s *composeService) preChecks(project *types.Project, options api.PublishOptions) (bool, error) {
  121. envVariables, err := s.checkEnvironmentVariables(project, options)
  122. if err != nil {
  123. return false, err
  124. }
  125. if !options.AssumeYes && len(envVariables) > 0 {
  126. fmt.Println("you are about to publish environment variables within your OCI artifact.\n" +
  127. "please double check that you are not leaking sensitive data")
  128. for key, val := range envVariables {
  129. _, _ = fmt.Fprintln(s.dockerCli.Out(), "Service/Config ", key)
  130. for k, v := range val {
  131. _, _ = fmt.Fprintf(s.dockerCli.Out(), "%s=%v\n", k, *v)
  132. }
  133. }
  134. return acceptPublishEnvVariables(s.dockerCli)
  135. }
  136. return true, nil
  137. }
  138. func (s *composeService) checkEnvironmentVariables(project *types.Project, options api.PublishOptions) (map[string]types.MappingWithEquals, error) {
  139. envVarList := map[string]types.MappingWithEquals{}
  140. errorList := map[string][]string{}
  141. for _, service := range project.Services {
  142. if len(service.EnvFiles) > 0 {
  143. errorList[service.Name] = append(errorList[service.Name], fmt.Sprintf("service %q has env_file declared.", service.Name))
  144. }
  145. if len(service.Environment) > 0 {
  146. errorList[service.Name] = append(errorList[service.Name], fmt.Sprintf("service %q has environment variable(s) declared.", service.Name))
  147. envVarList[service.Name] = service.Environment
  148. }
  149. }
  150. for _, config := range project.Configs {
  151. if config.Environment != "" {
  152. errorList[config.Name] = append(errorList[config.Name], fmt.Sprintf("config %q is declare as an environment variable.", config.Name))
  153. envVarList[config.Name] = types.NewMappingWithEquals([]string{fmt.Sprintf("%s=%s", config.Name, config.Environment)})
  154. }
  155. }
  156. if !options.WithEnvironment && len(errorList) > 0 {
  157. errorMsgSuffix := "To avoid leaking sensitive data, you must either explicitly allow the sending of environment variables by using the --with-env flag,\n" +
  158. "or remove sensitive data from your Compose configuration"
  159. errorMsg := ""
  160. for _, errors := range errorList {
  161. for _, err := range errors {
  162. errorMsg += fmt.Sprintf("%s\n", err)
  163. }
  164. }
  165. return nil, fmt.Errorf("%s%s", errorMsg, errorMsgSuffix)
  166. }
  167. return envVarList, nil
  168. }
  169. func acceptPublishEnvVariables(cli command.Cli) (bool, error) {
  170. msg := "Are you ok to publish these environment variables? [y/N]: "
  171. confirm, err := prompt.NewPrompt(cli.In(), cli.Out()).Confirm(msg, false)
  172. return confirm, err
  173. }
  174. func envFileLayers(project *types.Project) []ocipush.Pushable {
  175. var layers []ocipush.Pushable
  176. for _, service := range project.Services {
  177. for _, envFile := range service.EnvFiles {
  178. f, err := os.ReadFile(envFile.Path)
  179. if err != nil {
  180. // if we can't read the file, skip to the next one
  181. continue
  182. }
  183. layerDescriptor := ocipush.DescriptorForEnvFile(envFile.Path, f)
  184. layers = append(layers, ocipush.Pushable{
  185. Descriptor: layerDescriptor,
  186. Data: f,
  187. })
  188. }
  189. }
  190. return layers
  191. }