config.go 9.1 KB

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