ps.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 cmd
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "text/tabwriter"
  19. "github.com/pkg/errors"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/api/cli/formatter"
  22. "github.com/docker/api/client"
  23. formatter2 "github.com/docker/api/formatter"
  24. )
  25. type psOpts struct {
  26. all bool
  27. quiet bool
  28. json bool
  29. }
  30. func (o psOpts) validate() error {
  31. if o.quiet && o.json {
  32. return errors.New(`cannot combine "quiet" and "json" options`)
  33. }
  34. return nil
  35. }
  36. // PsCommand lists containers
  37. func PsCommand() *cobra.Command {
  38. var opts psOpts
  39. cmd := &cobra.Command{
  40. Use: "ps",
  41. Short: "List containers",
  42. RunE: func(cmd *cobra.Command, args []string) error {
  43. return runPs(cmd.Context(), opts)
  44. },
  45. }
  46. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
  47. cmd.Flags().BoolVarP(&opts.all, "all", "a", false, "Show all containers (default shows just running)")
  48. cmd.Flags().BoolVar(&opts.json, "json", false, "Format output as JSON")
  49. return cmd
  50. }
  51. func runPs(ctx context.Context, opts psOpts) error {
  52. err := opts.validate()
  53. if err != nil {
  54. return err
  55. }
  56. c, err := client.New(ctx)
  57. if err != nil {
  58. return errors.Wrap(err, "cannot connect to backend")
  59. }
  60. containers, err := c.ContainerService().List(ctx, opts.all)
  61. if err != nil {
  62. return errors.Wrap(err, "fetch containers")
  63. }
  64. if opts.quiet {
  65. for _, c := range containers {
  66. fmt.Println(c.ID)
  67. }
  68. return nil
  69. }
  70. if opts.json {
  71. j, err := formatter2.ToStandardJSON(containers)
  72. if err != nil {
  73. return err
  74. }
  75. fmt.Println(j)
  76. return nil
  77. }
  78. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  79. fmt.Fprintf(w, "CONTAINER ID\tIMAGE\tCOMMAND\tSTATUS\tPORTS\n")
  80. format := "%s\t%s\t%s\t%s\t%s\n"
  81. for _, c := range containers {
  82. fmt.Fprintf(w, format, c.ID, c.Image, c.Command, c.Status, formatter.PortsString(c.Ports))
  83. }
  84. return w.Flush()
  85. }