config.go 11 KB

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