config.go 12 KB

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