config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. "bytes"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "os"
  21. "sort"
  22. "strings"
  23. "github.com/compose-spec/compose-go/v2/cli"
  24. "github.com/compose-spec/compose-go/v2/template"
  25. "github.com/compose-spec/compose-go/v2/types"
  26. "github.com/docker/cli/cli/command"
  27. "github.com/docker/compose/v2/cmd/formatter"
  28. "github.com/spf13/cobra"
  29. "gopkg.in/yaml.v3"
  30. "github.com/docker/compose/v2/pkg/api"
  31. "github.com/docker/compose/v2/pkg/compose"
  32. )
  33. type configOptions struct {
  34. *ProjectOptions
  35. Format string
  36. Output string
  37. quiet bool
  38. resolveImageDigests bool
  39. noInterpolate bool
  40. noNormalize bool
  41. noResolvePath bool
  42. services bool
  43. volumes bool
  44. profiles bool
  45. images bool
  46. hash string
  47. noConsistency bool
  48. variables bool
  49. }
  50. func (o *configOptions) ToProject(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  51. po = append(po, o.ToProjectOptions()...)
  52. project, _, err := o.ProjectOptions.ToProject(ctx, dockerCli, services, po...)
  53. return project, err
  54. }
  55. func (o *configOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  56. po = append(po, o.ToProjectOptions()...)
  57. return o.ProjectOptions.ToModel(ctx, dockerCli, services, po...)
  58. }
  59. func (o *configOptions) ToProjectOptions() []cli.ProjectOptionsFn {
  60. return []cli.ProjectOptionsFn{
  61. cli.WithInterpolation(!o.noInterpolate),
  62. cli.WithResolvedPaths(!o.noResolvePath),
  63. cli.WithNormalization(!o.noNormalize),
  64. cli.WithConsistency(!o.noConsistency),
  65. cli.WithDefaultProfiles(o.Profiles...),
  66. cli.WithDiscardEnvFile,
  67. }
  68. }
  69. func configCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command {
  70. opts := configOptions{
  71. ProjectOptions: p,
  72. }
  73. cmd := &cobra.Command{
  74. Aliases: []string{"convert"}, // for backward compatibility with Cloud integrations
  75. Use: "config [OPTIONS] [SERVICE...]",
  76. Short: "Parse, resolve and render compose file in canonical format",
  77. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  78. if opts.quiet {
  79. devnull, err := os.Open(os.DevNull)
  80. if err != nil {
  81. return err
  82. }
  83. os.Stdout = devnull
  84. }
  85. if p.Compatibility {
  86. opts.noNormalize = true
  87. }
  88. return nil
  89. }),
  90. RunE: Adapt(func(ctx context.Context, args []string) error {
  91. if opts.services {
  92. return runServices(ctx, dockerCli, opts)
  93. }
  94. if opts.volumes {
  95. return runVolumes(ctx, dockerCli, opts)
  96. }
  97. if opts.hash != "" {
  98. return runHash(ctx, dockerCli, opts)
  99. }
  100. if opts.profiles {
  101. return runProfiles(ctx, dockerCli, opts, args)
  102. }
  103. if opts.images {
  104. return runConfigImages(ctx, dockerCli, opts, args)
  105. }
  106. if opts.variables {
  107. return runVariables(ctx, dockerCli, opts, args)
  108. }
  109. return runConfig(ctx, dockerCli, opts, args)
  110. }),
  111. ValidArgsFunction: completeServiceNames(dockerCli, p),
  112. }
  113. flags := cmd.Flags()
  114. flags.StringVar(&opts.Format, "format", "yaml", "Format the output. Values: [yaml | json]")
  115. flags.BoolVar(&opts.resolveImageDigests, "resolve-image-digests", false, "Pin image tags to digests")
  116. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only validate the configuration, don't print anything")
  117. flags.BoolVar(&opts.noInterpolate, "no-interpolate", false, "Don't interpolate environment variables")
  118. flags.BoolVar(&opts.noNormalize, "no-normalize", false, "Don't normalize compose model")
  119. flags.BoolVar(&opts.noResolvePath, "no-path-resolution", false, "Don't resolve file paths")
  120. flags.BoolVar(&opts.noConsistency, "no-consistency", false, "Don't check model consistency - warning: may produce invalid Compose output")
  121. flags.BoolVar(&opts.services, "services", false, "Print the service names, one per line.")
  122. flags.BoolVar(&opts.volumes, "volumes", false, "Print the volume names, one per line.")
  123. flags.BoolVar(&opts.profiles, "profiles", false, "Print the profile names, one per line.")
  124. flags.BoolVar(&opts.images, "images", false, "Print the image names, one per line.")
  125. flags.StringVar(&opts.hash, "hash", "", "Print the service config hash, one per line.")
  126. flags.BoolVar(&opts.variables, "variables", false, "Print model variables and default values.")
  127. flags.StringVarP(&opts.Output, "output", "o", "", "Save to file (default to stdout)")
  128. return cmd
  129. }
  130. func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  131. var content []byte
  132. if opts.noInterpolate {
  133. // we can't use ToProject, so the model we render here is only partially resolved
  134. model, err := opts.ToModel(ctx, dockerCli, services)
  135. if err != nil {
  136. return err
  137. }
  138. if opts.resolveImageDigests {
  139. err = resolveImageDigests(ctx, dockerCli, model)
  140. if err != nil {
  141. return err
  142. }
  143. }
  144. content, err = formatModel(model, opts.Format)
  145. if err != nil {
  146. return err
  147. }
  148. } else {
  149. project, err := opts.ToProject(ctx, dockerCli, services)
  150. if err != nil {
  151. return err
  152. }
  153. if !opts.noConsistency {
  154. err := project.CheckContainerNameUnicity()
  155. if err != nil {
  156. return err
  157. }
  158. }
  159. switch opts.Format {
  160. case "json":
  161. content, err = project.MarshalJSON()
  162. case "yaml":
  163. content, err = project.MarshalYAML()
  164. default:
  165. return fmt.Errorf("unsupported format %q", opts.Format)
  166. }
  167. if err != nil {
  168. return err
  169. }
  170. }
  171. if !opts.noInterpolate {
  172. content = escapeDollarSign(content)
  173. }
  174. if opts.quiet {
  175. return nil
  176. }
  177. if opts.Output != "" && len(content) > 0 {
  178. return os.WriteFile(opts.Output, content, 0o666)
  179. }
  180. _, err := fmt.Fprint(dockerCli.Out(), string(content))
  181. return err
  182. }
  183. func resolveImageDigests(ctx context.Context, dockerCli command.Cli, model map[string]any) (err error) {
  184. // create a pseudo-project so we can rely on WithImagesResolved to resolve images
  185. p := &types.Project{
  186. Services: types.Services{},
  187. }
  188. services := model["services"].(map[string]any)
  189. for name, s := range services {
  190. service := s.(map[string]any)
  191. if image, ok := service["image"]; ok {
  192. p.Services[name] = types.ServiceConfig{
  193. Image: image.(string),
  194. }
  195. }
  196. }
  197. p, err = p.WithImagesResolved(compose.ImageDigestResolver(ctx, dockerCli.ConfigFile(), dockerCli.Client()))
  198. if err != nil {
  199. return err
  200. }
  201. // Collect image resolved with digest and update model accordingly
  202. for name, s := range services {
  203. service := s.(map[string]any)
  204. config := p.Services[name]
  205. if config.Image != "" {
  206. service["image"] = config.Image
  207. }
  208. services[name] = service
  209. }
  210. model["services"] = services
  211. return nil
  212. }
  213. func formatModel(model map[string]any, format string) (content []byte, err error) {
  214. switch format {
  215. case "json":
  216. content, err = json.MarshalIndent(model, "", " ")
  217. case "yaml":
  218. buf := bytes.NewBuffer([]byte{})
  219. encoder := yaml.NewEncoder(buf)
  220. encoder.SetIndent(2)
  221. err = encoder.Encode(model)
  222. content = buf.Bytes()
  223. default:
  224. return nil, fmt.Errorf("unsupported format %q", format)
  225. }
  226. return
  227. }
  228. func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  229. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  230. if err != nil {
  231. return err
  232. }
  233. err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error {
  234. fmt.Fprintln(dockerCli.Out(), serviceName)
  235. return nil
  236. })
  237. return err
  238. }
  239. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  240. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  241. if err != nil {
  242. return err
  243. }
  244. for n := range project.Volumes {
  245. fmt.Fprintln(dockerCli.Out(), n)
  246. }
  247. return nil
  248. }
  249. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  250. var services []string
  251. if opts.hash != "*" {
  252. services = append(services, strings.Split(opts.hash, ",")...)
  253. }
  254. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  255. if err != nil {
  256. return err
  257. }
  258. if err := applyPlatforms(project, true); err != nil {
  259. return err
  260. }
  261. if len(services) == 0 {
  262. services = project.ServiceNames()
  263. }
  264. sorted := services
  265. sort.Slice(sorted, func(i, j int) bool {
  266. return sorted[i] < sorted[j]
  267. })
  268. for _, name := range sorted {
  269. s, err := project.GetService(name)
  270. if err != nil {
  271. return err
  272. }
  273. hash, err := compose.ServiceHash(s)
  274. if err != nil {
  275. return err
  276. }
  277. fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash)
  278. }
  279. return nil
  280. }
  281. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  282. set := map[string]struct{}{}
  283. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  284. if err != nil {
  285. return err
  286. }
  287. for _, s := range project.AllServices() {
  288. for _, p := range s.Profiles {
  289. set[p] = struct{}{}
  290. }
  291. }
  292. profiles := make([]string, 0, len(set))
  293. for p := range set {
  294. profiles = append(profiles, p)
  295. }
  296. sort.Strings(profiles)
  297. for _, p := range profiles {
  298. fmt.Fprintln(dockerCli.Out(), p)
  299. }
  300. return nil
  301. }
  302. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  303. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  304. if err != nil {
  305. return err
  306. }
  307. for _, s := range project.Services {
  308. fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name))
  309. }
  310. return nil
  311. }
  312. func runVariables(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  313. opts.noInterpolate = true
  314. model, err := opts.ToModel(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  315. if err != nil {
  316. return err
  317. }
  318. variables := template.ExtractVariables(model, template.DefaultPattern)
  319. return formatter.Print(variables, "", dockerCli.Out(), func(w io.Writer) {
  320. for name, variable := range variables {
  321. _, _ = fmt.Fprintf(w, "%s\t%t\t%s\t%s\n", name, variable.Required, variable.DefaultValue, variable.PresenceValue)
  322. }
  323. }, "NAME", "REQUIRED", "DEFAULT VALUE", "ALTERNATE VALUE")
  324. }
  325. func escapeDollarSign(marshal []byte) []byte {
  326. dollar := []byte{'$'}
  327. escDollar := []byte{'$', '$'}
  328. return bytes.ReplaceAll(marshal, dollar, escDollar)
  329. }