config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. switch opts.Format {
  154. case "json":
  155. content, err = project.MarshalJSON()
  156. case "yaml":
  157. content, err = project.MarshalYAML()
  158. default:
  159. return fmt.Errorf("unsupported format %q", opts.Format)
  160. }
  161. if err != nil {
  162. return err
  163. }
  164. }
  165. if !opts.noInterpolate {
  166. content = escapeDollarSign(content)
  167. }
  168. if opts.quiet {
  169. return nil
  170. }
  171. if opts.Output != "" && len(content) > 0 {
  172. return os.WriteFile(opts.Output, content, 0o666)
  173. }
  174. _, err := fmt.Fprint(dockerCli.Out(), string(content))
  175. return err
  176. }
  177. func resolveImageDigests(ctx context.Context, dockerCli command.Cli, model map[string]any) (err error) {
  178. // create a pseudo-project so we can rely on WithImagesResolved to resolve images
  179. p := &types.Project{
  180. Services: types.Services{},
  181. }
  182. services := model["services"].(map[string]any)
  183. for name, s := range services {
  184. service := s.(map[string]any)
  185. if image, ok := service["image"]; ok {
  186. p.Services[name] = types.ServiceConfig{
  187. Image: image.(string),
  188. }
  189. }
  190. }
  191. p, err = p.WithImagesResolved(compose.ImageDigestResolver(ctx, dockerCli.ConfigFile(), dockerCli.Client()))
  192. if err != nil {
  193. return err
  194. }
  195. // Collect image resolved with digest and update model accordingly
  196. for name, s := range services {
  197. service := s.(map[string]any)
  198. config := p.Services[name]
  199. if config.Image != "" {
  200. service["image"] = config.Image
  201. }
  202. services[name] = service
  203. }
  204. model["services"] = services
  205. return nil
  206. }
  207. func formatModel(model map[string]any, format string) (content []byte, err error) {
  208. switch format {
  209. case "json":
  210. content, err = json.MarshalIndent(model, "", " ")
  211. case "yaml":
  212. buf := bytes.NewBuffer([]byte{})
  213. encoder := yaml.NewEncoder(buf)
  214. encoder.SetIndent(2)
  215. err = encoder.Encode(model)
  216. content = buf.Bytes()
  217. default:
  218. return nil, fmt.Errorf("unsupported format %q", format)
  219. }
  220. return
  221. }
  222. func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  223. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  224. if err != nil {
  225. return err
  226. }
  227. err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error {
  228. fmt.Fprintln(dockerCli.Out(), serviceName)
  229. return nil
  230. })
  231. return err
  232. }
  233. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  234. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  235. if err != nil {
  236. return err
  237. }
  238. for n := range project.Volumes {
  239. fmt.Fprintln(dockerCli.Out(), n)
  240. }
  241. return nil
  242. }
  243. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  244. var services []string
  245. if opts.hash != "*" {
  246. services = append(services, strings.Split(opts.hash, ",")...)
  247. }
  248. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  249. if err != nil {
  250. return err
  251. }
  252. if err := applyPlatforms(project, true); err != nil {
  253. return err
  254. }
  255. if len(services) == 0 {
  256. services = project.ServiceNames()
  257. }
  258. sorted := services
  259. sort.Slice(sorted, func(i, j int) bool {
  260. return sorted[i] < sorted[j]
  261. })
  262. for _, name := range sorted {
  263. s, err := project.GetService(name)
  264. if err != nil {
  265. return err
  266. }
  267. hash, err := compose.ServiceHash(s)
  268. if err != nil {
  269. return err
  270. }
  271. fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash)
  272. }
  273. return nil
  274. }
  275. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  276. set := map[string]struct{}{}
  277. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  278. if err != nil {
  279. return err
  280. }
  281. for _, s := range project.AllServices() {
  282. for _, p := range s.Profiles {
  283. set[p] = struct{}{}
  284. }
  285. }
  286. profiles := make([]string, 0, len(set))
  287. for p := range set {
  288. profiles = append(profiles, p)
  289. }
  290. sort.Strings(profiles)
  291. for _, p := range profiles {
  292. fmt.Fprintln(dockerCli.Out(), p)
  293. }
  294. return nil
  295. }
  296. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  297. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  298. if err != nil {
  299. return err
  300. }
  301. for _, s := range project.Services {
  302. fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name))
  303. }
  304. return nil
  305. }
  306. func runVariables(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  307. opts.noInterpolate = true
  308. model, err := opts.ToModel(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  309. if err != nil {
  310. return err
  311. }
  312. variables := template.ExtractVariables(model, template.DefaultPattern)
  313. return formatter.Print(variables, "", dockerCli.Out(), func(w io.Writer) {
  314. for name, variable := range variables {
  315. _, _ = fmt.Fprintf(w, "%s\t%t\t%s\t%s\n", name, variable.Required, variable.DefaultValue, variable.PresenceValue)
  316. }
  317. }, "NAME", "REQUIRED", "DEFAULT VALUE", "ALTERNATE VALUE")
  318. }
  319. func escapeDollarSign(marshal []byte) []byte {
  320. dollar := []byte{'$'}
  321. escDollar := []byte{'$', '$'}
  322. return bytes.ReplaceAll(marshal, dollar, escDollar)
  323. }