config.go 9.6 KB

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