inspect.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package service
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/cli"
  7. "github.com/docker/docker/cli/command"
  8. "github.com/docker/docker/cli/command/formatter"
  9. apiclient "github.com/docker/docker/client"
  10. "github.com/spf13/cobra"
  11. )
  12. type inspectOptions struct {
  13. refs []string
  14. format string
  15. pretty bool
  16. }
  17. func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command {
  18. var opts inspectOptions
  19. cmd := &cobra.Command{
  20. Use: "inspect [OPTIONS] SERVICE [SERVICE...]",
  21. Short: "Display detailed information on one or more services",
  22. Args: cli.RequiresMinArgs(1),
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. opts.refs = args
  25. if opts.pretty && len(opts.format) > 0 {
  26. return fmt.Errorf("--format is incompatible with human friendly format")
  27. }
  28. return runInspect(dockerCli, opts)
  29. },
  30. }
  31. flags := cmd.Flags()
  32. flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
  33. flags.BoolVar(&opts.pretty, "pretty", false, "Print the information in a human friendly format.")
  34. return cmd
  35. }
  36. func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
  37. client := dockerCli.Client()
  38. ctx := context.Background()
  39. if opts.pretty {
  40. opts.format = "pretty"
  41. }
  42. getRef := func(ref string) (interface{}, []byte, error) {
  43. service, _, err := client.ServiceInspectWithRaw(ctx, ref)
  44. if err == nil || !apiclient.IsErrServiceNotFound(err) {
  45. return service, nil, err
  46. }
  47. return nil, nil, fmt.Errorf("Error: no such service: %s", ref)
  48. }
  49. f := opts.format
  50. if len(f) == 0 {
  51. f = "raw"
  52. if len(dockerCli.ConfigFile().ServiceInspectFormat) > 0 {
  53. f = dockerCli.ConfigFile().ServiceInspectFormat
  54. }
  55. }
  56. // check if the user is trying to apply a template to the pretty format, which
  57. // is not supported
  58. if strings.HasPrefix(f, "pretty") && f != "pretty" {
  59. return fmt.Errorf("Cannot supply extra formatting options to the pretty template")
  60. }
  61. serviceCtx := formatter.Context{
  62. Output: dockerCli.Out(),
  63. Format: formatter.NewServiceFormat(f),
  64. }
  65. if err := formatter.ServiceInspectWrite(serviceCtx, opts.refs, getRef); err != nil {
  66. return cli.StatusError{StatusCode: 1, Status: err.Error()}
  67. }
  68. return nil
  69. }