config.go 13 KB

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