config.go 13 KB

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