config.go 14 KB

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