publish.go 7.0 KB

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