config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  252. if err != nil {
  253. return err
  254. }
  255. err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error {
  256. fmt.Fprintln(dockerCli.Out(), serviceName)
  257. return nil
  258. })
  259. return err
  260. }
  261. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  262. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  263. if err != nil {
  264. return err
  265. }
  266. for n := range project.Volumes {
  267. fmt.Fprintln(dockerCli.Out(), n)
  268. }
  269. return nil
  270. }
  271. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  272. var services []string
  273. if opts.hash != "*" {
  274. services = append(services, strings.Split(opts.hash, ",")...)
  275. }
  276. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  277. if err != nil {
  278. return err
  279. }
  280. if err := applyPlatforms(project, true); err != nil {
  281. return err
  282. }
  283. if len(services) == 0 {
  284. services = project.ServiceNames()
  285. }
  286. sorted := services
  287. sort.Slice(sorted, func(i, j int) bool {
  288. return sorted[i] < sorted[j]
  289. })
  290. for _, name := range sorted {
  291. s, err := project.GetService(name)
  292. if err != nil {
  293. return err
  294. }
  295. hash, err := compose.ServiceHash(s)
  296. if err != nil {
  297. return err
  298. }
  299. fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash)
  300. }
  301. return nil
  302. }
  303. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  304. set := map[string]struct{}{}
  305. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  306. if err != nil {
  307. return err
  308. }
  309. for _, s := range project.AllServices() {
  310. for _, p := range s.Profiles {
  311. set[p] = struct{}{}
  312. }
  313. }
  314. profiles := make([]string, 0, len(set))
  315. for p := range set {
  316. profiles = append(profiles, p)
  317. }
  318. sort.Strings(profiles)
  319. for _, p := range profiles {
  320. fmt.Fprintln(dockerCli.Out(), p)
  321. }
  322. return nil
  323. }
  324. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  325. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  326. if err != nil {
  327. return err
  328. }
  329. for _, s := range project.Services {
  330. fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name))
  331. }
  332. return nil
  333. }
  334. func runVariables(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  335. opts.noInterpolate = true
  336. model, err := opts.ToModel(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  337. if err != nil {
  338. return err
  339. }
  340. variables := template.ExtractVariables(model, template.DefaultPattern)
  341. return formatter.Print(variables, "", dockerCli.Out(), func(w io.Writer) {
  342. for name, variable := range variables {
  343. _, _ = fmt.Fprintf(w, "%s\t%t\t%s\t%s\n", name, variable.Required, variable.DefaultValue, variable.PresenceValue)
  344. }
  345. }, "NAME", "REQUIRED", "DEFAULT VALUE", "ALTERNATE VALUE")
  346. }
  347. func runEnvironment(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  348. project, err := opts.ToProject(ctx, dockerCli, services)
  349. if err != nil {
  350. return err
  351. }
  352. for _, v := range project.Environment.Values() {
  353. fmt.Println(v)
  354. }
  355. return nil
  356. }
  357. func escapeDollarSign(marshal []byte) []byte {
  358. dollar := []byte{'$'}
  359. escDollar := []byte{'$', '$'}
  360. return bytes.ReplaceAll(marshal, dollar, escDollar)
  361. }