config.go 12 KB

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