options.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. Copyright 2023 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. "io"
  18. "os"
  19. "sort"
  20. "strings"
  21. "text/tabwriter"
  22. "github.com/compose-spec/compose-go/v2/cli"
  23. "github.com/compose-spec/compose-go/v2/template"
  24. "github.com/compose-spec/compose-go/v2/types"
  25. "github.com/docker/cli/cli/command"
  26. ui "github.com/docker/compose/v2/pkg/progress"
  27. "github.com/docker/compose/v2/pkg/prompt"
  28. "github.com/docker/compose/v2/pkg/utils"
  29. )
  30. func applyPlatforms(project *types.Project, buildForSinglePlatform bool) error {
  31. defaultPlatform := project.Environment["DOCKER_DEFAULT_PLATFORM"]
  32. for name, service := range project.Services {
  33. if service.Build == nil {
  34. continue
  35. }
  36. // default platform only applies if the service doesn't specify
  37. if defaultPlatform != "" && service.Platform == "" {
  38. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, defaultPlatform) {
  39. return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", name, defaultPlatform)
  40. }
  41. service.Platform = defaultPlatform
  42. }
  43. if service.Platform != "" {
  44. if len(service.Build.Platforms) > 0 {
  45. if !utils.StringContains(service.Build.Platforms, service.Platform) {
  46. return fmt.Errorf("service %q build configuration does not support platform: %s", name, service.Platform)
  47. }
  48. }
  49. if buildForSinglePlatform || len(service.Build.Platforms) == 0 {
  50. // if we're building for a single platform, we want to build for the platform we'll use to run the image
  51. // similarly, if no build platforms were explicitly specified, it makes sense to build for the platform
  52. // the image is designed for rather than allowing the builder to infer the platform
  53. service.Build.Platforms = []string{service.Platform}
  54. }
  55. }
  56. // services can specify that they should be built for multiple platforms, which can be used
  57. // with `docker compose build` to produce a multi-arch image
  58. // other cases, such as `up` and `run`, need a single architecture to actually run
  59. // if there is only a single platform present (which might have been inferred
  60. // from service.Platform above), it will be used, even if it requires emulation.
  61. // if there's more than one platform, then the list is cleared so that the builder
  62. // can decide.
  63. // TODO(milas): there's no validation that the platform the builder will pick is actually one
  64. // of the supported platforms from the build definition
  65. // e.g. `build.platforms: [linux/arm64, linux/amd64]` on a `linux/ppc64` machine would build
  66. // for `linux/ppc64` instead of returning an error that it's not a valid platform for the service.
  67. if buildForSinglePlatform && len(service.Build.Platforms) > 1 {
  68. // empty indicates that the builder gets to decide
  69. service.Build.Platforms = nil
  70. }
  71. project.Services[name] = service
  72. }
  73. return nil
  74. }
  75. // isRemoteConfig checks if the main compose file is from a remote source (OCI or Git)
  76. func isRemoteConfig(dockerCli command.Cli, options buildOptions) bool {
  77. if len(options.ConfigPaths) == 0 {
  78. return false
  79. }
  80. remoteLoaders := options.remoteLoaders(dockerCli)
  81. for _, loader := range remoteLoaders {
  82. if loader.Accept(options.ConfigPaths[0]) {
  83. return true
  84. }
  85. }
  86. return false
  87. }
  88. // checksForRemoteStack handles environment variable prompts for remote configurations
  89. func checksForRemoteStack(ctx context.Context, dockerCli command.Cli, project *types.Project, options buildOptions, assumeYes bool, cmdEnvs []string) error {
  90. if !isRemoteConfig(dockerCli, options) {
  91. return nil
  92. }
  93. displayLocationRemoteStack(dockerCli, project, options)
  94. return promptForInterpolatedVariables(ctx, dockerCli, options.ProjectOptions, assumeYes, cmdEnvs)
  95. }
  96. // Prepare the values map and collect all variables info
  97. type varInfo struct {
  98. name string
  99. value string
  100. source string
  101. required bool
  102. defaultValue string
  103. }
  104. // promptForInterpolatedVariables displays all variables and their values at once,
  105. // then prompts for confirmation
  106. func promptForInterpolatedVariables(ctx context.Context, dockerCli command.Cli, projectOptions *ProjectOptions, assumeYes bool, cmdEnvs []string) error {
  107. if assumeYes {
  108. return nil
  109. }
  110. varsInfo, noVariables, err := extractInterpolationVariablesFromModel(ctx, dockerCli, projectOptions, cmdEnvs)
  111. if err != nil {
  112. return err
  113. }
  114. if noVariables {
  115. return nil
  116. }
  117. displayInterpolationVariables(dockerCli.Out(), varsInfo)
  118. // Prompt for confirmation
  119. userInput := prompt.NewPrompt(dockerCli.In(), dockerCli.Out())
  120. msg := "\nDo you want to proceed with these variables? [Y/n]: "
  121. confirmed, err := userInput.Confirm(msg, true)
  122. if err != nil {
  123. return err
  124. }
  125. if !confirmed {
  126. return fmt.Errorf("operation cancelled by user")
  127. }
  128. return nil
  129. }
  130. func extractInterpolationVariablesFromModel(ctx context.Context, dockerCli command.Cli, projectOptions *ProjectOptions, cmdEnvs []string) ([]varInfo, bool, error) {
  131. cmdEnvMap := extractEnvCLIDefined(cmdEnvs)
  132. // Create a model without interpolation to extract variables
  133. opts := configOptions{
  134. noInterpolate: true,
  135. ProjectOptions: projectOptions,
  136. }
  137. model, err := opts.ToModel(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  138. if err != nil {
  139. return nil, false, err
  140. }
  141. // Extract variables that need interpolation
  142. variables := template.ExtractVariables(model, template.DefaultPattern)
  143. if len(variables) == 0 {
  144. return nil, true, nil
  145. }
  146. var varsInfo []varInfo
  147. proposedValues := make(map[string]string)
  148. for name, variable := range variables {
  149. info := varInfo{
  150. name: name,
  151. required: variable.Required,
  152. defaultValue: variable.DefaultValue,
  153. }
  154. // Determine value and source based on priority
  155. if value, exists := cmdEnvMap[name]; exists {
  156. info.value = value
  157. info.source = "command-line"
  158. proposedValues[name] = value
  159. } else if value, exists := os.LookupEnv(name); exists {
  160. info.value = value
  161. info.source = "environment"
  162. proposedValues[name] = value
  163. } else if variable.DefaultValue != "" {
  164. info.value = variable.DefaultValue
  165. info.source = "compose file"
  166. proposedValues[name] = variable.DefaultValue
  167. } else {
  168. info.value = "<unset>"
  169. info.source = "none"
  170. }
  171. varsInfo = append(varsInfo, info)
  172. }
  173. return varsInfo, false, nil
  174. }
  175. func extractEnvCLIDefined(cmdEnvs []string) map[string]string {
  176. // Parse command-line environment variables
  177. cmdEnvMap := make(map[string]string)
  178. for _, env := range cmdEnvs {
  179. parts := strings.SplitN(env, "=", 2)
  180. if len(parts) == 2 {
  181. cmdEnvMap[parts[0]] = parts[1]
  182. }
  183. }
  184. return cmdEnvMap
  185. }
  186. func displayInterpolationVariables(writer io.Writer, varsInfo []varInfo) {
  187. // Display all variables in a table format
  188. _, _ = fmt.Fprintln(writer, "\nFound the following variables in configuration:")
  189. w := tabwriter.NewWriter(writer, 0, 0, 3, ' ', 0)
  190. _, _ = fmt.Fprintln(w, "VARIABLE\tVALUE\tSOURCE\tREQUIRED\tDEFAULT")
  191. sort.Slice(varsInfo, func(a, b int) bool {
  192. return varsInfo[a].name < varsInfo[b].name
  193. })
  194. for _, info := range varsInfo {
  195. required := "no"
  196. if info.required {
  197. required = "yes"
  198. }
  199. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n",
  200. info.name,
  201. info.value,
  202. info.source,
  203. required,
  204. info.defaultValue,
  205. )
  206. }
  207. _ = w.Flush()
  208. }
  209. func displayLocationRemoteStack(dockerCli command.Cli, project *types.Project, options buildOptions) {
  210. mainComposeFile := options.ProjectOptions.ConfigPaths[0]
  211. if ui.Mode != ui.ModeQuiet && ui.Mode != ui.ModeJSON {
  212. _, _ = fmt.Fprintf(dockerCli.Out(), "Your compose stack %q is stored in %q\n", mainComposeFile, project.WorkingDir)
  213. }
  214. }