config.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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/spf13/cobra"
  28. "go.yaml.in/yaml/v4"
  29. "github.com/docker/compose/v5/cmd/formatter"
  30. "github.com/docker/compose/v5/pkg/api"
  31. "github.com/docker/compose/v5/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. noResolveEnv bool
  43. services bool
  44. volumes bool
  45. networks bool
  46. models bool
  47. profiles bool
  48. images bool
  49. hash string
  50. noConsistency bool
  51. variables bool
  52. environment bool
  53. lockImageDigests bool
  54. }
  55. func (o *configOptions) ToProject(ctx context.Context, dockerCli command.Cli, backend api.Compose, services []string) (*types.Project, error) {
  56. project, _, err := o.ProjectOptions.ToProject(ctx, dockerCli, backend, services, o.toProjectOptionsFns()...)
  57. return project, err
  58. }
  59. func (o *configOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  60. po = append(po, o.toProjectOptionsFns()...)
  61. return o.ProjectOptions.ToModel(ctx, dockerCli, services, po...)
  62. }
  63. // toProjectOptionsFns converts config options to cli.ProjectOptionsFn
  64. func (o *configOptions) toProjectOptionsFns() []cli.ProjectOptionsFn {
  65. fns := []cli.ProjectOptionsFn{
  66. cli.WithInterpolation(!o.noInterpolate),
  67. cli.WithResolvedPaths(!o.noResolvePath),
  68. cli.WithNormalization(!o.noNormalize),
  69. cli.WithConsistency(!o.noConsistency),
  70. cli.WithDefaultProfiles(o.Profiles...),
  71. cli.WithDiscardEnvFile,
  72. }
  73. if o.noResolveEnv {
  74. fns = append(fns, cli.WithoutEnvironmentResolution)
  75. }
  76. return fns
  77. }
  78. func configCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command {
  79. opts := configOptions{
  80. ProjectOptions: p,
  81. }
  82. cmd := &cobra.Command{
  83. Use: "config [OPTIONS] [SERVICE...]",
  84. Short: "Parse, resolve and render compose file in canonical format",
  85. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  86. if opts.quiet {
  87. devnull, err := os.Open(os.DevNull)
  88. if err != nil {
  89. return err
  90. }
  91. os.Stdout = devnull
  92. }
  93. if p.Compatibility {
  94. opts.noNormalize = true
  95. }
  96. if opts.lockImageDigests {
  97. opts.resolveImageDigests = true
  98. }
  99. return nil
  100. }),
  101. RunE: Adapt(func(ctx context.Context, args []string) error {
  102. if opts.services {
  103. return runServices(ctx, dockerCli, opts)
  104. }
  105. if opts.volumes {
  106. return runVolumes(ctx, dockerCli, opts)
  107. }
  108. if opts.networks {
  109. return runNetworks(ctx, dockerCli, opts)
  110. }
  111. if opts.models {
  112. return runModels(ctx, dockerCli, opts)
  113. }
  114. if opts.hash != "" {
  115. return runHash(ctx, dockerCli, opts)
  116. }
  117. if opts.profiles {
  118. return runProfiles(ctx, dockerCli, opts, args)
  119. }
  120. if opts.images {
  121. return runConfigImages(ctx, dockerCli, opts, args)
  122. }
  123. if opts.variables {
  124. return runVariables(ctx, dockerCli, opts, args)
  125. }
  126. if opts.environment {
  127. return runEnvironment(ctx, dockerCli, opts, args)
  128. }
  129. if opts.Format == "" {
  130. opts.Format = "yaml"
  131. }
  132. return runConfig(ctx, dockerCli, opts, args)
  133. }),
  134. ValidArgsFunction: completeServiceNames(dockerCli, p),
  135. }
  136. flags := cmd.Flags()
  137. flags.StringVar(&opts.Format, "format", "", "Format the output. Values: [yaml | json]")
  138. flags.BoolVar(&opts.resolveImageDigests, "resolve-image-digests", false, "Pin image tags to digests")
  139. flags.BoolVar(&opts.lockImageDigests, "lock-image-digests", false, "Produces an override file with image digests")
  140. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only validate the configuration, don't print anything")
  141. flags.BoolVar(&opts.noInterpolate, "no-interpolate", false, "Don't interpolate environment variables")
  142. flags.BoolVar(&opts.noNormalize, "no-normalize", false, "Don't normalize compose model")
  143. flags.BoolVar(&opts.noResolvePath, "no-path-resolution", false, "Don't resolve file paths")
  144. flags.BoolVar(&opts.noConsistency, "no-consistency", false, "Don't check model consistency - warning: may produce invalid Compose output")
  145. flags.BoolVar(&opts.noResolveEnv, "no-env-resolution", false, "Don't resolve service env files")
  146. flags.BoolVar(&opts.services, "services", false, "Print the service names, one per line.")
  147. flags.BoolVar(&opts.volumes, "volumes", false, "Print the volume names, one per line.")
  148. flags.BoolVar(&opts.networks, "networks", false, "Print the network names, one per line.")
  149. flags.BoolVar(&opts.models, "models", false, "Print the model names, one per line.")
  150. flags.BoolVar(&opts.profiles, "profiles", false, "Print the profile names, one per line.")
  151. flags.BoolVar(&opts.images, "images", false, "Print the image names, one per line.")
  152. flags.StringVar(&opts.hash, "hash", "", "Print the service config hash, one per line.")
  153. flags.BoolVar(&opts.variables, "variables", false, "Print model variables and default values.")
  154. flags.BoolVar(&opts.environment, "environment", false, "Print environment used for interpolation.")
  155. flags.StringVarP(&opts.Output, "output", "o", "", "Save to file (default to stdout)")
  156. return cmd
  157. }
  158. func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) (err error) {
  159. var content []byte
  160. if opts.noInterpolate {
  161. content, err = runConfigNoInterpolate(ctx, dockerCli, opts, services)
  162. if err != nil {
  163. return err
  164. }
  165. } else {
  166. content, err = runConfigInterpolate(ctx, dockerCli, opts, services)
  167. if err != nil {
  168. return err
  169. }
  170. }
  171. if !opts.noInterpolate {
  172. content = escapeDollarSign(content)
  173. }
  174. if opts.quiet {
  175. return nil
  176. }
  177. if opts.Output != "" && len(content) > 0 {
  178. return os.WriteFile(opts.Output, content, 0o666)
  179. }
  180. _, err = fmt.Fprint(dockerCli.Out(), string(content))
  181. return err
  182. }
  183. func runConfigInterpolate(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) ([]byte, error) {
  184. backend, err := compose.NewComposeService(dockerCli)
  185. if err != nil {
  186. return nil, err
  187. }
  188. project, err := opts.ToProject(ctx, dockerCli, backend, services)
  189. if err != nil {
  190. return nil, err
  191. }
  192. if opts.resolveImageDigests {
  193. project, err = project.WithImagesResolved(compose.ImageDigestResolver(ctx, dockerCli.ConfigFile(), dockerCli.Client()))
  194. if err != nil {
  195. return nil, err
  196. }
  197. }
  198. if !opts.noResolveEnv {
  199. project, err = project.WithServicesEnvironmentResolved(true)
  200. if err != nil {
  201. return nil, err
  202. }
  203. }
  204. if !opts.noConsistency {
  205. err := project.CheckContainerNameUnicity()
  206. if err != nil {
  207. return nil, err
  208. }
  209. }
  210. if opts.lockImageDigests {
  211. project = imagesOnly(project)
  212. }
  213. var content []byte
  214. switch opts.Format {
  215. case "json":
  216. content, err = project.MarshalJSON()
  217. case "yaml":
  218. content, err = project.MarshalYAML()
  219. default:
  220. return nil, fmt.Errorf("unsupported format %q", opts.Format)
  221. }
  222. if err != nil {
  223. return nil, err
  224. }
  225. return content, nil
  226. }
  227. // imagesOnly return project with all attributes removed but service.images
  228. func imagesOnly(project *types.Project) *types.Project {
  229. digests := types.Services{}
  230. for name, config := range project.Services {
  231. digests[name] = types.ServiceConfig{
  232. Image: config.Image,
  233. }
  234. }
  235. project = &types.Project{Services: digests}
  236. return project
  237. }
  238. func runConfigNoInterpolate(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) ([]byte, error) {
  239. // we can't use ToProject, so the model we render here is only partially resolved
  240. model, err := opts.ToModel(ctx, dockerCli, services)
  241. if err != nil {
  242. return nil, err
  243. }
  244. if opts.resolveImageDigests {
  245. err = resolveImageDigests(ctx, dockerCli, model)
  246. if err != nil {
  247. return nil, err
  248. }
  249. }
  250. if opts.lockImageDigests {
  251. for key, e := range model {
  252. if key != "services" {
  253. delete(model, key)
  254. } else {
  255. for _, s := range e.(map[string]any) {
  256. service := s.(map[string]any)
  257. for key := range service {
  258. if key != "image" {
  259. delete(service, key)
  260. }
  261. }
  262. }
  263. }
  264. }
  265. }
  266. return formatModel(model, opts.Format)
  267. }
  268. func resolveImageDigests(ctx context.Context, dockerCli command.Cli, model map[string]any) (err error) {
  269. // create a pseudo-project so we can rely on WithImagesResolved to resolve images
  270. p := &types.Project{
  271. Services: types.Services{},
  272. }
  273. services := model["services"].(map[string]any)
  274. for name, s := range services {
  275. service := s.(map[string]any)
  276. if image, ok := service["image"]; ok {
  277. p.Services[name] = types.ServiceConfig{
  278. Image: image.(string),
  279. }
  280. }
  281. }
  282. p, err = p.WithImagesResolved(compose.ImageDigestResolver(ctx, dockerCli.ConfigFile(), dockerCli.Client()))
  283. if err != nil {
  284. return err
  285. }
  286. // Collect image resolved with digest and update model accordingly
  287. for name, s := range services {
  288. service := s.(map[string]any)
  289. config := p.Services[name]
  290. if config.Image != "" {
  291. service["image"] = config.Image
  292. }
  293. services[name] = service
  294. }
  295. model["services"] = services
  296. return nil
  297. }
  298. func formatModel(model map[string]any, format string) (content []byte, err error) {
  299. switch format {
  300. case "json":
  301. return json.MarshalIndent(model, "", " ")
  302. case "yaml":
  303. buf := bytes.NewBuffer([]byte{})
  304. encoder := yaml.NewEncoder(buf)
  305. encoder.SetIndent(2)
  306. err = encoder.Encode(model)
  307. return buf.Bytes(), err
  308. default:
  309. return nil, fmt.Errorf("unsupported format %q", format)
  310. }
  311. }
  312. func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  313. if opts.noInterpolate {
  314. // we can't use ToProject, so the model we render here is only partially resolved
  315. data, err := opts.ToModel(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  316. if err != nil {
  317. return err
  318. }
  319. if _, ok := data["services"]; ok {
  320. for serviceName := range data["services"].(map[string]any) {
  321. _, _ = fmt.Fprintln(dockerCli.Out(), serviceName)
  322. }
  323. }
  324. return nil
  325. }
  326. backend, err := compose.NewComposeService(dockerCli)
  327. if err != nil {
  328. return err
  329. }
  330. project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution)
  331. if err != nil {
  332. return err
  333. }
  334. err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error {
  335. _, _ = fmt.Fprintln(dockerCli.Out(), serviceName)
  336. return nil
  337. })
  338. return err
  339. }
  340. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  341. backend, err := compose.NewComposeService(dockerCli)
  342. if err != nil {
  343. return err
  344. }
  345. project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution)
  346. if err != nil {
  347. return err
  348. }
  349. for n := range project.Volumes {
  350. _, _ = fmt.Fprintln(dockerCli.Out(), n)
  351. }
  352. return nil
  353. }
  354. func runNetworks(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  355. backend, err := compose.NewComposeService(dockerCli)
  356. if err != nil {
  357. return err
  358. }
  359. project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution)
  360. if err != nil {
  361. return err
  362. }
  363. for n := range project.Networks {
  364. _, _ = fmt.Fprintln(dockerCli.Out(), n)
  365. }
  366. return nil
  367. }
  368. func runModels(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  369. backend, err := compose.NewComposeService(dockerCli)
  370. if err != nil {
  371. return err
  372. }
  373. project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution)
  374. if err != nil {
  375. return err
  376. }
  377. for _, model := range project.Models {
  378. if model.Model != "" {
  379. _, _ = fmt.Fprintln(dockerCli.Out(), model.Model)
  380. }
  381. }
  382. return nil
  383. }
  384. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  385. var services []string
  386. if opts.hash != "*" {
  387. services = append(services, strings.Split(opts.hash, ",")...)
  388. }
  389. backend, err := compose.NewComposeService(dockerCli)
  390. if err != nil {
  391. return err
  392. }
  393. project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution)
  394. if err != nil {
  395. return err
  396. }
  397. if err := applyPlatforms(project, true); err != nil {
  398. return err
  399. }
  400. if len(services) == 0 {
  401. services = project.ServiceNames()
  402. }
  403. sorted := services
  404. sort.Slice(sorted, func(i, j int) bool {
  405. return sorted[i] < sorted[j]
  406. })
  407. for _, name := range sorted {
  408. s, err := project.GetService(name)
  409. if err != nil {
  410. return err
  411. }
  412. hash, err := compose.ServiceHash(s)
  413. if err != nil {
  414. return err
  415. }
  416. _, _ = fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash)
  417. }
  418. return nil
  419. }
  420. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  421. set := map[string]struct{}{}
  422. backend, err := compose.NewComposeService(dockerCli)
  423. if err != nil {
  424. return err
  425. }
  426. project, err := opts.ToProject(ctx, dockerCli, backend, services)
  427. if err != nil {
  428. return err
  429. }
  430. for _, s := range project.AllServices() {
  431. for _, p := range s.Profiles {
  432. set[p] = struct{}{}
  433. }
  434. }
  435. profiles := make([]string, 0, len(set))
  436. for p := range set {
  437. profiles = append(profiles, p)
  438. }
  439. sort.Strings(profiles)
  440. for _, p := range profiles {
  441. _, _ = fmt.Fprintln(dockerCli.Out(), p)
  442. }
  443. return nil
  444. }
  445. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  446. backend, err := compose.NewComposeService(dockerCli)
  447. if err != nil {
  448. return err
  449. }
  450. project, err := opts.ToProject(ctx, dockerCli, backend, services)
  451. if err != nil {
  452. return err
  453. }
  454. for _, s := range project.Services {
  455. _, _ = fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name))
  456. }
  457. return nil
  458. }
  459. func runVariables(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  460. opts.noInterpolate = true
  461. model, err := opts.ToModel(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  462. if err != nil {
  463. return err
  464. }
  465. variables := template.ExtractVariables(model, template.DefaultPattern)
  466. if opts.Format == "yaml" {
  467. result, err := yaml.Marshal(variables)
  468. if err != nil {
  469. return err
  470. }
  471. fmt.Print(string(result))
  472. return nil
  473. }
  474. return formatter.Print(variables, opts.Format, dockerCli.Out(), func(w io.Writer) {
  475. for name, variable := range variables {
  476. _, _ = fmt.Fprintf(w, "%s\t%t\t%s\t%s\n", name, variable.Required, variable.DefaultValue, variable.PresenceValue)
  477. }
  478. }, "NAME", "REQUIRED", "DEFAULT VALUE", "ALTERNATE VALUE")
  479. }
  480. func runEnvironment(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  481. backend, err := compose.NewComposeService(dockerCli)
  482. if err != nil {
  483. return err
  484. }
  485. project, err := opts.ToProject(ctx, dockerCli, backend, services)
  486. if err != nil {
  487. return err
  488. }
  489. for _, v := range project.Environment.Values() {
  490. fmt.Println(v)
  491. }
  492. return nil
  493. }
  494. func escapeDollarSign(marshal []byte) []byte {
  495. dollar := []byte{'$'}
  496. escDollar := []byte{'$', '$'}
  497. return bytes.ReplaceAll(marshal, dollar, escDollar)
  498. }